X86: silence sign comparison warning
[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 <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
524   }
525
526   // There's never any support for operations beyond MVT::f32.
527   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
531
532   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
536
537   if (Subtarget->hasPOPCNT()) {
538     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
539   } else {
540     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
541     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
543     if (Subtarget->is64Bit())
544       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
545   }
546
547   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
548
549   if (!Subtarget->hasMOVBE())
550     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
551
552   // These should be promoted to a larger select which is supported.
553   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
554   // X86 wants to expand cmov itself.
555   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
556   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
561   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
567   if (Subtarget->is64Bit()) {
568     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
569     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
570   }
571   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
572   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574   // support continuation, user-level threading, and etc.. As a result, no
575   // other SjLj exception interfaces are implemented and please don't build
576   // your own exception handling based on them.
577   // LLVM/Clang supports zero-cost DWARF exception handling.
578   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
580
581   // Darwin ABI issue.
582   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
583   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
584   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
586   if (Subtarget->is64Bit())
587     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
589   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
592     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
593     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
594     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
595     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
596   }
597   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
599   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
601   if (Subtarget->is64Bit()) {
602     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
603     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
605   }
606
607   if (Subtarget->hasSSE1())
608     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
609
610   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
611
612   // Expand certain atomics
613   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
614     MVT VT = IntVTs[i];
615     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
618   }
619
620   if (Subtarget->hasCmpxchg16b()) {
621     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
622   }
623
624   // FIXME - use subtarget debug flags
625   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
628   }
629
630   if (Subtarget->is64Bit()) {
631     setExceptionPointerRegister(X86::RAX);
632     setExceptionSelectorRegister(X86::RDX);
633   } else {
634     setExceptionPointerRegister(X86::EAX);
635     setExceptionSelectorRegister(X86::EDX);
636   }
637   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
639
640   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
642
643   setOperationAction(ISD::TRAP, MVT::Other, Legal);
644   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
645
646   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
648   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
649   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650     // TargetInfo::X86_64ABIBuiltinVaList
651     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
652     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
653   } else {
654     // TargetInfo::CharPtrBuiltinVaList
655     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
656     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
657   }
658
659   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
660   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
661
662   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
663                      MVT::i64 : MVT::i32, 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 means 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     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1015     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1016     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1017     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1018     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1019     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1020
1021     if (Subtarget->is64Bit()) {
1022       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1023       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1024     }
1025
1026     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1027     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1028       MVT VT = (MVT::SimpleValueType)i;
1029
1030       // Do not attempt to promote non-128-bit vectors
1031       if (!VT.is128BitVector())
1032         continue;
1033
1034       setOperationAction(ISD::AND,    VT, Promote);
1035       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1036       setOperationAction(ISD::OR,     VT, Promote);
1037       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1038       setOperationAction(ISD::XOR,    VT, Promote);
1039       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1040       setOperationAction(ISD::LOAD,   VT, Promote);
1041       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1042       setOperationAction(ISD::SELECT, VT, Promote);
1043       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1044     }
1045
1046     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1047
1048     // Custom lower v2i64 and v2f64 selects.
1049     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1050     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1051     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1052     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1053
1054     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1055     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1056
1057     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1058     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1059     // As there is no 64-bit GPR available, we need build a special custom
1060     // sequence to convert from v2i32 to v2f32.
1061     if (!Subtarget->is64Bit())
1062       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1063
1064     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1065     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1066
1067     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1068
1069     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1070     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1071     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1072   }
1073
1074   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1075     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1076     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1077     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1078     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1079     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1080     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1081     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1082     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1083     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1084     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1085
1086     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1087     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1088     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1089     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1090     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1091     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1092     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1093     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1094     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1095     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1096
1097     // FIXME: Do we need to handle scalar-to-vector here?
1098     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1099
1100     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1101     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1102     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1103     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1104     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1105     // There is no BLENDI for byte vectors. We don't need to custom lower
1106     // some vselects for now.
1107     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1108
1109     // i8 and i16 vectors are custom , because the source register and source
1110     // source memory operand types are not the same width.  f32 vectors are
1111     // custom since the immediate controlling the insert encodes additional
1112     // information.
1113     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1114     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1115     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1116     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1117
1118     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1119     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1120     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1121     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1122
1123     // FIXME: these should be Legal but thats only for the case where
1124     // the index is constant.  For now custom expand to deal with that.
1125     if (Subtarget->is64Bit()) {
1126       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1127       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1128     }
1129   }
1130
1131   if (Subtarget->hasSSE2()) {
1132     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1133     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1134
1135     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1136     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1137
1138     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1139     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1140
1141     // In the customized shift lowering, the legal cases in AVX2 will be
1142     // recognized.
1143     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1144     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1145
1146     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1147     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1148
1149     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1150   }
1151
1152   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1153     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1154     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1155     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1156     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1157     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1158     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1159
1160     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1161     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1162     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1163
1164     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1165     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1166     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1167     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1168     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1169     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1170     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1171     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1172     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1173     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1174     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1175     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1176
1177     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1178     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1179     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1180     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1181     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1182     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1183     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1184     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1185     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1186     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1187     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1188     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1189
1190     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1191     // even though v8i16 is a legal type.
1192     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1193     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1194     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1195
1196     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1197     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1198     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1199
1200     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1201     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1202
1203     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1204
1205     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1206     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1207
1208     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1209     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1210
1211     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1212     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1213
1214     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1215     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1216     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1217     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1218
1219     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1220     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1221     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1222
1223     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1224     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1225     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1226     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1227
1228     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1229     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1230     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1231     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1232     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1233     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1234     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1235     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1236     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1237     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1238     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1239     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1240
1241     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1242       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1243       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1244       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1245       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1246       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1247       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1248     }
1249
1250     if (Subtarget->hasInt256()) {
1251       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1252       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1253       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1254       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1255
1256       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1257       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1258       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1259       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1260
1261       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1262       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1263       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1264       // Don't lower v32i8 because there is no 128-bit byte mul
1265
1266       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1267       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1268       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1269       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1270
1271       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1272       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1273     } else {
1274       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1275       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1276       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1277       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1278
1279       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1280       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1281       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1282       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1283
1284       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1285       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1286       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1287       // Don't lower v32i8 because there is no 128-bit byte mul
1288     }
1289
1290     // In the customized shift lowering, the legal cases in AVX2 will be
1291     // recognized.
1292     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1293     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1294
1295     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1296     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1297
1298     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1299
1300     // Custom lower several nodes for 256-bit types.
1301     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1302              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1303       MVT VT = (MVT::SimpleValueType)i;
1304
1305       // Extract subvector is special because the value type
1306       // (result) is 128-bit but the source is 256-bit wide.
1307       if (VT.is128BitVector())
1308         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1309
1310       // Do not attempt to custom lower other non-256-bit vectors
1311       if (!VT.is256BitVector())
1312         continue;
1313
1314       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1315       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1316       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1317       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1318       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1319       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1320       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1321     }
1322
1323     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1324     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1325       MVT VT = (MVT::SimpleValueType)i;
1326
1327       // Do not attempt to promote non-256-bit vectors
1328       if (!VT.is256BitVector())
1329         continue;
1330
1331       setOperationAction(ISD::AND,    VT, Promote);
1332       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1333       setOperationAction(ISD::OR,     VT, Promote);
1334       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1335       setOperationAction(ISD::XOR,    VT, Promote);
1336       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1337       setOperationAction(ISD::LOAD,   VT, Promote);
1338       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1339       setOperationAction(ISD::SELECT, VT, Promote);
1340       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1341     }
1342   }
1343
1344   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1345     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1346     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1347     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1348     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1349
1350     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1351     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1352     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1353
1354     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1355     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1356     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1357     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1358     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1359     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1360     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1361     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1362     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1363     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1364     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1365
1366     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1367     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1368     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1369     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1370     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1371     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1372
1373     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1374     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1375     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1376     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1377     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1378     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1379     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1380     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1381
1382     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1383     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1384     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1385     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1386     if (Subtarget->is64Bit()) {
1387       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1388       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1389       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1390       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1391     }
1392     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1393     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1394     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1395     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1396     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1397     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1398     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1399     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1400     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1401     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1402
1403     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1404     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1405     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1406     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1407     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1408     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1409     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1410     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1411     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1412     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1413     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1414     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1415     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1416
1417     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1418     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1419     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1420     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1421     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1422     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1423
1424     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1425     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1426
1427     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1428
1429     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1430     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1431     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1432     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1433     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1434     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1435     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1436     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1437     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1438
1439     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1440     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1441
1442     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1443     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1444
1445     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1446
1447     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1448     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1449
1450     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1451     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1452
1453     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1454     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1455
1456     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1457     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1458     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1459     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1460     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1461     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1462
1463     if (Subtarget->hasCDI()) {
1464       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1465       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1466     }
1467
1468     // Custom lower several nodes.
1469     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1470              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1471       MVT VT = (MVT::SimpleValueType)i;
1472
1473       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1474       // Extract subvector is special because the value type
1475       // (result) is 256/128-bit but the source is 512-bit wide.
1476       if (VT.is128BitVector() || VT.is256BitVector())
1477         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1478
1479       if (VT.getVectorElementType() == MVT::i1)
1480         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1481
1482       // Do not attempt to custom lower other non-512-bit vectors
1483       if (!VT.is512BitVector())
1484         continue;
1485
1486       if ( EltSize >= 32) {
1487         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1488         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1489         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1490         setOperationAction(ISD::VSELECT,             VT, Legal);
1491         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1492         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1493         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1494       }
1495     }
1496     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1497       MVT VT = (MVT::SimpleValueType)i;
1498
1499       // Do not attempt to promote non-256-bit vectors
1500       if (!VT.is512BitVector())
1501         continue;
1502
1503       setOperationAction(ISD::SELECT, VT, Promote);
1504       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1505     }
1506   }// has  AVX-512
1507
1508   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1509     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1510     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1511   }
1512
1513   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1514   // of this type with custom code.
1515   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1516            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1517     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1518                        Custom);
1519   }
1520
1521   // We want to custom lower some of our intrinsics.
1522   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1523   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1524   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1525   if (!Subtarget->is64Bit())
1526     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1527
1528   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1529   // handle type legalization for these operations here.
1530   //
1531   // FIXME: We really should do custom legalization for addition and
1532   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1533   // than generic legalization for 64-bit multiplication-with-overflow, though.
1534   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1535     // Add/Sub/Mul with overflow operations are custom lowered.
1536     MVT VT = IntVTs[i];
1537     setOperationAction(ISD::SADDO, VT, Custom);
1538     setOperationAction(ISD::UADDO, VT, Custom);
1539     setOperationAction(ISD::SSUBO, VT, Custom);
1540     setOperationAction(ISD::USUBO, VT, Custom);
1541     setOperationAction(ISD::SMULO, VT, Custom);
1542     setOperationAction(ISD::UMULO, VT, Custom);
1543   }
1544
1545   // There are no 8-bit 3-address imul/mul instructions
1546   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1547   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1548
1549   if (!Subtarget->is64Bit()) {
1550     // These libcalls are not available in 32-bit.
1551     setLibcallName(RTLIB::SHL_I128, nullptr);
1552     setLibcallName(RTLIB::SRL_I128, nullptr);
1553     setLibcallName(RTLIB::SRA_I128, nullptr);
1554   }
1555
1556   // Combine sin / cos into one node or libcall if possible.
1557   if (Subtarget->hasSinCos()) {
1558     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1559     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1560     if (Subtarget->isTargetDarwin()) {
1561       // For MacOSX, we don't want to the normal expansion of a libcall to
1562       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1563       // traffic.
1564       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1565       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1566     }
1567   }
1568
1569   if (Subtarget->isTargetWin64()) {
1570     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1571     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1572     setOperationAction(ISD::SREM, MVT::i128, Custom);
1573     setOperationAction(ISD::UREM, MVT::i128, Custom);
1574     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1575     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1576   }
1577
1578   // We have target-specific dag combine patterns for the following nodes:
1579   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1580   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1581   setTargetDAGCombine(ISD::VSELECT);
1582   setTargetDAGCombine(ISD::SELECT);
1583   setTargetDAGCombine(ISD::SHL);
1584   setTargetDAGCombine(ISD::SRA);
1585   setTargetDAGCombine(ISD::SRL);
1586   setTargetDAGCombine(ISD::OR);
1587   setTargetDAGCombine(ISD::AND);
1588   setTargetDAGCombine(ISD::ADD);
1589   setTargetDAGCombine(ISD::FADD);
1590   setTargetDAGCombine(ISD::FSUB);
1591   setTargetDAGCombine(ISD::FMA);
1592   setTargetDAGCombine(ISD::SUB);
1593   setTargetDAGCombine(ISD::LOAD);
1594   setTargetDAGCombine(ISD::STORE);
1595   setTargetDAGCombine(ISD::ZERO_EXTEND);
1596   setTargetDAGCombine(ISD::ANY_EXTEND);
1597   setTargetDAGCombine(ISD::SIGN_EXTEND);
1598   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1599   setTargetDAGCombine(ISD::TRUNCATE);
1600   setTargetDAGCombine(ISD::SINT_TO_FP);
1601   setTargetDAGCombine(ISD::SETCC);
1602   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1603   setTargetDAGCombine(ISD::BUILD_VECTOR);
1604   if (Subtarget->is64Bit())
1605     setTargetDAGCombine(ISD::MUL);
1606   setTargetDAGCombine(ISD::XOR);
1607
1608   computeRegisterProperties();
1609
1610   // On Darwin, -Os means optimize for size without hurting performance,
1611   // do not reduce the limit.
1612   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1613   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1614   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1615   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1616   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1617   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1618   setPrefLoopAlignment(4); // 2^4 bytes.
1619
1620   // Predictable cmov don't hurt on atom because it's in-order.
1621   PredictableSelectIsExpensive = !Subtarget->isAtom();
1622
1623   setPrefFunctionAlignment(4); // 2^4 bytes.
1624 }
1625
1626 TargetLoweringBase::LegalizeTypeAction
1627 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1628   if (ExperimentalVectorWideningLegalization &&
1629       VT.getVectorNumElements() != 1 &&
1630       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1631     return TypeWidenVector;
1632
1633   return TargetLoweringBase::getPreferredVectorAction(VT);
1634 }
1635
1636 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1637   if (!VT.isVector())
1638     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1639
1640   if (Subtarget->hasAVX512())
1641     switch(VT.getVectorNumElements()) {
1642     case  8: return MVT::v8i1;
1643     case 16: return MVT::v16i1;
1644   }
1645
1646   return VT.changeVectorElementTypeToInteger();
1647 }
1648
1649 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1650 /// the desired ByVal argument alignment.
1651 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1652   if (MaxAlign == 16)
1653     return;
1654   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1655     if (VTy->getBitWidth() == 128)
1656       MaxAlign = 16;
1657   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1658     unsigned EltAlign = 0;
1659     getMaxByValAlign(ATy->getElementType(), EltAlign);
1660     if (EltAlign > MaxAlign)
1661       MaxAlign = EltAlign;
1662   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1663     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1664       unsigned EltAlign = 0;
1665       getMaxByValAlign(STy->getElementType(i), EltAlign);
1666       if (EltAlign > MaxAlign)
1667         MaxAlign = EltAlign;
1668       if (MaxAlign == 16)
1669         break;
1670     }
1671   }
1672 }
1673
1674 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1675 /// function arguments in the caller parameter area. For X86, aggregates
1676 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1677 /// are at 4-byte boundaries.
1678 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1679   if (Subtarget->is64Bit()) {
1680     // Max of 8 and alignment of type.
1681     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1682     if (TyAlign > 8)
1683       return TyAlign;
1684     return 8;
1685   }
1686
1687   unsigned Align = 4;
1688   if (Subtarget->hasSSE1())
1689     getMaxByValAlign(Ty, Align);
1690   return Align;
1691 }
1692
1693 /// getOptimalMemOpType - Returns the target specific optimal type for load
1694 /// and store operations as a result of memset, memcpy, and memmove
1695 /// lowering. If DstAlign is zero that means it's safe to destination
1696 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1697 /// means there isn't a need to check it against alignment requirement,
1698 /// probably because the source does not need to be loaded. If 'IsMemset' is
1699 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1700 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1701 /// source is constant so it does not need to be loaded.
1702 /// It returns EVT::Other if the type should be determined using generic
1703 /// target-independent logic.
1704 EVT
1705 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1706                                        unsigned DstAlign, unsigned SrcAlign,
1707                                        bool IsMemset, bool ZeroMemset,
1708                                        bool MemcpyStrSrc,
1709                                        MachineFunction &MF) const {
1710   const Function *F = MF.getFunction();
1711   if ((!IsMemset || ZeroMemset) &&
1712       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1713                                        Attribute::NoImplicitFloat)) {
1714     if (Size >= 16 &&
1715         (Subtarget->isUnalignedMemAccessFast() ||
1716          ((DstAlign == 0 || DstAlign >= 16) &&
1717           (SrcAlign == 0 || SrcAlign >= 16)))) {
1718       if (Size >= 32) {
1719         if (Subtarget->hasInt256())
1720           return MVT::v8i32;
1721         if (Subtarget->hasFp256())
1722           return MVT::v8f32;
1723       }
1724       if (Subtarget->hasSSE2())
1725         return MVT::v4i32;
1726       if (Subtarget->hasSSE1())
1727         return MVT::v4f32;
1728     } else if (!MemcpyStrSrc && Size >= 8 &&
1729                !Subtarget->is64Bit() &&
1730                Subtarget->hasSSE2()) {
1731       // Do not use f64 to lower memcpy if source is string constant. It's
1732       // better to use i32 to avoid the loads.
1733       return MVT::f64;
1734     }
1735   }
1736   if (Subtarget->is64Bit() && Size >= 8)
1737     return MVT::i64;
1738   return MVT::i32;
1739 }
1740
1741 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1742   if (VT == MVT::f32)
1743     return X86ScalarSSEf32;
1744   else if (VT == MVT::f64)
1745     return X86ScalarSSEf64;
1746   return true;
1747 }
1748
1749 bool
1750 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1751                                                  unsigned,
1752                                                  bool *Fast) const {
1753   if (Fast)
1754     *Fast = Subtarget->isUnalignedMemAccessFast();
1755   return true;
1756 }
1757
1758 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1759 /// current function.  The returned value is a member of the
1760 /// MachineJumpTableInfo::JTEntryKind enum.
1761 unsigned X86TargetLowering::getJumpTableEncoding() const {
1762   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1763   // symbol.
1764   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1765       Subtarget->isPICStyleGOT())
1766     return MachineJumpTableInfo::EK_Custom32;
1767
1768   // Otherwise, use the normal jump table encoding heuristics.
1769   return TargetLowering::getJumpTableEncoding();
1770 }
1771
1772 const MCExpr *
1773 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1774                                              const MachineBasicBlock *MBB,
1775                                              unsigned uid,MCContext &Ctx) const{
1776   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1777          Subtarget->isPICStyleGOT());
1778   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1779   // entries.
1780   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1781                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1782 }
1783
1784 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1785 /// jumptable.
1786 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1787                                                     SelectionDAG &DAG) const {
1788   if (!Subtarget->is64Bit())
1789     // This doesn't have SDLoc associated with it, but is not really the
1790     // same as a Register.
1791     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1792   return Table;
1793 }
1794
1795 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1796 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1797 /// MCExpr.
1798 const MCExpr *X86TargetLowering::
1799 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1800                              MCContext &Ctx) const {
1801   // X86-64 uses RIP relative addressing based on the jump table label.
1802   if (Subtarget->isPICStyleRIPRel())
1803     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1804
1805   // Otherwise, the reference is relative to the PIC base.
1806   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1807 }
1808
1809 // FIXME: Why this routine is here? Move to RegInfo!
1810 std::pair<const TargetRegisterClass*, uint8_t>
1811 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1812   const TargetRegisterClass *RRC = nullptr;
1813   uint8_t Cost = 1;
1814   switch (VT.SimpleTy) {
1815   default:
1816     return TargetLowering::findRepresentativeClass(VT);
1817   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1818     RRC = Subtarget->is64Bit() ?
1819       (const TargetRegisterClass*)&X86::GR64RegClass :
1820       (const TargetRegisterClass*)&X86::GR32RegClass;
1821     break;
1822   case MVT::x86mmx:
1823     RRC = &X86::VR64RegClass;
1824     break;
1825   case MVT::f32: case MVT::f64:
1826   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1827   case MVT::v4f32: case MVT::v2f64:
1828   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1829   case MVT::v4f64:
1830     RRC = &X86::VR128RegClass;
1831     break;
1832   }
1833   return std::make_pair(RRC, Cost);
1834 }
1835
1836 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1837                                                unsigned &Offset) const {
1838   if (!Subtarget->isTargetLinux())
1839     return false;
1840
1841   if (Subtarget->is64Bit()) {
1842     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1843     Offset = 0x28;
1844     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1845       AddressSpace = 256;
1846     else
1847       AddressSpace = 257;
1848   } else {
1849     // %gs:0x14 on i386
1850     Offset = 0x14;
1851     AddressSpace = 256;
1852   }
1853   return true;
1854 }
1855
1856 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1857                                             unsigned DestAS) const {
1858   assert(SrcAS != DestAS && "Expected different address spaces!");
1859
1860   return SrcAS < 256 && DestAS < 256;
1861 }
1862
1863 //===----------------------------------------------------------------------===//
1864 //               Return Value Calling Convention Implementation
1865 //===----------------------------------------------------------------------===//
1866
1867 #include "X86GenCallingConv.inc"
1868
1869 bool
1870 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1871                                   MachineFunction &MF, bool isVarArg,
1872                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1873                         LLVMContext &Context) const {
1874   SmallVector<CCValAssign, 16> RVLocs;
1875   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1876                  RVLocs, Context);
1877   return CCInfo.CheckReturn(Outs, RetCC_X86);
1878 }
1879
1880 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1881   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1882   return ScratchRegs;
1883 }
1884
1885 SDValue
1886 X86TargetLowering::LowerReturn(SDValue Chain,
1887                                CallingConv::ID CallConv, bool isVarArg,
1888                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1889                                const SmallVectorImpl<SDValue> &OutVals,
1890                                SDLoc dl, SelectionDAG &DAG) const {
1891   MachineFunction &MF = DAG.getMachineFunction();
1892   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1893
1894   SmallVector<CCValAssign, 16> RVLocs;
1895   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1896                  RVLocs, *DAG.getContext());
1897   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1898
1899   SDValue Flag;
1900   SmallVector<SDValue, 6> RetOps;
1901   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1902   // Operand #1 = Bytes To Pop
1903   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1904                    MVT::i16));
1905
1906   // Copy the result values into the output registers.
1907   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1908     CCValAssign &VA = RVLocs[i];
1909     assert(VA.isRegLoc() && "Can only return in registers!");
1910     SDValue ValToCopy = OutVals[i];
1911     EVT ValVT = ValToCopy.getValueType();
1912
1913     // Promote values to the appropriate types
1914     if (VA.getLocInfo() == CCValAssign::SExt)
1915       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1916     else if (VA.getLocInfo() == CCValAssign::ZExt)
1917       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1918     else if (VA.getLocInfo() == CCValAssign::AExt)
1919       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1920     else if (VA.getLocInfo() == CCValAssign::BCvt)
1921       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1922
1923     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1924            "Unexpected FP-extend for return value.");  
1925
1926     // If this is x86-64, and we disabled SSE, we can't return FP values,
1927     // or SSE or MMX vectors.
1928     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1929          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1930           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1931       report_fatal_error("SSE register return with SSE disabled");
1932     }
1933     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1934     // llvm-gcc has never done it right and no one has noticed, so this
1935     // should be OK for now.
1936     if (ValVT == MVT::f64 &&
1937         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1938       report_fatal_error("SSE2 register return with SSE2 disabled");
1939
1940     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1941     // the RET instruction and handled by the FP Stackifier.
1942     if (VA.getLocReg() == X86::ST0 ||
1943         VA.getLocReg() == X86::ST1) {
1944       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1945       // change the value to the FP stack register class.
1946       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1947         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1948       RetOps.push_back(ValToCopy);
1949       // Don't emit a copytoreg.
1950       continue;
1951     }
1952
1953     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1954     // which is returned in RAX / RDX.
1955     if (Subtarget->is64Bit()) {
1956       if (ValVT == MVT::x86mmx) {
1957         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1958           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1959           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1960                                   ValToCopy);
1961           // If we don't have SSE2 available, convert to v4f32 so the generated
1962           // register is legal.
1963           if (!Subtarget->hasSSE2())
1964             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1965         }
1966       }
1967     }
1968
1969     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1970     Flag = Chain.getValue(1);
1971     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1972   }
1973
1974   // The x86-64 ABIs require that for returning structs by value we copy
1975   // the sret argument into %rax/%eax (depending on ABI) for the return.
1976   // Win32 requires us to put the sret argument to %eax as well.
1977   // We saved the argument into a virtual register in the entry block,
1978   // so now we copy the value out and into %rax/%eax.
1979   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1980       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1981     MachineFunction &MF = DAG.getMachineFunction();
1982     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1983     unsigned Reg = FuncInfo->getSRetReturnReg();
1984     assert(Reg &&
1985            "SRetReturnReg should have been set in LowerFormalArguments().");
1986     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1987
1988     unsigned RetValReg
1989         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1990           X86::RAX : X86::EAX;
1991     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1992     Flag = Chain.getValue(1);
1993
1994     // RAX/EAX now acts like a return value.
1995     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1996   }
1997
1998   RetOps[0] = Chain;  // Update chain.
1999
2000   // Add the flag if we have it.
2001   if (Flag.getNode())
2002     RetOps.push_back(Flag);
2003
2004   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2005 }
2006
2007 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2008   if (N->getNumValues() != 1)
2009     return false;
2010   if (!N->hasNUsesOfValue(1, 0))
2011     return false;
2012
2013   SDValue TCChain = Chain;
2014   SDNode *Copy = *N->use_begin();
2015   if (Copy->getOpcode() == ISD::CopyToReg) {
2016     // If the copy has a glue operand, we conservatively assume it isn't safe to
2017     // perform a tail call.
2018     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2019       return false;
2020     TCChain = Copy->getOperand(0);
2021   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2022     return false;
2023
2024   bool HasRet = false;
2025   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2026        UI != UE; ++UI) {
2027     if (UI->getOpcode() != X86ISD::RET_FLAG)
2028       return false;
2029     HasRet = true;
2030   }
2031
2032   if (!HasRet)
2033     return false;
2034
2035   Chain = TCChain;
2036   return true;
2037 }
2038
2039 MVT
2040 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2041                                             ISD::NodeType ExtendKind) const {
2042   MVT ReturnMVT;
2043   // TODO: Is this also valid on 32-bit?
2044   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2045     ReturnMVT = MVT::i8;
2046   else
2047     ReturnMVT = MVT::i32;
2048
2049   MVT MinVT = getRegisterType(ReturnMVT);
2050   return VT.bitsLT(MinVT) ? MinVT : VT;
2051 }
2052
2053 /// LowerCallResult - Lower the result values of a call into the
2054 /// appropriate copies out of appropriate physical registers.
2055 ///
2056 SDValue
2057 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2058                                    CallingConv::ID CallConv, bool isVarArg,
2059                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2060                                    SDLoc dl, SelectionDAG &DAG,
2061                                    SmallVectorImpl<SDValue> &InVals) const {
2062
2063   // Assign locations to each value returned by this call.
2064   SmallVector<CCValAssign, 16> RVLocs;
2065   bool Is64Bit = Subtarget->is64Bit();
2066   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2067                  DAG.getTarget(), RVLocs, *DAG.getContext());
2068   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2069
2070   // Copy all of the result registers out of their specified physreg.
2071   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2072     CCValAssign &VA = RVLocs[i];
2073     EVT CopyVT = VA.getValVT();
2074
2075     // If this is x86-64, and we disabled SSE, we can't return FP values
2076     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2077         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2078       report_fatal_error("SSE register return with SSE disabled");
2079     }
2080
2081     SDValue Val;
2082
2083     // If this is a call to a function that returns an fp value on the floating
2084     // point stack, we must guarantee the value is popped from the stack, so
2085     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2086     // if the return value is not used. We use the FpPOP_RETVAL instruction
2087     // instead.
2088     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2089       // If we prefer to use the value in xmm registers, copy it out as f80 and
2090       // use a truncate to move it from fp stack reg to xmm reg.
2091       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2092       SDValue Ops[] = { Chain, InFlag };
2093       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2094                                          MVT::Other, MVT::Glue, Ops), 1);
2095       Val = Chain.getValue(0);
2096
2097       // Round the f80 to the right size, which also moves it to the appropriate
2098       // xmm register.
2099       if (CopyVT != VA.getValVT())
2100         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2101                           // This truncation won't change the value.
2102                           DAG.getIntPtrConstant(1));
2103     } else {
2104       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2105                                  CopyVT, InFlag).getValue(1);
2106       Val = Chain.getValue(0);
2107     }
2108     InFlag = Chain.getValue(2);
2109     InVals.push_back(Val);
2110   }
2111
2112   return Chain;
2113 }
2114
2115 //===----------------------------------------------------------------------===//
2116 //                C & StdCall & Fast Calling Convention implementation
2117 //===----------------------------------------------------------------------===//
2118 //  StdCall calling convention seems to be standard for many Windows' API
2119 //  routines and around. It differs from C calling convention just a little:
2120 //  callee should clean up the stack, not caller. Symbols should be also
2121 //  decorated in some fancy way :) It doesn't support any vector arguments.
2122 //  For info on fast calling convention see Fast Calling Convention (tail call)
2123 //  implementation LowerX86_32FastCCCallTo.
2124
2125 /// CallIsStructReturn - Determines whether a call uses struct return
2126 /// semantics.
2127 enum StructReturnType {
2128   NotStructReturn,
2129   RegStructReturn,
2130   StackStructReturn
2131 };
2132 static StructReturnType
2133 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2134   if (Outs.empty())
2135     return NotStructReturn;
2136
2137   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2138   if (!Flags.isSRet())
2139     return NotStructReturn;
2140   if (Flags.isInReg())
2141     return RegStructReturn;
2142   return StackStructReturn;
2143 }
2144
2145 /// ArgsAreStructReturn - Determines whether a function uses struct
2146 /// return semantics.
2147 static StructReturnType
2148 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2149   if (Ins.empty())
2150     return NotStructReturn;
2151
2152   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2153   if (!Flags.isSRet())
2154     return NotStructReturn;
2155   if (Flags.isInReg())
2156     return RegStructReturn;
2157   return StackStructReturn;
2158 }
2159
2160 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2161 /// by "Src" to address "Dst" with size and alignment information specified by
2162 /// the specific parameter attribute. The copy will be passed as a byval
2163 /// function parameter.
2164 static SDValue
2165 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2166                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2167                           SDLoc dl) {
2168   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2169
2170   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2171                        /*isVolatile*/false, /*AlwaysInline=*/true,
2172                        MachinePointerInfo(), MachinePointerInfo());
2173 }
2174
2175 /// IsTailCallConvention - Return true if the calling convention is one that
2176 /// supports tail call optimization.
2177 static bool IsTailCallConvention(CallingConv::ID CC) {
2178   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2179           CC == CallingConv::HiPE);
2180 }
2181
2182 /// \brief Return true if the calling convention is a C calling convention.
2183 static bool IsCCallConvention(CallingConv::ID CC) {
2184   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2185           CC == CallingConv::X86_64_SysV);
2186 }
2187
2188 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2189   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2190     return false;
2191
2192   CallSite CS(CI);
2193   CallingConv::ID CalleeCC = CS.getCallingConv();
2194   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2195     return false;
2196
2197   return true;
2198 }
2199
2200 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2201 /// a tailcall target by changing its ABI.
2202 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2203                                    bool GuaranteedTailCallOpt) {
2204   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2205 }
2206
2207 SDValue
2208 X86TargetLowering::LowerMemArgument(SDValue Chain,
2209                                     CallingConv::ID CallConv,
2210                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2211                                     SDLoc dl, SelectionDAG &DAG,
2212                                     const CCValAssign &VA,
2213                                     MachineFrameInfo *MFI,
2214                                     unsigned i) const {
2215   // Create the nodes corresponding to a load from this parameter slot.
2216   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2217   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2218       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2219   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2220   EVT ValVT;
2221
2222   // If value is passed by pointer we have address passed instead of the value
2223   // itself.
2224   if (VA.getLocInfo() == CCValAssign::Indirect)
2225     ValVT = VA.getLocVT();
2226   else
2227     ValVT = VA.getValVT();
2228
2229   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2230   // changed with more analysis.
2231   // In case of tail call optimization mark all arguments mutable. Since they
2232   // could be overwritten by lowering of arguments in case of a tail call.
2233   if (Flags.isByVal()) {
2234     unsigned Bytes = Flags.getByValSize();
2235     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2236     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2237     return DAG.getFrameIndex(FI, getPointerTy());
2238   } else {
2239     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2240                                     VA.getLocMemOffset(), isImmutable);
2241     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2242     return DAG.getLoad(ValVT, dl, Chain, FIN,
2243                        MachinePointerInfo::getFixedStack(FI),
2244                        false, false, false, 0);
2245   }
2246 }
2247
2248 SDValue
2249 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2250                                         CallingConv::ID CallConv,
2251                                         bool isVarArg,
2252                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2253                                         SDLoc dl,
2254                                         SelectionDAG &DAG,
2255                                         SmallVectorImpl<SDValue> &InVals)
2256                                           const {
2257   MachineFunction &MF = DAG.getMachineFunction();
2258   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2259
2260   const Function* Fn = MF.getFunction();
2261   if (Fn->hasExternalLinkage() &&
2262       Subtarget->isTargetCygMing() &&
2263       Fn->getName() == "main")
2264     FuncInfo->setForceFramePointer(true);
2265
2266   MachineFrameInfo *MFI = MF.getFrameInfo();
2267   bool Is64Bit = Subtarget->is64Bit();
2268   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2269
2270   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2271          "Var args not supported with calling convention fastcc, ghc or hipe");
2272
2273   // Assign locations to all of the incoming arguments.
2274   SmallVector<CCValAssign, 16> ArgLocs;
2275   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2276                  ArgLocs, *DAG.getContext());
2277
2278   // Allocate shadow area for Win64
2279   if (IsWin64)
2280     CCInfo.AllocateStack(32, 8);
2281
2282   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2283
2284   unsigned LastVal = ~0U;
2285   SDValue ArgValue;
2286   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2287     CCValAssign &VA = ArgLocs[i];
2288     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2289     // places.
2290     assert(VA.getValNo() != LastVal &&
2291            "Don't support value assigned to multiple locs yet");
2292     (void)LastVal;
2293     LastVal = VA.getValNo();
2294
2295     if (VA.isRegLoc()) {
2296       EVT RegVT = VA.getLocVT();
2297       const TargetRegisterClass *RC;
2298       if (RegVT == MVT::i32)
2299         RC = &X86::GR32RegClass;
2300       else if (Is64Bit && RegVT == MVT::i64)
2301         RC = &X86::GR64RegClass;
2302       else if (RegVT == MVT::f32)
2303         RC = &X86::FR32RegClass;
2304       else if (RegVT == MVT::f64)
2305         RC = &X86::FR64RegClass;
2306       else if (RegVT.is512BitVector())
2307         RC = &X86::VR512RegClass;
2308       else if (RegVT.is256BitVector())
2309         RC = &X86::VR256RegClass;
2310       else if (RegVT.is128BitVector())
2311         RC = &X86::VR128RegClass;
2312       else if (RegVT == MVT::x86mmx)
2313         RC = &X86::VR64RegClass;
2314       else if (RegVT == MVT::i1)
2315         RC = &X86::VK1RegClass;
2316       else if (RegVT == MVT::v8i1)
2317         RC = &X86::VK8RegClass;
2318       else if (RegVT == MVT::v16i1)
2319         RC = &X86::VK16RegClass;
2320       else if (RegVT == MVT::v32i1)
2321         RC = &X86::VK32RegClass;
2322       else if (RegVT == MVT::v64i1)
2323         RC = &X86::VK64RegClass;
2324       else
2325         llvm_unreachable("Unknown argument type!");
2326
2327       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2328       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2329
2330       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2331       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2332       // right size.
2333       if (VA.getLocInfo() == CCValAssign::SExt)
2334         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2335                                DAG.getValueType(VA.getValVT()));
2336       else if (VA.getLocInfo() == CCValAssign::ZExt)
2337         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2338                                DAG.getValueType(VA.getValVT()));
2339       else if (VA.getLocInfo() == CCValAssign::BCvt)
2340         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2341
2342       if (VA.isExtInLoc()) {
2343         // Handle MMX values passed in XMM regs.
2344         if (RegVT.isVector())
2345           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2346         else
2347           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2348       }
2349     } else {
2350       assert(VA.isMemLoc());
2351       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2352     }
2353
2354     // If value is passed via pointer - do a load.
2355     if (VA.getLocInfo() == CCValAssign::Indirect)
2356       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2357                              MachinePointerInfo(), false, false, false, 0);
2358
2359     InVals.push_back(ArgValue);
2360   }
2361
2362   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2363     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2364       // The x86-64 ABIs require that for returning structs by value we copy
2365       // the sret argument into %rax/%eax (depending on ABI) for the return.
2366       // Win32 requires us to put the sret argument to %eax as well.
2367       // Save the argument into a virtual register so that we can access it
2368       // from the return points.
2369       if (Ins[i].Flags.isSRet()) {
2370         unsigned Reg = FuncInfo->getSRetReturnReg();
2371         if (!Reg) {
2372           MVT PtrTy = getPointerTy();
2373           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2374           FuncInfo->setSRetReturnReg(Reg);
2375         }
2376         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2377         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2378         break;
2379       }
2380     }
2381   }
2382
2383   unsigned StackSize = CCInfo.getNextStackOffset();
2384   // Align stack specially for tail calls.
2385   if (FuncIsMadeTailCallSafe(CallConv,
2386                              MF.getTarget().Options.GuaranteedTailCallOpt))
2387     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2388
2389   // If the function takes variable number of arguments, make a frame index for
2390   // the start of the first vararg value... for expansion of llvm.va_start.
2391   if (isVarArg) {
2392     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2393                     CallConv != CallingConv::X86_ThisCall)) {
2394       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2395     }
2396     if (Is64Bit) {
2397       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2398
2399       // FIXME: We should really autogenerate these arrays
2400       static const MCPhysReg GPR64ArgRegsWin64[] = {
2401         X86::RCX, X86::RDX, X86::R8,  X86::R9
2402       };
2403       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2404         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2405       };
2406       static const MCPhysReg XMMArgRegs64Bit[] = {
2407         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2408         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2409       };
2410       const MCPhysReg *GPR64ArgRegs;
2411       unsigned NumXMMRegs = 0;
2412
2413       if (IsWin64) {
2414         // The XMM registers which might contain var arg parameters are shadowed
2415         // in their paired GPR.  So we only need to save the GPR to their home
2416         // slots.
2417         TotalNumIntRegs = 4;
2418         GPR64ArgRegs = GPR64ArgRegsWin64;
2419       } else {
2420         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2421         GPR64ArgRegs = GPR64ArgRegs64Bit;
2422
2423         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2424                                                 TotalNumXMMRegs);
2425       }
2426       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2427                                                        TotalNumIntRegs);
2428
2429       bool NoImplicitFloatOps = Fn->getAttributes().
2430         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2431       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2432              "SSE register cannot be used when SSE is disabled!");
2433       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2434                NoImplicitFloatOps) &&
2435              "SSE register cannot be used when SSE is disabled!");
2436       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2437           !Subtarget->hasSSE1())
2438         // Kernel mode asks for SSE to be disabled, so don't push them
2439         // on the stack.
2440         TotalNumXMMRegs = 0;
2441
2442       if (IsWin64) {
2443         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2444         // Get to the caller-allocated home save location.  Add 8 to account
2445         // for the return address.
2446         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2447         FuncInfo->setRegSaveFrameIndex(
2448           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2449         // Fixup to set vararg frame on shadow area (4 x i64).
2450         if (NumIntRegs < 4)
2451           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2452       } else {
2453         // For X86-64, if there are vararg parameters that are passed via
2454         // registers, then we must store them to their spots on the stack so
2455         // they may be loaded by deferencing the result of va_next.
2456         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2457         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2458         FuncInfo->setRegSaveFrameIndex(
2459           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2460                                false));
2461       }
2462
2463       // Store the integer parameter registers.
2464       SmallVector<SDValue, 8> MemOps;
2465       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2466                                         getPointerTy());
2467       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2468       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2469         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2470                                   DAG.getIntPtrConstant(Offset));
2471         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2472                                      &X86::GR64RegClass);
2473         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2474         SDValue Store =
2475           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2476                        MachinePointerInfo::getFixedStack(
2477                          FuncInfo->getRegSaveFrameIndex(), Offset),
2478                        false, false, 0);
2479         MemOps.push_back(Store);
2480         Offset += 8;
2481       }
2482
2483       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2484         // Now store the XMM (fp + vector) parameter registers.
2485         SmallVector<SDValue, 11> SaveXMMOps;
2486         SaveXMMOps.push_back(Chain);
2487
2488         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2489         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2490         SaveXMMOps.push_back(ALVal);
2491
2492         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2493                                FuncInfo->getRegSaveFrameIndex()));
2494         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2495                                FuncInfo->getVarArgsFPOffset()));
2496
2497         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2498           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2499                                        &X86::VR128RegClass);
2500           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2501           SaveXMMOps.push_back(Val);
2502         }
2503         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2504                                      MVT::Other, SaveXMMOps));
2505       }
2506
2507       if (!MemOps.empty())
2508         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2509     }
2510   }
2511
2512   // Some CCs need callee pop.
2513   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2514                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2515     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2516   } else {
2517     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2518     // If this is an sret function, the return should pop the hidden pointer.
2519     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2520         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2521         argsAreStructReturn(Ins) == StackStructReturn)
2522       FuncInfo->setBytesToPopOnReturn(4);
2523   }
2524
2525   if (!Is64Bit) {
2526     // RegSaveFrameIndex is X86-64 only.
2527     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2528     if (CallConv == CallingConv::X86_FastCall ||
2529         CallConv == CallingConv::X86_ThisCall)
2530       // fastcc functions can't have varargs.
2531       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2532   }
2533
2534   FuncInfo->setArgumentStackSize(StackSize);
2535
2536   return Chain;
2537 }
2538
2539 SDValue
2540 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2541                                     SDValue StackPtr, SDValue Arg,
2542                                     SDLoc dl, SelectionDAG &DAG,
2543                                     const CCValAssign &VA,
2544                                     ISD::ArgFlagsTy Flags) const {
2545   unsigned LocMemOffset = VA.getLocMemOffset();
2546   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2547   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2548   if (Flags.isByVal())
2549     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2550
2551   return DAG.getStore(Chain, dl, Arg, PtrOff,
2552                       MachinePointerInfo::getStack(LocMemOffset),
2553                       false, false, 0);
2554 }
2555
2556 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2557 /// optimization is performed and it is required.
2558 SDValue
2559 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2560                                            SDValue &OutRetAddr, SDValue Chain,
2561                                            bool IsTailCall, bool Is64Bit,
2562                                            int FPDiff, SDLoc dl) const {
2563   // Adjust the Return address stack slot.
2564   EVT VT = getPointerTy();
2565   OutRetAddr = getReturnAddressFrameIndex(DAG);
2566
2567   // Load the "old" Return address.
2568   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2569                            false, false, false, 0);
2570   return SDValue(OutRetAddr.getNode(), 1);
2571 }
2572
2573 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2574 /// optimization is performed and it is required (FPDiff!=0).
2575 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2576                                         SDValue Chain, SDValue RetAddrFrIdx,
2577                                         EVT PtrVT, unsigned SlotSize,
2578                                         int FPDiff, SDLoc dl) {
2579   // Store the return address to the appropriate stack slot.
2580   if (!FPDiff) return Chain;
2581   // Calculate the new stack slot for the return address.
2582   int NewReturnAddrFI =
2583     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2584                                          false);
2585   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2586   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2587                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2588                        false, false, 0);
2589   return Chain;
2590 }
2591
2592 SDValue
2593 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2594                              SmallVectorImpl<SDValue> &InVals) const {
2595   SelectionDAG &DAG                     = CLI.DAG;
2596   SDLoc &dl                             = CLI.DL;
2597   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2598   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2599   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2600   SDValue Chain                         = CLI.Chain;
2601   SDValue Callee                        = CLI.Callee;
2602   CallingConv::ID CallConv              = CLI.CallConv;
2603   bool &isTailCall                      = CLI.IsTailCall;
2604   bool isVarArg                         = CLI.IsVarArg;
2605
2606   MachineFunction &MF = DAG.getMachineFunction();
2607   bool Is64Bit        = Subtarget->is64Bit();
2608   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2609   StructReturnType SR = callIsStructReturn(Outs);
2610   bool IsSibcall      = false;
2611
2612   if (MF.getTarget().Options.DisableTailCalls)
2613     isTailCall = false;
2614
2615   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2616   if (IsMustTail) {
2617     // Force this to be a tail call.  The verifier rules are enough to ensure
2618     // that we can lower this successfully without moving the return address
2619     // around.
2620     isTailCall = true;
2621   } else if (isTailCall) {
2622     // Check if it's really possible to do a tail call.
2623     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2624                     isVarArg, SR != NotStructReturn,
2625                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2626                     Outs, OutVals, Ins, DAG);
2627
2628     // Sibcalls are automatically detected tailcalls which do not require
2629     // ABI changes.
2630     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2631       IsSibcall = true;
2632
2633     if (isTailCall)
2634       ++NumTailCalls;
2635   }
2636
2637   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2638          "Var args not supported with calling convention fastcc, ghc or hipe");
2639
2640   // Analyze operands of the call, assigning locations to each operand.
2641   SmallVector<CCValAssign, 16> ArgLocs;
2642   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2643                  ArgLocs, *DAG.getContext());
2644
2645   // Allocate shadow area for Win64
2646   if (IsWin64)
2647     CCInfo.AllocateStack(32, 8);
2648
2649   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2650
2651   // Get a count of how many bytes are to be pushed on the stack.
2652   unsigned NumBytes = CCInfo.getNextStackOffset();
2653   if (IsSibcall)
2654     // This is a sibcall. The memory operands are available in caller's
2655     // own caller's stack.
2656     NumBytes = 0;
2657   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2658            IsTailCallConvention(CallConv))
2659     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2660
2661   int FPDiff = 0;
2662   if (isTailCall && !IsSibcall && !IsMustTail) {
2663     // Lower arguments at fp - stackoffset + fpdiff.
2664     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2665     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2666
2667     FPDiff = NumBytesCallerPushed - NumBytes;
2668
2669     // Set the delta of movement of the returnaddr stackslot.
2670     // But only set if delta is greater than previous delta.
2671     if (FPDiff < X86Info->getTCReturnAddrDelta())
2672       X86Info->setTCReturnAddrDelta(FPDiff);
2673   }
2674
2675   unsigned NumBytesToPush = NumBytes;
2676   unsigned NumBytesToPop = NumBytes;
2677
2678   // If we have an inalloca argument, all stack space has already been allocated
2679   // for us and be right at the top of the stack.  We don't support multiple
2680   // arguments passed in memory when using inalloca.
2681   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2682     NumBytesToPush = 0;
2683     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2684            "an inalloca argument must be the only memory argument");
2685   }
2686
2687   if (!IsSibcall)
2688     Chain = DAG.getCALLSEQ_START(
2689         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2690
2691   SDValue RetAddrFrIdx;
2692   // Load return address for tail calls.
2693   if (isTailCall && FPDiff)
2694     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2695                                     Is64Bit, FPDiff, dl);
2696
2697   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2698   SmallVector<SDValue, 8> MemOpChains;
2699   SDValue StackPtr;
2700
2701   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2702   // of tail call optimization arguments are handle later.
2703   const X86RegisterInfo *RegInfo =
2704     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2705   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2706     // Skip inalloca arguments, they have already been written.
2707     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2708     if (Flags.isInAlloca())
2709       continue;
2710
2711     CCValAssign &VA = ArgLocs[i];
2712     EVT RegVT = VA.getLocVT();
2713     SDValue Arg = OutVals[i];
2714     bool isByVal = Flags.isByVal();
2715
2716     // Promote the value if needed.
2717     switch (VA.getLocInfo()) {
2718     default: llvm_unreachable("Unknown loc info!");
2719     case CCValAssign::Full: break;
2720     case CCValAssign::SExt:
2721       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2722       break;
2723     case CCValAssign::ZExt:
2724       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2725       break;
2726     case CCValAssign::AExt:
2727       if (RegVT.is128BitVector()) {
2728         // Special case: passing MMX values in XMM registers.
2729         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2730         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2731         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2732       } else
2733         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2734       break;
2735     case CCValAssign::BCvt:
2736       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2737       break;
2738     case CCValAssign::Indirect: {
2739       // Store the argument.
2740       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2741       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2742       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2743                            MachinePointerInfo::getFixedStack(FI),
2744                            false, false, 0);
2745       Arg = SpillSlot;
2746       break;
2747     }
2748     }
2749
2750     if (VA.isRegLoc()) {
2751       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2752       if (isVarArg && IsWin64) {
2753         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2754         // shadow reg if callee is a varargs function.
2755         unsigned ShadowReg = 0;
2756         switch (VA.getLocReg()) {
2757         case X86::XMM0: ShadowReg = X86::RCX; break;
2758         case X86::XMM1: ShadowReg = X86::RDX; break;
2759         case X86::XMM2: ShadowReg = X86::R8; break;
2760         case X86::XMM3: ShadowReg = X86::R9; break;
2761         }
2762         if (ShadowReg)
2763           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2764       }
2765     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2766       assert(VA.isMemLoc());
2767       if (!StackPtr.getNode())
2768         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2769                                       getPointerTy());
2770       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2771                                              dl, DAG, VA, Flags));
2772     }
2773   }
2774
2775   if (!MemOpChains.empty())
2776     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2777
2778   if (Subtarget->isPICStyleGOT()) {
2779     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2780     // GOT pointer.
2781     if (!isTailCall) {
2782       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2783                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2784     } else {
2785       // If we are tail calling and generating PIC/GOT style code load the
2786       // address of the callee into ECX. The value in ecx is used as target of
2787       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2788       // for tail calls on PIC/GOT architectures. Normally we would just put the
2789       // address of GOT into ebx and then call target@PLT. But for tail calls
2790       // ebx would be restored (since ebx is callee saved) before jumping to the
2791       // target@PLT.
2792
2793       // Note: The actual moving to ECX is done further down.
2794       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2795       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2796           !G->getGlobal()->hasProtectedVisibility())
2797         Callee = LowerGlobalAddress(Callee, DAG);
2798       else if (isa<ExternalSymbolSDNode>(Callee))
2799         Callee = LowerExternalSymbol(Callee, DAG);
2800     }
2801   }
2802
2803   if (Is64Bit && isVarArg && !IsWin64) {
2804     // From AMD64 ABI document:
2805     // For calls that may call functions that use varargs or stdargs
2806     // (prototype-less calls or calls to functions containing ellipsis (...) in
2807     // the declaration) %al is used as hidden argument to specify the number
2808     // of SSE registers used. The contents of %al do not need to match exactly
2809     // the number of registers, but must be an ubound on the number of SSE
2810     // registers used and is in the range 0 - 8 inclusive.
2811
2812     // Count the number of XMM registers allocated.
2813     static const MCPhysReg XMMArgRegs[] = {
2814       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2815       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2816     };
2817     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2818     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2819            && "SSE registers cannot be used when SSE is disabled");
2820
2821     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2822                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2823   }
2824
2825   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2826   // don't need this because the eligibility check rejects calls that require
2827   // shuffling arguments passed in memory.
2828   if (!IsSibcall && isTailCall) {
2829     // Force all the incoming stack arguments to be loaded from the stack
2830     // before any new outgoing arguments are stored to the stack, because the
2831     // outgoing stack slots may alias the incoming argument stack slots, and
2832     // the alias isn't otherwise explicit. This is slightly more conservative
2833     // than necessary, because it means that each store effectively depends
2834     // on every argument instead of just those arguments it would clobber.
2835     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2836
2837     SmallVector<SDValue, 8> MemOpChains2;
2838     SDValue FIN;
2839     int FI = 0;
2840     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2841       CCValAssign &VA = ArgLocs[i];
2842       if (VA.isRegLoc())
2843         continue;
2844       assert(VA.isMemLoc());
2845       SDValue Arg = OutVals[i];
2846       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2847       // Skip inalloca arguments.  They don't require any work.
2848       if (Flags.isInAlloca())
2849         continue;
2850       // Create frame index.
2851       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2852       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2853       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2854       FIN = DAG.getFrameIndex(FI, getPointerTy());
2855
2856       if (Flags.isByVal()) {
2857         // Copy relative to framepointer.
2858         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2859         if (!StackPtr.getNode())
2860           StackPtr = DAG.getCopyFromReg(Chain, dl,
2861                                         RegInfo->getStackRegister(),
2862                                         getPointerTy());
2863         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2864
2865         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2866                                                          ArgChain,
2867                                                          Flags, DAG, dl));
2868       } else {
2869         // Store relative to framepointer.
2870         MemOpChains2.push_back(
2871           DAG.getStore(ArgChain, dl, Arg, FIN,
2872                        MachinePointerInfo::getFixedStack(FI),
2873                        false, false, 0));
2874       }
2875     }
2876
2877     if (!MemOpChains2.empty())
2878       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2879
2880     // Store the return address to the appropriate stack slot.
2881     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2882                                      getPointerTy(), RegInfo->getSlotSize(),
2883                                      FPDiff, dl);
2884   }
2885
2886   // Build a sequence of copy-to-reg nodes chained together with token chain
2887   // and flag operands which copy the outgoing args into registers.
2888   SDValue InFlag;
2889   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2890     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2891                              RegsToPass[i].second, InFlag);
2892     InFlag = Chain.getValue(1);
2893   }
2894
2895   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2896     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2897     // In the 64-bit large code model, we have to make all calls
2898     // through a register, since the call instruction's 32-bit
2899     // pc-relative offset may not be large enough to hold the whole
2900     // address.
2901   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2902     // If the callee is a GlobalAddress node (quite common, every direct call
2903     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2904     // it.
2905
2906     // We should use extra load for direct calls to dllimported functions in
2907     // non-JIT mode.
2908     const GlobalValue *GV = G->getGlobal();
2909     if (!GV->hasDLLImportStorageClass()) {
2910       unsigned char OpFlags = 0;
2911       bool ExtraLoad = false;
2912       unsigned WrapperKind = ISD::DELETED_NODE;
2913
2914       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2915       // external symbols most go through the PLT in PIC mode.  If the symbol
2916       // has hidden or protected visibility, or if it is static or local, then
2917       // we don't need to use the PLT - we can directly call it.
2918       if (Subtarget->isTargetELF() &&
2919           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2920           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2921         OpFlags = X86II::MO_PLT;
2922       } else if (Subtarget->isPICStyleStubAny() &&
2923                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2924                  (!Subtarget->getTargetTriple().isMacOSX() ||
2925                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2926         // PC-relative references to external symbols should go through $stub,
2927         // unless we're building with the leopard linker or later, which
2928         // automatically synthesizes these stubs.
2929         OpFlags = X86II::MO_DARWIN_STUB;
2930       } else if (Subtarget->isPICStyleRIPRel() &&
2931                  isa<Function>(GV) &&
2932                  cast<Function>(GV)->getAttributes().
2933                    hasAttribute(AttributeSet::FunctionIndex,
2934                                 Attribute::NonLazyBind)) {
2935         // If the function is marked as non-lazy, generate an indirect call
2936         // which loads from the GOT directly. This avoids runtime overhead
2937         // at the cost of eager binding (and one extra byte of encoding).
2938         OpFlags = X86II::MO_GOTPCREL;
2939         WrapperKind = X86ISD::WrapperRIP;
2940         ExtraLoad = true;
2941       }
2942
2943       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2944                                           G->getOffset(), OpFlags);
2945
2946       // Add a wrapper if needed.
2947       if (WrapperKind != ISD::DELETED_NODE)
2948         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2949       // Add extra indirection if needed.
2950       if (ExtraLoad)
2951         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2952                              MachinePointerInfo::getGOT(),
2953                              false, false, false, 0);
2954     }
2955   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2956     unsigned char OpFlags = 0;
2957
2958     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2959     // external symbols should go through the PLT.
2960     if (Subtarget->isTargetELF() &&
2961         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2962       OpFlags = X86II::MO_PLT;
2963     } else if (Subtarget->isPICStyleStubAny() &&
2964                (!Subtarget->getTargetTriple().isMacOSX() ||
2965                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2966       // PC-relative references to external symbols should go through $stub,
2967       // unless we're building with the leopard linker or later, which
2968       // automatically synthesizes these stubs.
2969       OpFlags = X86II::MO_DARWIN_STUB;
2970     }
2971
2972     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2973                                          OpFlags);
2974   }
2975
2976   // Returns a chain & a flag for retval copy to use.
2977   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2978   SmallVector<SDValue, 8> Ops;
2979
2980   if (!IsSibcall && isTailCall) {
2981     Chain = DAG.getCALLSEQ_END(Chain,
2982                                DAG.getIntPtrConstant(NumBytesToPop, true),
2983                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2984     InFlag = Chain.getValue(1);
2985   }
2986
2987   Ops.push_back(Chain);
2988   Ops.push_back(Callee);
2989
2990   if (isTailCall)
2991     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2992
2993   // Add argument registers to the end of the list so that they are known live
2994   // into the call.
2995   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2996     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2997                                   RegsToPass[i].second.getValueType()));
2998
2999   // Add a register mask operand representing the call-preserved registers.
3000   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3001   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3002   assert(Mask && "Missing call preserved mask for calling convention");
3003   Ops.push_back(DAG.getRegisterMask(Mask));
3004
3005   if (InFlag.getNode())
3006     Ops.push_back(InFlag);
3007
3008   if (isTailCall) {
3009     // We used to do:
3010     //// If this is the first return lowered for this function, add the regs
3011     //// to the liveout set for the function.
3012     // This isn't right, although it's probably harmless on x86; liveouts
3013     // should be computed from returns not tail calls.  Consider a void
3014     // function making a tail call to a function returning int.
3015     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3016   }
3017
3018   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3019   InFlag = Chain.getValue(1);
3020
3021   // Create the CALLSEQ_END node.
3022   unsigned NumBytesForCalleeToPop;
3023   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3024                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3025     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3026   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3027            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3028            SR == StackStructReturn)
3029     // If this is a call to a struct-return function, the callee
3030     // pops the hidden struct pointer, so we have to push it back.
3031     // This is common for Darwin/X86, Linux & Mingw32 targets.
3032     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3033     NumBytesForCalleeToPop = 4;
3034   else
3035     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3036
3037   // Returns a flag for retval copy to use.
3038   if (!IsSibcall) {
3039     Chain = DAG.getCALLSEQ_END(Chain,
3040                                DAG.getIntPtrConstant(NumBytesToPop, true),
3041                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3042                                                      true),
3043                                InFlag, dl);
3044     InFlag = Chain.getValue(1);
3045   }
3046
3047   // Handle result values, copying them out of physregs into vregs that we
3048   // return.
3049   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3050                          Ins, dl, DAG, InVals);
3051 }
3052
3053 //===----------------------------------------------------------------------===//
3054 //                Fast Calling Convention (tail call) implementation
3055 //===----------------------------------------------------------------------===//
3056
3057 //  Like std call, callee cleans arguments, convention except that ECX is
3058 //  reserved for storing the tail called function address. Only 2 registers are
3059 //  free for argument passing (inreg). Tail call optimization is performed
3060 //  provided:
3061 //                * tailcallopt is enabled
3062 //                * caller/callee are fastcc
3063 //  On X86_64 architecture with GOT-style position independent code only local
3064 //  (within module) calls are supported at the moment.
3065 //  To keep the stack aligned according to platform abi the function
3066 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3067 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3068 //  If a tail called function callee has more arguments than the caller the
3069 //  caller needs to make sure that there is room to move the RETADDR to. This is
3070 //  achieved by reserving an area the size of the argument delta right after the
3071 //  original RETADDR, but before the saved framepointer or the spilled registers
3072 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3073 //  stack layout:
3074 //    arg1
3075 //    arg2
3076 //    RETADDR
3077 //    [ new RETADDR
3078 //      move area ]
3079 //    (possible EBP)
3080 //    ESI
3081 //    EDI
3082 //    local1 ..
3083
3084 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3085 /// for a 16 byte align requirement.
3086 unsigned
3087 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3088                                                SelectionDAG& DAG) const {
3089   MachineFunction &MF = DAG.getMachineFunction();
3090   const TargetMachine &TM = MF.getTarget();
3091   const X86RegisterInfo *RegInfo =
3092     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3093   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3094   unsigned StackAlignment = TFI.getStackAlignment();
3095   uint64_t AlignMask = StackAlignment - 1;
3096   int64_t Offset = StackSize;
3097   unsigned SlotSize = RegInfo->getSlotSize();
3098   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3099     // Number smaller than 12 so just add the difference.
3100     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3101   } else {
3102     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3103     Offset = ((~AlignMask) & Offset) + StackAlignment +
3104       (StackAlignment-SlotSize);
3105   }
3106   return Offset;
3107 }
3108
3109 /// MatchingStackOffset - Return true if the given stack call argument is
3110 /// already available in the same position (relatively) of the caller's
3111 /// incoming argument stack.
3112 static
3113 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3114                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3115                          const X86InstrInfo *TII) {
3116   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3117   int FI = INT_MAX;
3118   if (Arg.getOpcode() == ISD::CopyFromReg) {
3119     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3120     if (!TargetRegisterInfo::isVirtualRegister(VR))
3121       return false;
3122     MachineInstr *Def = MRI->getVRegDef(VR);
3123     if (!Def)
3124       return false;
3125     if (!Flags.isByVal()) {
3126       if (!TII->isLoadFromStackSlot(Def, FI))
3127         return false;
3128     } else {
3129       unsigned Opcode = Def->getOpcode();
3130       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3131           Def->getOperand(1).isFI()) {
3132         FI = Def->getOperand(1).getIndex();
3133         Bytes = Flags.getByValSize();
3134       } else
3135         return false;
3136     }
3137   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3138     if (Flags.isByVal())
3139       // ByVal argument is passed in as a pointer but it's now being
3140       // dereferenced. e.g.
3141       // define @foo(%struct.X* %A) {
3142       //   tail call @bar(%struct.X* byval %A)
3143       // }
3144       return false;
3145     SDValue Ptr = Ld->getBasePtr();
3146     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3147     if (!FINode)
3148       return false;
3149     FI = FINode->getIndex();
3150   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3151     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3152     FI = FINode->getIndex();
3153     Bytes = Flags.getByValSize();
3154   } else
3155     return false;
3156
3157   assert(FI != INT_MAX);
3158   if (!MFI->isFixedObjectIndex(FI))
3159     return false;
3160   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3161 }
3162
3163 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3164 /// for tail call optimization. Targets which want to do tail call
3165 /// optimization should implement this function.
3166 bool
3167 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3168                                                      CallingConv::ID CalleeCC,
3169                                                      bool isVarArg,
3170                                                      bool isCalleeStructRet,
3171                                                      bool isCallerStructRet,
3172                                                      Type *RetTy,
3173                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3174                                     const SmallVectorImpl<SDValue> &OutVals,
3175                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3176                                                      SelectionDAG &DAG) const {
3177   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3178     return false;
3179
3180   // If -tailcallopt is specified, make fastcc functions tail-callable.
3181   const MachineFunction &MF = DAG.getMachineFunction();
3182   const Function *CallerF = MF.getFunction();
3183
3184   // If the function return type is x86_fp80 and the callee return type is not,
3185   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3186   // perform a tailcall optimization here.
3187   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3188     return false;
3189
3190   CallingConv::ID CallerCC = CallerF->getCallingConv();
3191   bool CCMatch = CallerCC == CalleeCC;
3192   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3193   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3194
3195   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3196     if (IsTailCallConvention(CalleeCC) && CCMatch)
3197       return true;
3198     return false;
3199   }
3200
3201   // Look for obvious safe cases to perform tail call optimization that do not
3202   // require ABI changes. This is what gcc calls sibcall.
3203
3204   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3205   // emit a special epilogue.
3206   const X86RegisterInfo *RegInfo =
3207     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3208   if (RegInfo->needsStackRealignment(MF))
3209     return false;
3210
3211   // Also avoid sibcall optimization if either caller or callee uses struct
3212   // return semantics.
3213   if (isCalleeStructRet || isCallerStructRet)
3214     return false;
3215
3216   // An stdcall/thiscall caller is expected to clean up its arguments; the
3217   // callee isn't going to do that.
3218   // FIXME: this is more restrictive than needed. We could produce a tailcall
3219   // when the stack adjustment matches. For example, with a thiscall that takes
3220   // only one argument.
3221   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3222                    CallerCC == CallingConv::X86_ThisCall))
3223     return false;
3224
3225   // Do not sibcall optimize vararg calls unless all arguments are passed via
3226   // registers.
3227   if (isVarArg && !Outs.empty()) {
3228
3229     // Optimizing for varargs on Win64 is unlikely to be safe without
3230     // additional testing.
3231     if (IsCalleeWin64 || IsCallerWin64)
3232       return false;
3233
3234     SmallVector<CCValAssign, 16> ArgLocs;
3235     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3236                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3237
3238     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3239     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3240       if (!ArgLocs[i].isRegLoc())
3241         return false;
3242   }
3243
3244   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3245   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3246   // this into a sibcall.
3247   bool Unused = false;
3248   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3249     if (!Ins[i].Used) {
3250       Unused = true;
3251       break;
3252     }
3253   }
3254   if (Unused) {
3255     SmallVector<CCValAssign, 16> RVLocs;
3256     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3257                    DAG.getTarget(), RVLocs, *DAG.getContext());
3258     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3259     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3260       CCValAssign &VA = RVLocs[i];
3261       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3262         return false;
3263     }
3264   }
3265
3266   // If the calling conventions do not match, then we'd better make sure the
3267   // results are returned in the same way as what the caller expects.
3268   if (!CCMatch) {
3269     SmallVector<CCValAssign, 16> RVLocs1;
3270     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3271                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3272     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3273
3274     SmallVector<CCValAssign, 16> RVLocs2;
3275     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3276                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3277     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3278
3279     if (RVLocs1.size() != RVLocs2.size())
3280       return false;
3281     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3282       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3283         return false;
3284       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3285         return false;
3286       if (RVLocs1[i].isRegLoc()) {
3287         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3288           return false;
3289       } else {
3290         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3291           return false;
3292       }
3293     }
3294   }
3295
3296   // If the callee takes no arguments then go on to check the results of the
3297   // call.
3298   if (!Outs.empty()) {
3299     // Check if stack adjustment is needed. For now, do not do this if any
3300     // argument is passed on the stack.
3301     SmallVector<CCValAssign, 16> ArgLocs;
3302     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3303                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3304
3305     // Allocate shadow area for Win64
3306     if (IsCalleeWin64)
3307       CCInfo.AllocateStack(32, 8);
3308
3309     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3310     if (CCInfo.getNextStackOffset()) {
3311       MachineFunction &MF = DAG.getMachineFunction();
3312       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3313         return false;
3314
3315       // Check if the arguments are already laid out in the right way as
3316       // the caller's fixed stack objects.
3317       MachineFrameInfo *MFI = MF.getFrameInfo();
3318       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3319       const X86InstrInfo *TII =
3320           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3321       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3322         CCValAssign &VA = ArgLocs[i];
3323         SDValue Arg = OutVals[i];
3324         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3325         if (VA.getLocInfo() == CCValAssign::Indirect)
3326           return false;
3327         if (!VA.isRegLoc()) {
3328           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3329                                    MFI, MRI, TII))
3330             return false;
3331         }
3332       }
3333     }
3334
3335     // If the tailcall address may be in a register, then make sure it's
3336     // possible to register allocate for it. In 32-bit, the call address can
3337     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3338     // callee-saved registers are restored. These happen to be the same
3339     // registers used to pass 'inreg' arguments so watch out for those.
3340     if (!Subtarget->is64Bit() &&
3341         ((!isa<GlobalAddressSDNode>(Callee) &&
3342           !isa<ExternalSymbolSDNode>(Callee)) ||
3343          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3344       unsigned NumInRegs = 0;
3345       // In PIC we need an extra register to formulate the address computation
3346       // for the callee.
3347       unsigned MaxInRegs =
3348         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3349
3350       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3351         CCValAssign &VA = ArgLocs[i];
3352         if (!VA.isRegLoc())
3353           continue;
3354         unsigned Reg = VA.getLocReg();
3355         switch (Reg) {
3356         default: break;
3357         case X86::EAX: case X86::EDX: case X86::ECX:
3358           if (++NumInRegs == MaxInRegs)
3359             return false;
3360           break;
3361         }
3362       }
3363     }
3364   }
3365
3366   return true;
3367 }
3368
3369 FastISel *
3370 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3371                                   const TargetLibraryInfo *libInfo) const {
3372   return X86::createFastISel(funcInfo, libInfo);
3373 }
3374
3375 //===----------------------------------------------------------------------===//
3376 //                           Other Lowering Hooks
3377 //===----------------------------------------------------------------------===//
3378
3379 static bool MayFoldLoad(SDValue Op) {
3380   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3381 }
3382
3383 static bool MayFoldIntoStore(SDValue Op) {
3384   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3385 }
3386
3387 static bool isTargetShuffle(unsigned Opcode) {
3388   switch(Opcode) {
3389   default: return false;
3390   case X86ISD::PSHUFD:
3391   case X86ISD::PSHUFHW:
3392   case X86ISD::PSHUFLW:
3393   case X86ISD::SHUFP:
3394   case X86ISD::PALIGNR:
3395   case X86ISD::MOVLHPS:
3396   case X86ISD::MOVLHPD:
3397   case X86ISD::MOVHLPS:
3398   case X86ISD::MOVLPS:
3399   case X86ISD::MOVLPD:
3400   case X86ISD::MOVSHDUP:
3401   case X86ISD::MOVSLDUP:
3402   case X86ISD::MOVDDUP:
3403   case X86ISD::MOVSS:
3404   case X86ISD::MOVSD:
3405   case X86ISD::UNPCKL:
3406   case X86ISD::UNPCKH:
3407   case X86ISD::VPERMILP:
3408   case X86ISD::VPERM2X128:
3409   case X86ISD::VPERMI:
3410     return true;
3411   }
3412 }
3413
3414 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3415                                     SDValue V1, SelectionDAG &DAG) {
3416   switch(Opc) {
3417   default: llvm_unreachable("Unknown x86 shuffle node");
3418   case X86ISD::MOVSHDUP:
3419   case X86ISD::MOVSLDUP:
3420   case X86ISD::MOVDDUP:
3421     return DAG.getNode(Opc, dl, VT, V1);
3422   }
3423 }
3424
3425 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3426                                     SDValue V1, unsigned TargetMask,
3427                                     SelectionDAG &DAG) {
3428   switch(Opc) {
3429   default: llvm_unreachable("Unknown x86 shuffle node");
3430   case X86ISD::PSHUFD:
3431   case X86ISD::PSHUFHW:
3432   case X86ISD::PSHUFLW:
3433   case X86ISD::VPERMILP:
3434   case X86ISD::VPERMI:
3435     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3436   }
3437 }
3438
3439 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3440                                     SDValue V1, SDValue V2, unsigned TargetMask,
3441                                     SelectionDAG &DAG) {
3442   switch(Opc) {
3443   default: llvm_unreachable("Unknown x86 shuffle node");
3444   case X86ISD::PALIGNR:
3445   case X86ISD::SHUFP:
3446   case X86ISD::VPERM2X128:
3447     return DAG.getNode(Opc, dl, VT, V1, V2,
3448                        DAG.getConstant(TargetMask, MVT::i8));
3449   }
3450 }
3451
3452 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3453                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3454   switch(Opc) {
3455   default: llvm_unreachable("Unknown x86 shuffle node");
3456   case X86ISD::MOVLHPS:
3457   case X86ISD::MOVLHPD:
3458   case X86ISD::MOVHLPS:
3459   case X86ISD::MOVLPS:
3460   case X86ISD::MOVLPD:
3461   case X86ISD::MOVSS:
3462   case X86ISD::MOVSD:
3463   case X86ISD::UNPCKL:
3464   case X86ISD::UNPCKH:
3465     return DAG.getNode(Opc, dl, VT, V1, V2);
3466   }
3467 }
3468
3469 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3470   MachineFunction &MF = DAG.getMachineFunction();
3471   const X86RegisterInfo *RegInfo =
3472     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3473   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3474   int ReturnAddrIndex = FuncInfo->getRAIndex();
3475
3476   if (ReturnAddrIndex == 0) {
3477     // Set up a frame object for the return address.
3478     unsigned SlotSize = RegInfo->getSlotSize();
3479     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3480                                                            -(int64_t)SlotSize,
3481                                                            false);
3482     FuncInfo->setRAIndex(ReturnAddrIndex);
3483   }
3484
3485   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3486 }
3487
3488 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3489                                        bool hasSymbolicDisplacement) {
3490   // Offset should fit into 32 bit immediate field.
3491   if (!isInt<32>(Offset))
3492     return false;
3493
3494   // If we don't have a symbolic displacement - we don't have any extra
3495   // restrictions.
3496   if (!hasSymbolicDisplacement)
3497     return true;
3498
3499   // FIXME: Some tweaks might be needed for medium code model.
3500   if (M != CodeModel::Small && M != CodeModel::Kernel)
3501     return false;
3502
3503   // For small code model we assume that latest object is 16MB before end of 31
3504   // bits boundary. We may also accept pretty large negative constants knowing
3505   // that all objects are in the positive half of address space.
3506   if (M == CodeModel::Small && Offset < 16*1024*1024)
3507     return true;
3508
3509   // For kernel code model we know that all object resist in the negative half
3510   // of 32bits address space. We may not accept negative offsets, since they may
3511   // be just off and we may accept pretty large positive ones.
3512   if (M == CodeModel::Kernel && Offset > 0)
3513     return true;
3514
3515   return false;
3516 }
3517
3518 /// isCalleePop - Determines whether the callee is required to pop its
3519 /// own arguments. Callee pop is necessary to support tail calls.
3520 bool X86::isCalleePop(CallingConv::ID CallingConv,
3521                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3522   if (IsVarArg)
3523     return false;
3524
3525   switch (CallingConv) {
3526   default:
3527     return false;
3528   case CallingConv::X86_StdCall:
3529     return !is64Bit;
3530   case CallingConv::X86_FastCall:
3531     return !is64Bit;
3532   case CallingConv::X86_ThisCall:
3533     return !is64Bit;
3534   case CallingConv::Fast:
3535     return TailCallOpt;
3536   case CallingConv::GHC:
3537     return TailCallOpt;
3538   case CallingConv::HiPE:
3539     return TailCallOpt;
3540   }
3541 }
3542
3543 /// \brief Return true if the condition is an unsigned comparison operation.
3544 static bool isX86CCUnsigned(unsigned X86CC) {
3545   switch (X86CC) {
3546   default: llvm_unreachable("Invalid integer condition!");
3547   case X86::COND_E:     return true;
3548   case X86::COND_G:     return false;
3549   case X86::COND_GE:    return false;
3550   case X86::COND_L:     return false;
3551   case X86::COND_LE:    return false;
3552   case X86::COND_NE:    return true;
3553   case X86::COND_B:     return true;
3554   case X86::COND_A:     return true;
3555   case X86::COND_BE:    return true;
3556   case X86::COND_AE:    return true;
3557   }
3558   llvm_unreachable("covered switch fell through?!");
3559 }
3560
3561 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3562 /// specific condition code, returning the condition code and the LHS/RHS of the
3563 /// comparison to make.
3564 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3565                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3566   if (!isFP) {
3567     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3568       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3569         // X > -1   -> X == 0, jump !sign.
3570         RHS = DAG.getConstant(0, RHS.getValueType());
3571         return X86::COND_NS;
3572       }
3573       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3574         // X < 0   -> X == 0, jump on sign.
3575         return X86::COND_S;
3576       }
3577       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3578         // X < 1   -> X <= 0
3579         RHS = DAG.getConstant(0, RHS.getValueType());
3580         return X86::COND_LE;
3581       }
3582     }
3583
3584     switch (SetCCOpcode) {
3585     default: llvm_unreachable("Invalid integer condition!");
3586     case ISD::SETEQ:  return X86::COND_E;
3587     case ISD::SETGT:  return X86::COND_G;
3588     case ISD::SETGE:  return X86::COND_GE;
3589     case ISD::SETLT:  return X86::COND_L;
3590     case ISD::SETLE:  return X86::COND_LE;
3591     case ISD::SETNE:  return X86::COND_NE;
3592     case ISD::SETULT: return X86::COND_B;
3593     case ISD::SETUGT: return X86::COND_A;
3594     case ISD::SETULE: return X86::COND_BE;
3595     case ISD::SETUGE: return X86::COND_AE;
3596     }
3597   }
3598
3599   // First determine if it is required or is profitable to flip the operands.
3600
3601   // If LHS is a foldable load, but RHS is not, flip the condition.
3602   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3603       !ISD::isNON_EXTLoad(RHS.getNode())) {
3604     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3605     std::swap(LHS, RHS);
3606   }
3607
3608   switch (SetCCOpcode) {
3609   default: break;
3610   case ISD::SETOLT:
3611   case ISD::SETOLE:
3612   case ISD::SETUGT:
3613   case ISD::SETUGE:
3614     std::swap(LHS, RHS);
3615     break;
3616   }
3617
3618   // On a floating point condition, the flags are set as follows:
3619   // ZF  PF  CF   op
3620   //  0 | 0 | 0 | X > Y
3621   //  0 | 0 | 1 | X < Y
3622   //  1 | 0 | 0 | X == Y
3623   //  1 | 1 | 1 | unordered
3624   switch (SetCCOpcode) {
3625   default: llvm_unreachable("Condcode should be pre-legalized away");
3626   case ISD::SETUEQ:
3627   case ISD::SETEQ:   return X86::COND_E;
3628   case ISD::SETOLT:              // flipped
3629   case ISD::SETOGT:
3630   case ISD::SETGT:   return X86::COND_A;
3631   case ISD::SETOLE:              // flipped
3632   case ISD::SETOGE:
3633   case ISD::SETGE:   return X86::COND_AE;
3634   case ISD::SETUGT:              // flipped
3635   case ISD::SETULT:
3636   case ISD::SETLT:   return X86::COND_B;
3637   case ISD::SETUGE:              // flipped
3638   case ISD::SETULE:
3639   case ISD::SETLE:   return X86::COND_BE;
3640   case ISD::SETONE:
3641   case ISD::SETNE:   return X86::COND_NE;
3642   case ISD::SETUO:   return X86::COND_P;
3643   case ISD::SETO:    return X86::COND_NP;
3644   case ISD::SETOEQ:
3645   case ISD::SETUNE:  return X86::COND_INVALID;
3646   }
3647 }
3648
3649 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3650 /// code. Current x86 isa includes the following FP cmov instructions:
3651 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3652 static bool hasFPCMov(unsigned X86CC) {
3653   switch (X86CC) {
3654   default:
3655     return false;
3656   case X86::COND_B:
3657   case X86::COND_BE:
3658   case X86::COND_E:
3659   case X86::COND_P:
3660   case X86::COND_A:
3661   case X86::COND_AE:
3662   case X86::COND_NE:
3663   case X86::COND_NP:
3664     return true;
3665   }
3666 }
3667
3668 /// isFPImmLegal - Returns true if the target can instruction select the
3669 /// specified FP immediate natively. If false, the legalizer will
3670 /// materialize the FP immediate as a load from a constant pool.
3671 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3672   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3673     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3674       return true;
3675   }
3676   return false;
3677 }
3678
3679 /// \brief Returns true if it is beneficial to convert a load of a constant
3680 /// to just the constant itself.
3681 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3682                                                           Type *Ty) const {
3683   assert(Ty->isIntegerTy());
3684
3685   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3686   if (BitSize == 0 || BitSize > 64)
3687     return false;
3688   return true;
3689 }
3690
3691 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3692 /// the specified range (L, H].
3693 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3694   return (Val < 0) || (Val >= Low && Val < Hi);
3695 }
3696
3697 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3698 /// specified value.
3699 static bool isUndefOrEqual(int Val, int CmpVal) {
3700   return (Val < 0 || Val == CmpVal);
3701 }
3702
3703 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3704 /// from position Pos and ending in Pos+Size, falls within the specified
3705 /// sequential range (L, L+Pos]. or is undef.
3706 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3707                                        unsigned Pos, unsigned Size, int Low) {
3708   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3709     if (!isUndefOrEqual(Mask[i], Low))
3710       return false;
3711   return true;
3712 }
3713
3714 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3715 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3716 /// the second operand.
3717 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3718   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3719     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3720   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3721     return (Mask[0] < 2 && Mask[1] < 2);
3722   return false;
3723 }
3724
3725 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3726 /// is suitable for input to PSHUFHW.
3727 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3728   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3729     return false;
3730
3731   // Lower quadword copied in order or undef.
3732   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3733     return false;
3734
3735   // Upper quadword shuffled.
3736   for (unsigned i = 4; i != 8; ++i)
3737     if (!isUndefOrInRange(Mask[i], 4, 8))
3738       return false;
3739
3740   if (VT == MVT::v16i16) {
3741     // Lower quadword copied in order or undef.
3742     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3743       return false;
3744
3745     // Upper quadword shuffled.
3746     for (unsigned i = 12; i != 16; ++i)
3747       if (!isUndefOrInRange(Mask[i], 12, 16))
3748         return false;
3749   }
3750
3751   return true;
3752 }
3753
3754 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3755 /// is suitable for input to PSHUFLW.
3756 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3757   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3758     return false;
3759
3760   // Upper quadword copied in order.
3761   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3762     return false;
3763
3764   // Lower quadword shuffled.
3765   for (unsigned i = 0; i != 4; ++i)
3766     if (!isUndefOrInRange(Mask[i], 0, 4))
3767       return false;
3768
3769   if (VT == MVT::v16i16) {
3770     // Upper quadword copied in order.
3771     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3772       return false;
3773
3774     // Lower quadword shuffled.
3775     for (unsigned i = 8; i != 12; ++i)
3776       if (!isUndefOrInRange(Mask[i], 8, 12))
3777         return false;
3778   }
3779
3780   return true;
3781 }
3782
3783 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3784 /// is suitable for input to PALIGNR.
3785 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3786                           const X86Subtarget *Subtarget) {
3787   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3788       (VT.is256BitVector() && !Subtarget->hasInt256()))
3789     return false;
3790
3791   unsigned NumElts = VT.getVectorNumElements();
3792   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3793   unsigned NumLaneElts = NumElts/NumLanes;
3794
3795   // Do not handle 64-bit element shuffles with palignr.
3796   if (NumLaneElts == 2)
3797     return false;
3798
3799   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3800     unsigned i;
3801     for (i = 0; i != NumLaneElts; ++i) {
3802       if (Mask[i+l] >= 0)
3803         break;
3804     }
3805
3806     // Lane is all undef, go to next lane
3807     if (i == NumLaneElts)
3808       continue;
3809
3810     int Start = Mask[i+l];
3811
3812     // Make sure its in this lane in one of the sources
3813     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3814         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3815       return false;
3816
3817     // If not lane 0, then we must match lane 0
3818     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3819       return false;
3820
3821     // Correct second source to be contiguous with first source
3822     if (Start >= (int)NumElts)
3823       Start -= NumElts - NumLaneElts;
3824
3825     // Make sure we're shifting in the right direction.
3826     if (Start <= (int)(i+l))
3827       return false;
3828
3829     Start -= i;
3830
3831     // Check the rest of the elements to see if they are consecutive.
3832     for (++i; i != NumLaneElts; ++i) {
3833       int Idx = Mask[i+l];
3834
3835       // Make sure its in this lane
3836       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3837           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3838         return false;
3839
3840       // If not lane 0, then we must match lane 0
3841       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3842         return false;
3843
3844       if (Idx >= (int)NumElts)
3845         Idx -= NumElts - NumLaneElts;
3846
3847       if (!isUndefOrEqual(Idx, Start+i))
3848         return false;
3849
3850     }
3851   }
3852
3853   return true;
3854 }
3855
3856 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3857 /// the two vector operands have swapped position.
3858 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3859                                      unsigned NumElems) {
3860   for (unsigned i = 0; i != NumElems; ++i) {
3861     int idx = Mask[i];
3862     if (idx < 0)
3863       continue;
3864     else if (idx < (int)NumElems)
3865       Mask[i] = idx + NumElems;
3866     else
3867       Mask[i] = idx - NumElems;
3868   }
3869 }
3870
3871 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3872 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3873 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3874 /// reverse of what x86 shuffles want.
3875 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3876
3877   unsigned NumElems = VT.getVectorNumElements();
3878   unsigned NumLanes = VT.getSizeInBits()/128;
3879   unsigned NumLaneElems = NumElems/NumLanes;
3880
3881   if (NumLaneElems != 2 && NumLaneElems != 4)
3882     return false;
3883
3884   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3885   bool symetricMaskRequired =
3886     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3887
3888   // VSHUFPSY divides the resulting vector into 4 chunks.
3889   // The sources are also splitted into 4 chunks, and each destination
3890   // chunk must come from a different source chunk.
3891   //
3892   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3893   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3894   //
3895   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3896   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3897   //
3898   // VSHUFPDY divides the resulting vector into 4 chunks.
3899   // The sources are also splitted into 4 chunks, and each destination
3900   // chunk must come from a different source chunk.
3901   //
3902   //  SRC1 =>      X3       X2       X1       X0
3903   //  SRC2 =>      Y3       Y2       Y1       Y0
3904   //
3905   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3906   //
3907   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3908   unsigned HalfLaneElems = NumLaneElems/2;
3909   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3910     for (unsigned i = 0; i != NumLaneElems; ++i) {
3911       int Idx = Mask[i+l];
3912       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3913       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3914         return false;
3915       // For VSHUFPSY, the mask of the second half must be the same as the
3916       // first but with the appropriate offsets. This works in the same way as
3917       // VPERMILPS works with masks.
3918       if (!symetricMaskRequired || Idx < 0)
3919         continue;
3920       if (MaskVal[i] < 0) {
3921         MaskVal[i] = Idx - l;
3922         continue;
3923       }
3924       if ((signed)(Idx - l) != MaskVal[i])
3925         return false;
3926     }
3927   }
3928
3929   return true;
3930 }
3931
3932 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3933 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3934 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3935   if (!VT.is128BitVector())
3936     return false;
3937
3938   unsigned NumElems = VT.getVectorNumElements();
3939
3940   if (NumElems != 4)
3941     return false;
3942
3943   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3944   return isUndefOrEqual(Mask[0], 6) &&
3945          isUndefOrEqual(Mask[1], 7) &&
3946          isUndefOrEqual(Mask[2], 2) &&
3947          isUndefOrEqual(Mask[3], 3);
3948 }
3949
3950 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3951 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3952 /// <2, 3, 2, 3>
3953 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3954   if (!VT.is128BitVector())
3955     return false;
3956
3957   unsigned NumElems = VT.getVectorNumElements();
3958
3959   if (NumElems != 4)
3960     return false;
3961
3962   return isUndefOrEqual(Mask[0], 2) &&
3963          isUndefOrEqual(Mask[1], 3) &&
3964          isUndefOrEqual(Mask[2], 2) &&
3965          isUndefOrEqual(Mask[3], 3);
3966 }
3967
3968 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3969 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3970 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3971   if (!VT.is128BitVector())
3972     return false;
3973
3974   unsigned NumElems = VT.getVectorNumElements();
3975
3976   if (NumElems != 2 && NumElems != 4)
3977     return false;
3978
3979   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3980     if (!isUndefOrEqual(Mask[i], i + NumElems))
3981       return false;
3982
3983   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3984     if (!isUndefOrEqual(Mask[i], i))
3985       return false;
3986
3987   return true;
3988 }
3989
3990 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3991 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3992 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3993   if (!VT.is128BitVector())
3994     return false;
3995
3996   unsigned NumElems = VT.getVectorNumElements();
3997
3998   if (NumElems != 2 && NumElems != 4)
3999     return false;
4000
4001   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4002     if (!isUndefOrEqual(Mask[i], i))
4003       return false;
4004
4005   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4006     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4007       return false;
4008
4009   return true;
4010 }
4011
4012 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4013 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4014 /// i. e: If all but one element come from the same vector.
4015 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4016   // TODO: Deal with AVX's VINSERTPS
4017   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4018     return false;
4019
4020   unsigned CorrectPosV1 = 0;
4021   unsigned CorrectPosV2 = 0;
4022   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4023     if (Mask[i] == -1) {
4024       ++CorrectPosV1;
4025       ++CorrectPosV2;
4026       continue;
4027     }
4028
4029     if (Mask[i] == i)
4030       ++CorrectPosV1;
4031     else if (Mask[i] == i + 4)
4032       ++CorrectPosV2;
4033   }
4034
4035   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4036     // We have 3 elements (undefs count as elements from any vector) from one
4037     // vector, and one from another.
4038     return true;
4039
4040   return false;
4041 }
4042
4043 //
4044 // Some special combinations that can be optimized.
4045 //
4046 static
4047 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4048                                SelectionDAG &DAG) {
4049   MVT VT = SVOp->getSimpleValueType(0);
4050   SDLoc dl(SVOp);
4051
4052   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4053     return SDValue();
4054
4055   ArrayRef<int> Mask = SVOp->getMask();
4056
4057   // These are the special masks that may be optimized.
4058   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4059   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4060   bool MatchEvenMask = true;
4061   bool MatchOddMask  = true;
4062   for (int i=0; i<8; ++i) {
4063     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4064       MatchEvenMask = false;
4065     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4066       MatchOddMask = false;
4067   }
4068
4069   if (!MatchEvenMask && !MatchOddMask)
4070     return SDValue();
4071
4072   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4073
4074   SDValue Op0 = SVOp->getOperand(0);
4075   SDValue Op1 = SVOp->getOperand(1);
4076
4077   if (MatchEvenMask) {
4078     // Shift the second operand right to 32 bits.
4079     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4080     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4081   } else {
4082     // Shift the first operand left to 32 bits.
4083     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4084     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4085   }
4086   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4087   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4088 }
4089
4090 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4091 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4092 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4093                          bool HasInt256, bool V2IsSplat = false) {
4094
4095   assert(VT.getSizeInBits() >= 128 &&
4096          "Unsupported vector type for unpckl");
4097
4098   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4099   unsigned NumLanes;
4100   unsigned NumOf256BitLanes;
4101   unsigned NumElts = VT.getVectorNumElements();
4102   if (VT.is256BitVector()) {
4103     if (NumElts != 4 && NumElts != 8 &&
4104         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4105     return false;
4106     NumLanes = 2;
4107     NumOf256BitLanes = 1;
4108   } else if (VT.is512BitVector()) {
4109     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4110            "Unsupported vector type for unpckh");
4111     NumLanes = 2;
4112     NumOf256BitLanes = 2;
4113   } else {
4114     NumLanes = 1;
4115     NumOf256BitLanes = 1;
4116   }
4117
4118   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4119   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4120
4121   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4122     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4123       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4124         int BitI  = Mask[l256*NumEltsInStride+l+i];
4125         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4126         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4127           return false;
4128         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4129           return false;
4130         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4131           return false;
4132       }
4133     }
4134   }
4135   return true;
4136 }
4137
4138 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4139 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4140 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4141                          bool HasInt256, bool V2IsSplat = false) {
4142   assert(VT.getSizeInBits() >= 128 &&
4143          "Unsupported vector type for unpckh");
4144
4145   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4146   unsigned NumLanes;
4147   unsigned NumOf256BitLanes;
4148   unsigned NumElts = VT.getVectorNumElements();
4149   if (VT.is256BitVector()) {
4150     if (NumElts != 4 && NumElts != 8 &&
4151         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4152     return false;
4153     NumLanes = 2;
4154     NumOf256BitLanes = 1;
4155   } else if (VT.is512BitVector()) {
4156     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4157            "Unsupported vector type for unpckh");
4158     NumLanes = 2;
4159     NumOf256BitLanes = 2;
4160   } else {
4161     NumLanes = 1;
4162     NumOf256BitLanes = 1;
4163   }
4164
4165   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4166   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4167
4168   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4169     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4170       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4171         int BitI  = Mask[l256*NumEltsInStride+l+i];
4172         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4173         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4174           return false;
4175         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4176           return false;
4177         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4178           return false;
4179       }
4180     }
4181   }
4182   return true;
4183 }
4184
4185 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4186 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4187 /// <0, 0, 1, 1>
4188 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4189   unsigned NumElts = VT.getVectorNumElements();
4190   bool Is256BitVec = VT.is256BitVector();
4191
4192   if (VT.is512BitVector())
4193     return false;
4194   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4195          "Unsupported vector type for unpckh");
4196
4197   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4198       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4199     return false;
4200
4201   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4202   // FIXME: Need a better way to get rid of this, there's no latency difference
4203   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4204   // the former later. We should also remove the "_undef" special mask.
4205   if (NumElts == 4 && Is256BitVec)
4206     return false;
4207
4208   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4209   // independently on 128-bit lanes.
4210   unsigned NumLanes = VT.getSizeInBits()/128;
4211   unsigned NumLaneElts = NumElts/NumLanes;
4212
4213   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4214     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4215       int BitI  = Mask[l+i];
4216       int BitI1 = Mask[l+i+1];
4217
4218       if (!isUndefOrEqual(BitI, j))
4219         return false;
4220       if (!isUndefOrEqual(BitI1, j))
4221         return false;
4222     }
4223   }
4224
4225   return true;
4226 }
4227
4228 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4229 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4230 /// <2, 2, 3, 3>
4231 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4232   unsigned NumElts = VT.getVectorNumElements();
4233
4234   if (VT.is512BitVector())
4235     return false;
4236
4237   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4238          "Unsupported vector type for unpckh");
4239
4240   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4241       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4242     return false;
4243
4244   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4245   // independently on 128-bit lanes.
4246   unsigned NumLanes = VT.getSizeInBits()/128;
4247   unsigned NumLaneElts = NumElts/NumLanes;
4248
4249   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4250     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4251       int BitI  = Mask[l+i];
4252       int BitI1 = Mask[l+i+1];
4253       if (!isUndefOrEqual(BitI, j))
4254         return false;
4255       if (!isUndefOrEqual(BitI1, j))
4256         return false;
4257     }
4258   }
4259   return true;
4260 }
4261
4262 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4263 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4264 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4265   if (!VT.is512BitVector())
4266     return false;
4267
4268   unsigned NumElts = VT.getVectorNumElements();
4269   unsigned HalfSize = NumElts/2;
4270   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4271     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4272       *Imm = 1;
4273       return true;
4274     }
4275   }
4276   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4277     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4278       *Imm = 0;
4279       return true;
4280     }
4281   }
4282   return false;
4283 }
4284
4285 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4286 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4287 /// MOVSD, and MOVD, i.e. setting the lowest element.
4288 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4289   if (VT.getVectorElementType().getSizeInBits() < 32)
4290     return false;
4291   if (!VT.is128BitVector())
4292     return false;
4293
4294   unsigned NumElts = VT.getVectorNumElements();
4295
4296   if (!isUndefOrEqual(Mask[0], NumElts))
4297     return false;
4298
4299   for (unsigned i = 1; i != NumElts; ++i)
4300     if (!isUndefOrEqual(Mask[i], i))
4301       return false;
4302
4303   return true;
4304 }
4305
4306 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4307 /// as permutations between 128-bit chunks or halves. As an example: this
4308 /// shuffle bellow:
4309 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4310 /// The first half comes from the second half of V1 and the second half from the
4311 /// the second half of V2.
4312 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4313   if (!HasFp256 || !VT.is256BitVector())
4314     return false;
4315
4316   // The shuffle result is divided into half A and half B. In total the two
4317   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4318   // B must come from C, D, E or F.
4319   unsigned HalfSize = VT.getVectorNumElements()/2;
4320   bool MatchA = false, MatchB = false;
4321
4322   // Check if A comes from one of C, D, E, F.
4323   for (unsigned Half = 0; Half != 4; ++Half) {
4324     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4325       MatchA = true;
4326       break;
4327     }
4328   }
4329
4330   // Check if B comes from one of C, D, E, F.
4331   for (unsigned Half = 0; Half != 4; ++Half) {
4332     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4333       MatchB = true;
4334       break;
4335     }
4336   }
4337
4338   return MatchA && MatchB;
4339 }
4340
4341 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4342 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4343 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4344   MVT VT = SVOp->getSimpleValueType(0);
4345
4346   unsigned HalfSize = VT.getVectorNumElements()/2;
4347
4348   unsigned FstHalf = 0, SndHalf = 0;
4349   for (unsigned i = 0; i < HalfSize; ++i) {
4350     if (SVOp->getMaskElt(i) > 0) {
4351       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4352       break;
4353     }
4354   }
4355   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4356     if (SVOp->getMaskElt(i) > 0) {
4357       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4358       break;
4359     }
4360   }
4361
4362   return (FstHalf | (SndHalf << 4));
4363 }
4364
4365 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4366 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4367   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4368   if (EltSize < 32)
4369     return false;
4370
4371   unsigned NumElts = VT.getVectorNumElements();
4372   Imm8 = 0;
4373   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4374     for (unsigned i = 0; i != NumElts; ++i) {
4375       if (Mask[i] < 0)
4376         continue;
4377       Imm8 |= Mask[i] << (i*2);
4378     }
4379     return true;
4380   }
4381
4382   unsigned LaneSize = 4;
4383   SmallVector<int, 4> MaskVal(LaneSize, -1);
4384
4385   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4386     for (unsigned i = 0; i != LaneSize; ++i) {
4387       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4388         return false;
4389       if (Mask[i+l] < 0)
4390         continue;
4391       if (MaskVal[i] < 0) {
4392         MaskVal[i] = Mask[i+l] - l;
4393         Imm8 |= MaskVal[i] << (i*2);
4394         continue;
4395       }
4396       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4397         return false;
4398     }
4399   }
4400   return true;
4401 }
4402
4403 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4404 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4405 /// Note that VPERMIL mask matching is different depending whether theunderlying
4406 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4407 /// to the same elements of the low, but to the higher half of the source.
4408 /// In VPERMILPD the two lanes could be shuffled independently of each other
4409 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4410 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4411   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4412   if (VT.getSizeInBits() < 256 || EltSize < 32)
4413     return false;
4414   bool symetricMaskRequired = (EltSize == 32);
4415   unsigned NumElts = VT.getVectorNumElements();
4416
4417   unsigned NumLanes = VT.getSizeInBits()/128;
4418   unsigned LaneSize = NumElts/NumLanes;
4419   // 2 or 4 elements in one lane
4420
4421   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4422   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4423     for (unsigned i = 0; i != LaneSize; ++i) {
4424       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4425         return false;
4426       if (symetricMaskRequired) {
4427         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4428           ExpectedMaskVal[i] = Mask[i+l] - l;
4429           continue;
4430         }
4431         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4432           return false;
4433       }
4434     }
4435   }
4436   return true;
4437 }
4438
4439 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4440 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4441 /// element of vector 2 and the other elements to come from vector 1 in order.
4442 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4443                                bool V2IsSplat = false, bool V2IsUndef = false) {
4444   if (!VT.is128BitVector())
4445     return false;
4446
4447   unsigned NumOps = VT.getVectorNumElements();
4448   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4449     return false;
4450
4451   if (!isUndefOrEqual(Mask[0], 0))
4452     return false;
4453
4454   for (unsigned i = 1; i != NumOps; ++i)
4455     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4456           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4457           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4458       return false;
4459
4460   return true;
4461 }
4462
4463 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4464 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4465 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4466 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4467                            const X86Subtarget *Subtarget) {
4468   if (!Subtarget->hasSSE3())
4469     return false;
4470
4471   unsigned NumElems = VT.getVectorNumElements();
4472
4473   if ((VT.is128BitVector() && NumElems != 4) ||
4474       (VT.is256BitVector() && NumElems != 8) ||
4475       (VT.is512BitVector() && NumElems != 16))
4476     return false;
4477
4478   // "i+1" is the value the indexed mask element must have
4479   for (unsigned i = 0; i != NumElems; i += 2)
4480     if (!isUndefOrEqual(Mask[i], i+1) ||
4481         !isUndefOrEqual(Mask[i+1], i+1))
4482       return false;
4483
4484   return true;
4485 }
4486
4487 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4488 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4489 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4490 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4491                            const X86Subtarget *Subtarget) {
4492   if (!Subtarget->hasSSE3())
4493     return false;
4494
4495   unsigned NumElems = VT.getVectorNumElements();
4496
4497   if ((VT.is128BitVector() && NumElems != 4) ||
4498       (VT.is256BitVector() && NumElems != 8) ||
4499       (VT.is512BitVector() && NumElems != 16))
4500     return false;
4501
4502   // "i" is the value the indexed mask element must have
4503   for (unsigned i = 0; i != NumElems; i += 2)
4504     if (!isUndefOrEqual(Mask[i], i) ||
4505         !isUndefOrEqual(Mask[i+1], i))
4506       return false;
4507
4508   return true;
4509 }
4510
4511 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4512 /// specifies a shuffle of elements that is suitable for input to 256-bit
4513 /// version of MOVDDUP.
4514 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4515   if (!HasFp256 || !VT.is256BitVector())
4516     return false;
4517
4518   unsigned NumElts = VT.getVectorNumElements();
4519   if (NumElts != 4)
4520     return false;
4521
4522   for (unsigned i = 0; i != NumElts/2; ++i)
4523     if (!isUndefOrEqual(Mask[i], 0))
4524       return false;
4525   for (unsigned i = NumElts/2; i != NumElts; ++i)
4526     if (!isUndefOrEqual(Mask[i], NumElts/2))
4527       return false;
4528   return true;
4529 }
4530
4531 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4532 /// specifies a shuffle of elements that is suitable for input to 128-bit
4533 /// version of MOVDDUP.
4534 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4535   if (!VT.is128BitVector())
4536     return false;
4537
4538   unsigned e = VT.getVectorNumElements() / 2;
4539   for (unsigned i = 0; i != e; ++i)
4540     if (!isUndefOrEqual(Mask[i], i))
4541       return false;
4542   for (unsigned i = 0; i != e; ++i)
4543     if (!isUndefOrEqual(Mask[e+i], i))
4544       return false;
4545   return true;
4546 }
4547
4548 /// isVEXTRACTIndex - Return true if the specified
4549 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4550 /// suitable for instruction that extract 128 or 256 bit vectors
4551 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4552   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4553   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4554     return false;
4555
4556   // The index should be aligned on a vecWidth-bit boundary.
4557   uint64_t Index =
4558     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4559
4560   MVT VT = N->getSimpleValueType(0);
4561   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4562   bool Result = (Index * ElSize) % vecWidth == 0;
4563
4564   return Result;
4565 }
4566
4567 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4568 /// operand specifies a subvector insert that is suitable for input to
4569 /// insertion of 128 or 256-bit subvectors
4570 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4571   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4572   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4573     return false;
4574   // The index should be aligned on a vecWidth-bit boundary.
4575   uint64_t Index =
4576     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4577
4578   MVT VT = N->getSimpleValueType(0);
4579   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4580   bool Result = (Index * ElSize) % vecWidth == 0;
4581
4582   return Result;
4583 }
4584
4585 bool X86::isVINSERT128Index(SDNode *N) {
4586   return isVINSERTIndex(N, 128);
4587 }
4588
4589 bool X86::isVINSERT256Index(SDNode *N) {
4590   return isVINSERTIndex(N, 256);
4591 }
4592
4593 bool X86::isVEXTRACT128Index(SDNode *N) {
4594   return isVEXTRACTIndex(N, 128);
4595 }
4596
4597 bool X86::isVEXTRACT256Index(SDNode *N) {
4598   return isVEXTRACTIndex(N, 256);
4599 }
4600
4601 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4602 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4603 /// Handles 128-bit and 256-bit.
4604 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4605   MVT VT = N->getSimpleValueType(0);
4606
4607   assert((VT.getSizeInBits() >= 128) &&
4608          "Unsupported vector type for PSHUF/SHUFP");
4609
4610   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4611   // independently on 128-bit lanes.
4612   unsigned NumElts = VT.getVectorNumElements();
4613   unsigned NumLanes = VT.getSizeInBits()/128;
4614   unsigned NumLaneElts = NumElts/NumLanes;
4615
4616   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4617          "Only supports 2, 4 or 8 elements per lane");
4618
4619   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4620   unsigned Mask = 0;
4621   for (unsigned i = 0; i != NumElts; ++i) {
4622     int Elt = N->getMaskElt(i);
4623     if (Elt < 0) continue;
4624     Elt &= NumLaneElts - 1;
4625     unsigned ShAmt = (i << Shift) % 8;
4626     Mask |= Elt << ShAmt;
4627   }
4628
4629   return Mask;
4630 }
4631
4632 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4633 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4634 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4635   MVT VT = N->getSimpleValueType(0);
4636
4637   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4638          "Unsupported vector type for PSHUFHW");
4639
4640   unsigned NumElts = VT.getVectorNumElements();
4641
4642   unsigned Mask = 0;
4643   for (unsigned l = 0; l != NumElts; l += 8) {
4644     // 8 nodes per lane, but we only care about the last 4.
4645     for (unsigned i = 0; i < 4; ++i) {
4646       int Elt = N->getMaskElt(l+i+4);
4647       if (Elt < 0) continue;
4648       Elt &= 0x3; // only 2-bits.
4649       Mask |= Elt << (i * 2);
4650     }
4651   }
4652
4653   return Mask;
4654 }
4655
4656 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4657 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4658 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4659   MVT VT = N->getSimpleValueType(0);
4660
4661   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4662          "Unsupported vector type for PSHUFHW");
4663
4664   unsigned NumElts = VT.getVectorNumElements();
4665
4666   unsigned Mask = 0;
4667   for (unsigned l = 0; l != NumElts; l += 8) {
4668     // 8 nodes per lane, but we only care about the first 4.
4669     for (unsigned i = 0; i < 4; ++i) {
4670       int Elt = N->getMaskElt(l+i);
4671       if (Elt < 0) continue;
4672       Elt &= 0x3; // only 2-bits
4673       Mask |= Elt << (i * 2);
4674     }
4675   }
4676
4677   return Mask;
4678 }
4679
4680 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4681 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4682 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4683   MVT VT = SVOp->getSimpleValueType(0);
4684   unsigned EltSize = VT.is512BitVector() ? 1 :
4685     VT.getVectorElementType().getSizeInBits() >> 3;
4686
4687   unsigned NumElts = VT.getVectorNumElements();
4688   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4689   unsigned NumLaneElts = NumElts/NumLanes;
4690
4691   int Val = 0;
4692   unsigned i;
4693   for (i = 0; i != NumElts; ++i) {
4694     Val = SVOp->getMaskElt(i);
4695     if (Val >= 0)
4696       break;
4697   }
4698   if (Val >= (int)NumElts)
4699     Val -= NumElts - NumLaneElts;
4700
4701   assert(Val - i > 0 && "PALIGNR imm should be positive");
4702   return (Val - i) * EltSize;
4703 }
4704
4705 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4706   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4707   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4708     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4709
4710   uint64_t Index =
4711     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4712
4713   MVT VecVT = N->getOperand(0).getSimpleValueType();
4714   MVT ElVT = VecVT.getVectorElementType();
4715
4716   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4717   return Index / NumElemsPerChunk;
4718 }
4719
4720 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4721   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4722   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4723     llvm_unreachable("Illegal insert subvector for VINSERT");
4724
4725   uint64_t Index =
4726     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4727
4728   MVT VecVT = N->getSimpleValueType(0);
4729   MVT ElVT = VecVT.getVectorElementType();
4730
4731   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4732   return Index / NumElemsPerChunk;
4733 }
4734
4735 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4736 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4737 /// and VINSERTI128 instructions.
4738 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4739   return getExtractVEXTRACTImmediate(N, 128);
4740 }
4741
4742 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4743 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4744 /// and VINSERTI64x4 instructions.
4745 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4746   return getExtractVEXTRACTImmediate(N, 256);
4747 }
4748
4749 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4750 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4751 /// and VINSERTI128 instructions.
4752 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4753   return getInsertVINSERTImmediate(N, 128);
4754 }
4755
4756 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4757 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4758 /// and VINSERTI64x4 instructions.
4759 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4760   return getInsertVINSERTImmediate(N, 256);
4761 }
4762
4763 /// isZero - Returns true if Elt is a constant integer zero
4764 static bool isZero(SDValue V) {
4765   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4766   return C && C->isNullValue();
4767 }
4768
4769 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4770 /// constant +0.0.
4771 bool X86::isZeroNode(SDValue Elt) {
4772   if (isZero(Elt))
4773     return true;
4774   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4775     return CFP->getValueAPF().isPosZero();
4776   return false;
4777 }
4778
4779 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4780 /// match movhlps. The lower half elements should come from upper half of
4781 /// V1 (and in order), and the upper half elements should come from the upper
4782 /// half of V2 (and in order).
4783 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4784   if (!VT.is128BitVector())
4785     return false;
4786   if (VT.getVectorNumElements() != 4)
4787     return false;
4788   for (unsigned i = 0, e = 2; i != e; ++i)
4789     if (!isUndefOrEqual(Mask[i], i+2))
4790       return false;
4791   for (unsigned i = 2; i != 4; ++i)
4792     if (!isUndefOrEqual(Mask[i], i+4))
4793       return false;
4794   return true;
4795 }
4796
4797 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4798 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4799 /// required.
4800 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4801   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4802     return false;
4803   N = N->getOperand(0).getNode();
4804   if (!ISD::isNON_EXTLoad(N))
4805     return false;
4806   if (LD)
4807     *LD = cast<LoadSDNode>(N);
4808   return true;
4809 }
4810
4811 // Test whether the given value is a vector value which will be legalized
4812 // into a load.
4813 static bool WillBeConstantPoolLoad(SDNode *N) {
4814   if (N->getOpcode() != ISD::BUILD_VECTOR)
4815     return false;
4816
4817   // Check for any non-constant elements.
4818   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4819     switch (N->getOperand(i).getNode()->getOpcode()) {
4820     case ISD::UNDEF:
4821     case ISD::ConstantFP:
4822     case ISD::Constant:
4823       break;
4824     default:
4825       return false;
4826     }
4827
4828   // Vectors of all-zeros and all-ones are materialized with special
4829   // instructions rather than being loaded.
4830   return !ISD::isBuildVectorAllZeros(N) &&
4831          !ISD::isBuildVectorAllOnes(N);
4832 }
4833
4834 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4835 /// match movlp{s|d}. The lower half elements should come from lower half of
4836 /// V1 (and in order), and the upper half elements should come from the upper
4837 /// half of V2 (and in order). And since V1 will become the source of the
4838 /// MOVLP, it must be either a vector load or a scalar load to vector.
4839 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4840                                ArrayRef<int> Mask, MVT VT) {
4841   if (!VT.is128BitVector())
4842     return false;
4843
4844   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4845     return false;
4846   // Is V2 is a vector load, don't do this transformation. We will try to use
4847   // load folding shufps op.
4848   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4849     return false;
4850
4851   unsigned NumElems = VT.getVectorNumElements();
4852
4853   if (NumElems != 2 && NumElems != 4)
4854     return false;
4855   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4856     if (!isUndefOrEqual(Mask[i], i))
4857       return false;
4858   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4859     if (!isUndefOrEqual(Mask[i], i+NumElems))
4860       return false;
4861   return true;
4862 }
4863
4864 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4865 /// to an zero vector.
4866 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4867 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4868   SDValue V1 = N->getOperand(0);
4869   SDValue V2 = N->getOperand(1);
4870   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4871   for (unsigned i = 0; i != NumElems; ++i) {
4872     int Idx = N->getMaskElt(i);
4873     if (Idx >= (int)NumElems) {
4874       unsigned Opc = V2.getOpcode();
4875       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4876         continue;
4877       if (Opc != ISD::BUILD_VECTOR ||
4878           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4879         return false;
4880     } else if (Idx >= 0) {
4881       unsigned Opc = V1.getOpcode();
4882       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4883         continue;
4884       if (Opc != ISD::BUILD_VECTOR ||
4885           !X86::isZeroNode(V1.getOperand(Idx)))
4886         return false;
4887     }
4888   }
4889   return true;
4890 }
4891
4892 /// getZeroVector - Returns a vector of specified type with all zero elements.
4893 ///
4894 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4895                              SelectionDAG &DAG, SDLoc dl) {
4896   assert(VT.isVector() && "Expected a vector type");
4897
4898   // Always build SSE zero vectors as <4 x i32> bitcasted
4899   // to their dest type. This ensures they get CSE'd.
4900   SDValue Vec;
4901   if (VT.is128BitVector()) {  // SSE
4902     if (Subtarget->hasSSE2()) {  // SSE2
4903       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4904       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4905     } else { // SSE1
4906       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4907       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4908     }
4909   } else if (VT.is256BitVector()) { // AVX
4910     if (Subtarget->hasInt256()) { // AVX2
4911       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4912       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4913       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4914     } else {
4915       // 256-bit logic and arithmetic instructions in AVX are all
4916       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4917       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4918       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4919       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4920     }
4921   } else if (VT.is512BitVector()) { // AVX-512
4922       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4923       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4924                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4925       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4926   } else if (VT.getScalarType() == MVT::i1) {
4927     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4928     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4929     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4930     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4931   } else
4932     llvm_unreachable("Unexpected vector type");
4933
4934   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4935 }
4936
4937 /// getOnesVector - Returns a vector of specified type with all bits set.
4938 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4939 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4940 /// Then bitcast to their original type, ensuring they get CSE'd.
4941 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4942                              SDLoc dl) {
4943   assert(VT.isVector() && "Expected a vector type");
4944
4945   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4946   SDValue Vec;
4947   if (VT.is256BitVector()) {
4948     if (HasInt256) { // AVX2
4949       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4950       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4951     } else { // AVX
4952       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4953       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4954     }
4955   } else if (VT.is128BitVector()) {
4956     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4957   } else
4958     llvm_unreachable("Unexpected vector type");
4959
4960   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4961 }
4962
4963 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4964 /// that point to V2 points to its first element.
4965 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4966   for (unsigned i = 0; i != NumElems; ++i) {
4967     if (Mask[i] > (int)NumElems) {
4968       Mask[i] = NumElems;
4969     }
4970   }
4971 }
4972
4973 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4974 /// operation of specified width.
4975 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4976                        SDValue V2) {
4977   unsigned NumElems = VT.getVectorNumElements();
4978   SmallVector<int, 8> Mask;
4979   Mask.push_back(NumElems);
4980   for (unsigned i = 1; i != NumElems; ++i)
4981     Mask.push_back(i);
4982   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4983 }
4984
4985 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4986 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4987                           SDValue V2) {
4988   unsigned NumElems = VT.getVectorNumElements();
4989   SmallVector<int, 8> Mask;
4990   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4991     Mask.push_back(i);
4992     Mask.push_back(i + NumElems);
4993   }
4994   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4995 }
4996
4997 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4998 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4999                           SDValue V2) {
5000   unsigned NumElems = VT.getVectorNumElements();
5001   SmallVector<int, 8> Mask;
5002   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5003     Mask.push_back(i + Half);
5004     Mask.push_back(i + NumElems + Half);
5005   }
5006   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5007 }
5008
5009 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5010 // a generic shuffle instruction because the target has no such instructions.
5011 // Generate shuffles which repeat i16 and i8 several times until they can be
5012 // represented by v4f32 and then be manipulated by target suported shuffles.
5013 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5014   MVT VT = V.getSimpleValueType();
5015   int NumElems = VT.getVectorNumElements();
5016   SDLoc dl(V);
5017
5018   while (NumElems > 4) {
5019     if (EltNo < NumElems/2) {
5020       V = getUnpackl(DAG, dl, VT, V, V);
5021     } else {
5022       V = getUnpackh(DAG, dl, VT, V, V);
5023       EltNo -= NumElems/2;
5024     }
5025     NumElems >>= 1;
5026   }
5027   return V;
5028 }
5029
5030 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5031 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5032   MVT VT = V.getSimpleValueType();
5033   SDLoc dl(V);
5034
5035   if (VT.is128BitVector()) {
5036     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5037     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5038     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5039                              &SplatMask[0]);
5040   } else if (VT.is256BitVector()) {
5041     // To use VPERMILPS to splat scalars, the second half of indicies must
5042     // refer to the higher part, which is a duplication of the lower one,
5043     // because VPERMILPS can only handle in-lane permutations.
5044     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5045                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5046
5047     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5048     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5049                              &SplatMask[0]);
5050   } else
5051     llvm_unreachable("Vector size not supported");
5052
5053   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5054 }
5055
5056 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5057 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5058   MVT SrcVT = SV->getSimpleValueType(0);
5059   SDValue V1 = SV->getOperand(0);
5060   SDLoc dl(SV);
5061
5062   int EltNo = SV->getSplatIndex();
5063   int NumElems = SrcVT.getVectorNumElements();
5064   bool Is256BitVec = SrcVT.is256BitVector();
5065
5066   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5067          "Unknown how to promote splat for type");
5068
5069   // Extract the 128-bit part containing the splat element and update
5070   // the splat element index when it refers to the higher register.
5071   if (Is256BitVec) {
5072     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5073     if (EltNo >= NumElems/2)
5074       EltNo -= NumElems/2;
5075   }
5076
5077   // All i16 and i8 vector types can't be used directly by a generic shuffle
5078   // instruction because the target has no such instruction. Generate shuffles
5079   // which repeat i16 and i8 several times until they fit in i32, and then can
5080   // be manipulated by target suported shuffles.
5081   MVT EltVT = SrcVT.getVectorElementType();
5082   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5083     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5084
5085   // Recreate the 256-bit vector and place the same 128-bit vector
5086   // into the low and high part. This is necessary because we want
5087   // to use VPERM* to shuffle the vectors
5088   if (Is256BitVec) {
5089     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5090   }
5091
5092   return getLegalSplat(DAG, V1, EltNo);
5093 }
5094
5095 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5096 /// vector of zero or undef vector.  This produces a shuffle where the low
5097 /// element of V2 is swizzled into the zero/undef vector, landing at element
5098 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5099 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5100                                            bool IsZero,
5101                                            const X86Subtarget *Subtarget,
5102                                            SelectionDAG &DAG) {
5103   MVT VT = V2.getSimpleValueType();
5104   SDValue V1 = IsZero
5105     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5106   unsigned NumElems = VT.getVectorNumElements();
5107   SmallVector<int, 16> MaskVec;
5108   for (unsigned i = 0; i != NumElems; ++i)
5109     // If this is the insertion idx, put the low elt of V2 here.
5110     MaskVec.push_back(i == Idx ? NumElems : i);
5111   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5112 }
5113
5114 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5115 /// target specific opcode. Returns true if the Mask could be calculated.
5116 /// Sets IsUnary to true if only uses one source.
5117 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5118                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5119   unsigned NumElems = VT.getVectorNumElements();
5120   SDValue ImmN;
5121
5122   IsUnary = false;
5123   switch(N->getOpcode()) {
5124   case X86ISD::SHUFP:
5125     ImmN = N->getOperand(N->getNumOperands()-1);
5126     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5127     break;
5128   case X86ISD::UNPCKH:
5129     DecodeUNPCKHMask(VT, Mask);
5130     break;
5131   case X86ISD::UNPCKL:
5132     DecodeUNPCKLMask(VT, Mask);
5133     break;
5134   case X86ISD::MOVHLPS:
5135     DecodeMOVHLPSMask(NumElems, Mask);
5136     break;
5137   case X86ISD::MOVLHPS:
5138     DecodeMOVLHPSMask(NumElems, Mask);
5139     break;
5140   case X86ISD::PALIGNR:
5141     ImmN = N->getOperand(N->getNumOperands()-1);
5142     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5143     break;
5144   case X86ISD::PSHUFD:
5145   case X86ISD::VPERMILP:
5146     ImmN = N->getOperand(N->getNumOperands()-1);
5147     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5148     IsUnary = true;
5149     break;
5150   case X86ISD::PSHUFHW:
5151     ImmN = N->getOperand(N->getNumOperands()-1);
5152     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5153     IsUnary = true;
5154     break;
5155   case X86ISD::PSHUFLW:
5156     ImmN = N->getOperand(N->getNumOperands()-1);
5157     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5158     IsUnary = true;
5159     break;
5160   case X86ISD::VPERMI:
5161     ImmN = N->getOperand(N->getNumOperands()-1);
5162     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5163     IsUnary = true;
5164     break;
5165   case X86ISD::MOVSS:
5166   case X86ISD::MOVSD: {
5167     // The index 0 always comes from the first element of the second source,
5168     // this is why MOVSS and MOVSD are used in the first place. The other
5169     // elements come from the other positions of the first source vector
5170     Mask.push_back(NumElems);
5171     for (unsigned i = 1; i != NumElems; ++i) {
5172       Mask.push_back(i);
5173     }
5174     break;
5175   }
5176   case X86ISD::VPERM2X128:
5177     ImmN = N->getOperand(N->getNumOperands()-1);
5178     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5179     if (Mask.empty()) return false;
5180     break;
5181   case X86ISD::MOVDDUP:
5182   case X86ISD::MOVLHPD:
5183   case X86ISD::MOVLPD:
5184   case X86ISD::MOVLPS:
5185   case X86ISD::MOVSHDUP:
5186   case X86ISD::MOVSLDUP:
5187     // Not yet implemented
5188     return false;
5189   default: llvm_unreachable("unknown target shuffle node");
5190   }
5191
5192   return true;
5193 }
5194
5195 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5196 /// element of the result of the vector shuffle.
5197 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5198                                    unsigned Depth) {
5199   if (Depth == 6)
5200     return SDValue();  // Limit search depth.
5201
5202   SDValue V = SDValue(N, 0);
5203   EVT VT = V.getValueType();
5204   unsigned Opcode = V.getOpcode();
5205
5206   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5207   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5208     int Elt = SV->getMaskElt(Index);
5209
5210     if (Elt < 0)
5211       return DAG.getUNDEF(VT.getVectorElementType());
5212
5213     unsigned NumElems = VT.getVectorNumElements();
5214     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5215                                          : SV->getOperand(1);
5216     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5217   }
5218
5219   // Recurse into target specific vector shuffles to find scalars.
5220   if (isTargetShuffle(Opcode)) {
5221     MVT ShufVT = V.getSimpleValueType();
5222     unsigned NumElems = ShufVT.getVectorNumElements();
5223     SmallVector<int, 16> ShuffleMask;
5224     bool IsUnary;
5225
5226     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5227       return SDValue();
5228
5229     int Elt = ShuffleMask[Index];
5230     if (Elt < 0)
5231       return DAG.getUNDEF(ShufVT.getVectorElementType());
5232
5233     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5234                                          : N->getOperand(1);
5235     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5236                                Depth+1);
5237   }
5238
5239   // Actual nodes that may contain scalar elements
5240   if (Opcode == ISD::BITCAST) {
5241     V = V.getOperand(0);
5242     EVT SrcVT = V.getValueType();
5243     unsigned NumElems = VT.getVectorNumElements();
5244
5245     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5246       return SDValue();
5247   }
5248
5249   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5250     return (Index == 0) ? V.getOperand(0)
5251                         : DAG.getUNDEF(VT.getVectorElementType());
5252
5253   if (V.getOpcode() == ISD::BUILD_VECTOR)
5254     return V.getOperand(Index);
5255
5256   return SDValue();
5257 }
5258
5259 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5260 /// shuffle operation which come from a consecutively from a zero. The
5261 /// search can start in two different directions, from left or right.
5262 /// We count undefs as zeros until PreferredNum is reached.
5263 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5264                                          unsigned NumElems, bool ZerosFromLeft,
5265                                          SelectionDAG &DAG,
5266                                          unsigned PreferredNum = -1U) {
5267   unsigned NumZeros = 0;
5268   for (unsigned i = 0; i != NumElems; ++i) {
5269     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5270     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5271     if (!Elt.getNode())
5272       break;
5273
5274     if (X86::isZeroNode(Elt))
5275       ++NumZeros;
5276     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5277       NumZeros = std::min(NumZeros + 1, PreferredNum);
5278     else
5279       break;
5280   }
5281
5282   return NumZeros;
5283 }
5284
5285 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5286 /// correspond consecutively to elements from one of the vector operands,
5287 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5288 static
5289 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5290                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5291                               unsigned NumElems, unsigned &OpNum) {
5292   bool SeenV1 = false;
5293   bool SeenV2 = false;
5294
5295   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5296     int Idx = SVOp->getMaskElt(i);
5297     // Ignore undef indicies
5298     if (Idx < 0)
5299       continue;
5300
5301     if (Idx < (int)NumElems)
5302       SeenV1 = true;
5303     else
5304       SeenV2 = true;
5305
5306     // Only accept consecutive elements from the same vector
5307     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5308       return false;
5309   }
5310
5311   OpNum = SeenV1 ? 0 : 1;
5312   return true;
5313 }
5314
5315 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5316 /// logical left shift of a vector.
5317 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5318                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5319   unsigned NumElems =
5320     SVOp->getSimpleValueType(0).getVectorNumElements();
5321   unsigned NumZeros = getNumOfConsecutiveZeros(
5322       SVOp, NumElems, false /* check zeros from right */, DAG,
5323       SVOp->getMaskElt(0));
5324   unsigned OpSrc;
5325
5326   if (!NumZeros)
5327     return false;
5328
5329   // Considering the elements in the mask that are not consecutive zeros,
5330   // check if they consecutively come from only one of the source vectors.
5331   //
5332   //               V1 = {X, A, B, C}     0
5333   //                         \  \  \    /
5334   //   vector_shuffle V1, V2 <1, 2, 3, X>
5335   //
5336   if (!isShuffleMaskConsecutive(SVOp,
5337             0,                   // Mask Start Index
5338             NumElems-NumZeros,   // Mask End Index(exclusive)
5339             NumZeros,            // Where to start looking in the src vector
5340             NumElems,            // Number of elements in vector
5341             OpSrc))              // Which source operand ?
5342     return false;
5343
5344   isLeft = false;
5345   ShAmt = NumZeros;
5346   ShVal = SVOp->getOperand(OpSrc);
5347   return true;
5348 }
5349
5350 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5351 /// logical left shift of a vector.
5352 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5353                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5354   unsigned NumElems =
5355     SVOp->getSimpleValueType(0).getVectorNumElements();
5356   unsigned NumZeros = getNumOfConsecutiveZeros(
5357       SVOp, NumElems, true /* check zeros from left */, DAG,
5358       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5359   unsigned OpSrc;
5360
5361   if (!NumZeros)
5362     return false;
5363
5364   // Considering the elements in the mask that are not consecutive zeros,
5365   // check if they consecutively come from only one of the source vectors.
5366   //
5367   //                           0    { A, B, X, X } = V2
5368   //                          / \    /  /
5369   //   vector_shuffle V1, V2 <X, X, 4, 5>
5370   //
5371   if (!isShuffleMaskConsecutive(SVOp,
5372             NumZeros,     // Mask Start Index
5373             NumElems,     // Mask End Index(exclusive)
5374             0,            // Where to start looking in the src vector
5375             NumElems,     // Number of elements in vector
5376             OpSrc))       // Which source operand ?
5377     return false;
5378
5379   isLeft = true;
5380   ShAmt = NumZeros;
5381   ShVal = SVOp->getOperand(OpSrc);
5382   return true;
5383 }
5384
5385 /// isVectorShift - Returns true if the shuffle can be implemented as a
5386 /// logical left or right shift of a vector.
5387 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5388                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5389   // Although the logic below support any bitwidth size, there are no
5390   // shift instructions which handle more than 128-bit vectors.
5391   if (!SVOp->getSimpleValueType(0).is128BitVector())
5392     return false;
5393
5394   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5395       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5396     return true;
5397
5398   return false;
5399 }
5400
5401 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5402 ///
5403 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5404                                        unsigned NumNonZero, unsigned NumZero,
5405                                        SelectionDAG &DAG,
5406                                        const X86Subtarget* Subtarget,
5407                                        const TargetLowering &TLI) {
5408   if (NumNonZero > 8)
5409     return SDValue();
5410
5411   SDLoc dl(Op);
5412   SDValue V;
5413   bool First = true;
5414   for (unsigned i = 0; i < 16; ++i) {
5415     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5416     if (ThisIsNonZero && First) {
5417       if (NumZero)
5418         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5419       else
5420         V = DAG.getUNDEF(MVT::v8i16);
5421       First = false;
5422     }
5423
5424     if ((i & 1) != 0) {
5425       SDValue ThisElt, LastElt;
5426       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5427       if (LastIsNonZero) {
5428         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5429                               MVT::i16, Op.getOperand(i-1));
5430       }
5431       if (ThisIsNonZero) {
5432         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5433         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5434                               ThisElt, DAG.getConstant(8, MVT::i8));
5435         if (LastIsNonZero)
5436           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5437       } else
5438         ThisElt = LastElt;
5439
5440       if (ThisElt.getNode())
5441         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5442                         DAG.getIntPtrConstant(i/2));
5443     }
5444   }
5445
5446   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5447 }
5448
5449 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5450 ///
5451 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5452                                      unsigned NumNonZero, unsigned NumZero,
5453                                      SelectionDAG &DAG,
5454                                      const X86Subtarget* Subtarget,
5455                                      const TargetLowering &TLI) {
5456   if (NumNonZero > 4)
5457     return SDValue();
5458
5459   SDLoc dl(Op);
5460   SDValue V;
5461   bool First = true;
5462   for (unsigned i = 0; i < 8; ++i) {
5463     bool isNonZero = (NonZeros & (1 << i)) != 0;
5464     if (isNonZero) {
5465       if (First) {
5466         if (NumZero)
5467           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5468         else
5469           V = DAG.getUNDEF(MVT::v8i16);
5470         First = false;
5471       }
5472       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5473                       MVT::v8i16, V, Op.getOperand(i),
5474                       DAG.getIntPtrConstant(i));
5475     }
5476   }
5477
5478   return V;
5479 }
5480
5481 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5482 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5483                                      unsigned NonZeros, unsigned NumNonZero,
5484                                      unsigned NumZero, SelectionDAG &DAG,
5485                                      const X86Subtarget *Subtarget,
5486                                      const TargetLowering &TLI) {
5487   // We know there's at least one non-zero element
5488   unsigned FirstNonZeroIdx = 0;
5489   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5490   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5491          X86::isZeroNode(FirstNonZero)) {
5492     ++FirstNonZeroIdx;
5493     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5494   }
5495
5496   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5497       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5498     return SDValue();
5499
5500   SDValue V = FirstNonZero.getOperand(0);
5501   MVT VVT = V.getSimpleValueType();
5502   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5503     return SDValue();
5504
5505   unsigned FirstNonZeroDst =
5506       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5507   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5508   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5509   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5510
5511   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5512     SDValue Elem = Op.getOperand(Idx);
5513     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5514       continue;
5515
5516     // TODO: What else can be here? Deal with it.
5517     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5518       return SDValue();
5519
5520     // TODO: Some optimizations are still possible here
5521     // ex: Getting one element from a vector, and the rest from another.
5522     if (Elem.getOperand(0) != V)
5523       return SDValue();
5524
5525     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5526     if (Dst == Idx)
5527       ++CorrectIdx;
5528     else if (IncorrectIdx == -1U) {
5529       IncorrectIdx = Idx;
5530       IncorrectDst = Dst;
5531     } else
5532       // There was already one element with an incorrect index.
5533       // We can't optimize this case to an insertps.
5534       return SDValue();
5535   }
5536
5537   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5538     SDLoc dl(Op);
5539     EVT VT = Op.getSimpleValueType();
5540     unsigned ElementMoveMask = 0;
5541     if (IncorrectIdx == -1U)
5542       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5543     else
5544       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5545
5546     SDValue InsertpsMask =
5547         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5548     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5549   }
5550
5551   return SDValue();
5552 }
5553
5554 /// getVShift - Return a vector logical shift node.
5555 ///
5556 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5557                          unsigned NumBits, SelectionDAG &DAG,
5558                          const TargetLowering &TLI, SDLoc dl) {
5559   assert(VT.is128BitVector() && "Unknown type for VShift");
5560   EVT ShVT = MVT::v2i64;
5561   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5562   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5563   return DAG.getNode(ISD::BITCAST, dl, VT,
5564                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5565                              DAG.getConstant(NumBits,
5566                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5567 }
5568
5569 static SDValue
5570 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5571
5572   // Check if the scalar load can be widened into a vector load. And if
5573   // the address is "base + cst" see if the cst can be "absorbed" into
5574   // the shuffle mask.
5575   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5576     SDValue Ptr = LD->getBasePtr();
5577     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5578       return SDValue();
5579     EVT PVT = LD->getValueType(0);
5580     if (PVT != MVT::i32 && PVT != MVT::f32)
5581       return SDValue();
5582
5583     int FI = -1;
5584     int64_t Offset = 0;
5585     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5586       FI = FINode->getIndex();
5587       Offset = 0;
5588     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5589                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5590       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5591       Offset = Ptr.getConstantOperandVal(1);
5592       Ptr = Ptr.getOperand(0);
5593     } else {
5594       return SDValue();
5595     }
5596
5597     // FIXME: 256-bit vector instructions don't require a strict alignment,
5598     // improve this code to support it better.
5599     unsigned RequiredAlign = VT.getSizeInBits()/8;
5600     SDValue Chain = LD->getChain();
5601     // Make sure the stack object alignment is at least 16 or 32.
5602     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5603     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5604       if (MFI->isFixedObjectIndex(FI)) {
5605         // Can't change the alignment. FIXME: It's possible to compute
5606         // the exact stack offset and reference FI + adjust offset instead.
5607         // If someone *really* cares about this. That's the way to implement it.
5608         return SDValue();
5609       } else {
5610         MFI->setObjectAlignment(FI, RequiredAlign);
5611       }
5612     }
5613
5614     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5615     // Ptr + (Offset & ~15).
5616     if (Offset < 0)
5617       return SDValue();
5618     if ((Offset % RequiredAlign) & 3)
5619       return SDValue();
5620     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5621     if (StartOffset)
5622       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5623                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5624
5625     int EltNo = (Offset - StartOffset) >> 2;
5626     unsigned NumElems = VT.getVectorNumElements();
5627
5628     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5629     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5630                              LD->getPointerInfo().getWithOffset(StartOffset),
5631                              false, false, false, 0);
5632
5633     SmallVector<int, 8> Mask;
5634     for (unsigned i = 0; i != NumElems; ++i)
5635       Mask.push_back(EltNo);
5636
5637     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5638   }
5639
5640   return SDValue();
5641 }
5642
5643 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5644 /// vector of type 'VT', see if the elements can be replaced by a single large
5645 /// load which has the same value as a build_vector whose operands are 'elts'.
5646 ///
5647 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5648 ///
5649 /// FIXME: we'd also like to handle the case where the last elements are zero
5650 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5651 /// There's even a handy isZeroNode for that purpose.
5652 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5653                                         SDLoc &DL, SelectionDAG &DAG,
5654                                         bool isAfterLegalize) {
5655   EVT EltVT = VT.getVectorElementType();
5656   unsigned NumElems = Elts.size();
5657
5658   LoadSDNode *LDBase = nullptr;
5659   unsigned LastLoadedElt = -1U;
5660
5661   // For each element in the initializer, see if we've found a load or an undef.
5662   // If we don't find an initial load element, or later load elements are
5663   // non-consecutive, bail out.
5664   for (unsigned i = 0; i < NumElems; ++i) {
5665     SDValue Elt = Elts[i];
5666
5667     if (!Elt.getNode() ||
5668         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5669       return SDValue();
5670     if (!LDBase) {
5671       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5672         return SDValue();
5673       LDBase = cast<LoadSDNode>(Elt.getNode());
5674       LastLoadedElt = i;
5675       continue;
5676     }
5677     if (Elt.getOpcode() == ISD::UNDEF)
5678       continue;
5679
5680     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5681     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5682       return SDValue();
5683     LastLoadedElt = i;
5684   }
5685
5686   // If we have found an entire vector of loads and undefs, then return a large
5687   // load of the entire vector width starting at the base pointer.  If we found
5688   // consecutive loads for the low half, generate a vzext_load node.
5689   if (LastLoadedElt == NumElems - 1) {
5690
5691     if (isAfterLegalize &&
5692         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5693       return SDValue();
5694
5695     SDValue NewLd = SDValue();
5696
5697     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5698       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5699                           LDBase->getPointerInfo(),
5700                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5701                           LDBase->isInvariant(), 0);
5702     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5703                         LDBase->getPointerInfo(),
5704                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5705                         LDBase->isInvariant(), LDBase->getAlignment());
5706
5707     if (LDBase->hasAnyUseOfValue(1)) {
5708       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5709                                      SDValue(LDBase, 1),
5710                                      SDValue(NewLd.getNode(), 1));
5711       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5712       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5713                              SDValue(NewLd.getNode(), 1));
5714     }
5715
5716     return NewLd;
5717   }
5718   if (NumElems == 4 && LastLoadedElt == 1 &&
5719       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5720     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5721     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5722     SDValue ResNode =
5723         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5724                                 LDBase->getPointerInfo(),
5725                                 LDBase->getAlignment(),
5726                                 false/*isVolatile*/, true/*ReadMem*/,
5727                                 false/*WriteMem*/);
5728
5729     // Make sure the newly-created LOAD is in the same position as LDBase in
5730     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5731     // update uses of LDBase's output chain to use the TokenFactor.
5732     if (LDBase->hasAnyUseOfValue(1)) {
5733       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5734                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5735       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5736       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5737                              SDValue(ResNode.getNode(), 1));
5738     }
5739
5740     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5741   }
5742   return SDValue();
5743 }
5744
5745 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5746 /// to generate a splat value for the following cases:
5747 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5748 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5749 /// a scalar load, or a constant.
5750 /// The VBROADCAST node is returned when a pattern is found,
5751 /// or SDValue() otherwise.
5752 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5753                                     SelectionDAG &DAG) {
5754   if (!Subtarget->hasFp256())
5755     return SDValue();
5756
5757   MVT VT = Op.getSimpleValueType();
5758   SDLoc dl(Op);
5759
5760   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5761          "Unsupported vector type for broadcast.");
5762
5763   SDValue Ld;
5764   bool ConstSplatVal;
5765
5766   switch (Op.getOpcode()) {
5767     default:
5768       // Unknown pattern found.
5769       return SDValue();
5770
5771     case ISD::BUILD_VECTOR: {
5772       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5773       BitVector UndefElements;
5774       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5775
5776       // We need a splat of a single value to use broadcast, and it doesn't
5777       // make any sense if the value is only in one element of the vector.
5778       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5779         return SDValue();
5780
5781       Ld = Splat;
5782       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5783                        Ld.getOpcode() == ISD::ConstantFP);
5784
5785       // Make sure that all of the users of a non-constant load are from the
5786       // BUILD_VECTOR node.
5787       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5788         return SDValue();
5789       break;
5790     }
5791
5792     case ISD::VECTOR_SHUFFLE: {
5793       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5794
5795       // Shuffles must have a splat mask where the first element is
5796       // broadcasted.
5797       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5798         return SDValue();
5799
5800       SDValue Sc = Op.getOperand(0);
5801       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5802           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5803
5804         if (!Subtarget->hasInt256())
5805           return SDValue();
5806
5807         // Use the register form of the broadcast instruction available on AVX2.
5808         if (VT.getSizeInBits() >= 256)
5809           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5810         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5811       }
5812
5813       Ld = Sc.getOperand(0);
5814       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5815                        Ld.getOpcode() == ISD::ConstantFP);
5816
5817       // The scalar_to_vector node and the suspected
5818       // load node must have exactly one user.
5819       // Constants may have multiple users.
5820
5821       // AVX-512 has register version of the broadcast
5822       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5823         Ld.getValueType().getSizeInBits() >= 32;
5824       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5825           !hasRegVer))
5826         return SDValue();
5827       break;
5828     }
5829   }
5830
5831   bool IsGE256 = (VT.getSizeInBits() >= 256);
5832
5833   // Handle the broadcasting a single constant scalar from the constant pool
5834   // into a vector. On Sandybridge it is still better to load a constant vector
5835   // from the constant pool and not to broadcast it from a scalar.
5836   if (ConstSplatVal && Subtarget->hasInt256()) {
5837     EVT CVT = Ld.getValueType();
5838     assert(!CVT.isVector() && "Must not broadcast a vector type");
5839     unsigned ScalarSize = CVT.getSizeInBits();
5840
5841     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5842       const Constant *C = nullptr;
5843       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5844         C = CI->getConstantIntValue();
5845       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5846         C = CF->getConstantFPValue();
5847
5848       assert(C && "Invalid constant type");
5849
5850       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5851       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5852       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5853       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5854                        MachinePointerInfo::getConstantPool(),
5855                        false, false, false, Alignment);
5856
5857       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5858     }
5859   }
5860
5861   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5862   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5863
5864   // Handle AVX2 in-register broadcasts.
5865   if (!IsLoad && Subtarget->hasInt256() &&
5866       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5867     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5868
5869   // The scalar source must be a normal load.
5870   if (!IsLoad)
5871     return SDValue();
5872
5873   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5874     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5875
5876   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5877   // double since there is no vbroadcastsd xmm
5878   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5879     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5880       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5881   }
5882
5883   // Unsupported broadcast.
5884   return SDValue();
5885 }
5886
5887 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5888 /// underlying vector and index.
5889 ///
5890 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5891 /// index.
5892 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5893                                          SDValue ExtIdx) {
5894   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5895   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5896     return Idx;
5897
5898   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5899   // lowered this:
5900   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5901   // to:
5902   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5903   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5904   //                           undef)
5905   //                       Constant<0>)
5906   // In this case the vector is the extract_subvector expression and the index
5907   // is 2, as specified by the shuffle.
5908   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5909   SDValue ShuffleVec = SVOp->getOperand(0);
5910   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5911   assert(ShuffleVecVT.getVectorElementType() ==
5912          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5913
5914   int ShuffleIdx = SVOp->getMaskElt(Idx);
5915   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5916     ExtractedFromVec = ShuffleVec;
5917     return ShuffleIdx;
5918   }
5919   return Idx;
5920 }
5921
5922 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5923   MVT VT = Op.getSimpleValueType();
5924
5925   // Skip if insert_vec_elt is not supported.
5926   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5927   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5928     return SDValue();
5929
5930   SDLoc DL(Op);
5931   unsigned NumElems = Op.getNumOperands();
5932
5933   SDValue VecIn1;
5934   SDValue VecIn2;
5935   SmallVector<unsigned, 4> InsertIndices;
5936   SmallVector<int, 8> Mask(NumElems, -1);
5937
5938   for (unsigned i = 0; i != NumElems; ++i) {
5939     unsigned Opc = Op.getOperand(i).getOpcode();
5940
5941     if (Opc == ISD::UNDEF)
5942       continue;
5943
5944     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5945       // Quit if more than 1 elements need inserting.
5946       if (InsertIndices.size() > 1)
5947         return SDValue();
5948
5949       InsertIndices.push_back(i);
5950       continue;
5951     }
5952
5953     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5954     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5955     // Quit if non-constant index.
5956     if (!isa<ConstantSDNode>(ExtIdx))
5957       return SDValue();
5958     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5959
5960     // Quit if extracted from vector of different type.
5961     if (ExtractedFromVec.getValueType() != VT)
5962       return SDValue();
5963
5964     if (!VecIn1.getNode())
5965       VecIn1 = ExtractedFromVec;
5966     else if (VecIn1 != ExtractedFromVec) {
5967       if (!VecIn2.getNode())
5968         VecIn2 = ExtractedFromVec;
5969       else if (VecIn2 != ExtractedFromVec)
5970         // Quit if more than 2 vectors to shuffle
5971         return SDValue();
5972     }
5973
5974     if (ExtractedFromVec == VecIn1)
5975       Mask[i] = Idx;
5976     else if (ExtractedFromVec == VecIn2)
5977       Mask[i] = Idx + NumElems;
5978   }
5979
5980   if (!VecIn1.getNode())
5981     return SDValue();
5982
5983   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5984   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5985   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5986     unsigned Idx = InsertIndices[i];
5987     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5988                      DAG.getIntPtrConstant(Idx));
5989   }
5990
5991   return NV;
5992 }
5993
5994 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5995 SDValue
5996 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5997
5998   MVT VT = Op.getSimpleValueType();
5999   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6000          "Unexpected type in LowerBUILD_VECTORvXi1!");
6001
6002   SDLoc dl(Op);
6003   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6004     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6005     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6006     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6007   }
6008
6009   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6010     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6011     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6012     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6013   }
6014
6015   bool AllContants = true;
6016   uint64_t Immediate = 0;
6017   int NonConstIdx = -1;
6018   bool IsSplat = true;
6019   unsigned NumNonConsts = 0;
6020   unsigned NumConsts = 0;
6021   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6022     SDValue In = Op.getOperand(idx);
6023     if (In.getOpcode() == ISD::UNDEF)
6024       continue;
6025     if (!isa<ConstantSDNode>(In)) {
6026       AllContants = false;
6027       NonConstIdx = idx;
6028       NumNonConsts++;
6029     }
6030     else {
6031       NumConsts++;
6032       if (cast<ConstantSDNode>(In)->getZExtValue())
6033       Immediate |= (1ULL << idx);
6034     }
6035     if (In != Op.getOperand(0))
6036       IsSplat = false;
6037   }
6038
6039   if (AllContants) {
6040     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6041       DAG.getConstant(Immediate, MVT::i16));
6042     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6043                        DAG.getIntPtrConstant(0));
6044   }
6045
6046   if (NumNonConsts == 1 && NonConstIdx != 0) {
6047     SDValue DstVec;
6048     if (NumConsts) {
6049       SDValue VecAsImm = DAG.getConstant(Immediate,
6050                                          MVT::getIntegerVT(VT.getSizeInBits()));
6051       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6052     }
6053     else 
6054       DstVec = DAG.getUNDEF(VT);
6055     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6056                        Op.getOperand(NonConstIdx),
6057                        DAG.getIntPtrConstant(NonConstIdx));
6058   }
6059   if (!IsSplat && (NonConstIdx != 0))
6060     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6061   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6062   SDValue Select;
6063   if (IsSplat)
6064     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6065                           DAG.getConstant(-1, SelectVT),
6066                           DAG.getConstant(0, SelectVT));
6067   else
6068     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6069                          DAG.getConstant((Immediate | 1), SelectVT),
6070                          DAG.getConstant(Immediate, SelectVT));
6071   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6072 }
6073
6074 /// \brief Return true if \p N implements a horizontal binop and return the
6075 /// operands for the horizontal binop into V0 and V1.
6076 /// 
6077 /// This is a helper function of PerformBUILD_VECTORCombine.
6078 /// This function checks that the build_vector \p N in input implements a
6079 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6080 /// operation to match.
6081 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6082 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6083 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6084 /// arithmetic sub.
6085 ///
6086 /// This function only analyzes elements of \p N whose indices are
6087 /// in range [BaseIdx, LastIdx).
6088 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6089                               SelectionDAG &DAG,
6090                               unsigned BaseIdx, unsigned LastIdx,
6091                               SDValue &V0, SDValue &V1) {
6092   EVT VT = N->getValueType(0);
6093
6094   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6095   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6096          "Invalid Vector in input!");
6097   
6098   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6099   bool CanFold = true;
6100   unsigned ExpectedVExtractIdx = BaseIdx;
6101   unsigned NumElts = LastIdx - BaseIdx;
6102   V0 = DAG.getUNDEF(VT);
6103   V1 = DAG.getUNDEF(VT);
6104
6105   // Check if N implements a horizontal binop.
6106   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6107     SDValue Op = N->getOperand(i + BaseIdx);
6108
6109     // Skip UNDEFs.
6110     if (Op->getOpcode() == ISD::UNDEF) {
6111       // Update the expected vector extract index.
6112       if (i * 2 == NumElts)
6113         ExpectedVExtractIdx = BaseIdx;
6114       ExpectedVExtractIdx += 2;
6115       continue;
6116     }
6117
6118     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6119
6120     if (!CanFold)
6121       break;
6122
6123     SDValue Op0 = Op.getOperand(0);
6124     SDValue Op1 = Op.getOperand(1);
6125
6126     // Try to match the following pattern:
6127     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6128     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6129         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6130         Op0.getOperand(0) == Op1.getOperand(0) &&
6131         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6132         isa<ConstantSDNode>(Op1.getOperand(1)));
6133     if (!CanFold)
6134       break;
6135
6136     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6137     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6138
6139     if (i * 2 < NumElts) {
6140       if (V0.getOpcode() == ISD::UNDEF)
6141         V0 = Op0.getOperand(0);
6142     } else {
6143       if (V1.getOpcode() == ISD::UNDEF)
6144         V1 = Op0.getOperand(0);
6145       if (i * 2 == NumElts)
6146         ExpectedVExtractIdx = BaseIdx;
6147     }
6148
6149     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6150     if (I0 == ExpectedVExtractIdx)
6151       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6152     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6153       // Try to match the following dag sequence:
6154       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6155       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6156     } else
6157       CanFold = false;
6158
6159     ExpectedVExtractIdx += 2;
6160   }
6161
6162   return CanFold;
6163 }
6164
6165 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6166 /// a concat_vector. 
6167 ///
6168 /// This is a helper function of PerformBUILD_VECTORCombine.
6169 /// This function expects two 256-bit vectors called V0 and V1.
6170 /// At first, each vector is split into two separate 128-bit vectors.
6171 /// Then, the resulting 128-bit vectors are used to implement two
6172 /// horizontal binary operations. 
6173 ///
6174 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6175 ///
6176 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6177 /// the two new horizontal binop.
6178 /// When Mode is set, the first horizontal binop dag node would take as input
6179 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6180 /// horizontal binop dag node would take as input the lower 128-bit of V1
6181 /// and the upper 128-bit of V1.
6182 ///   Example:
6183 ///     HADD V0_LO, V0_HI
6184 ///     HADD V1_LO, V1_HI
6185 ///
6186 /// Otherwise, the first horizontal binop dag node takes as input the lower
6187 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6188 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6189 ///   Example:
6190 ///     HADD V0_LO, V1_LO
6191 ///     HADD V0_HI, V1_HI
6192 ///
6193 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6194 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6195 /// the upper 128-bits of the result.
6196 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6197                                      SDLoc DL, SelectionDAG &DAG,
6198                                      unsigned X86Opcode, bool Mode,
6199                                      bool isUndefLO, bool isUndefHI) {
6200   EVT VT = V0.getValueType();
6201   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6202          "Invalid nodes in input!");
6203
6204   unsigned NumElts = VT.getVectorNumElements();
6205   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6206   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6207   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6208   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6209   EVT NewVT = V0_LO.getValueType();
6210
6211   SDValue LO = DAG.getUNDEF(NewVT);
6212   SDValue HI = DAG.getUNDEF(NewVT);
6213
6214   if (Mode) {
6215     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6216     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6217       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6218     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6219       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6220   } else {
6221     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6222     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6223                        V1_LO->getOpcode() != ISD::UNDEF))
6224       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6225
6226     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6227                        V1_HI->getOpcode() != ISD::UNDEF))
6228       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6229   }
6230
6231   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6232 }
6233
6234 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6235 /// sequence of 'vadd + vsub + blendi'.
6236 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6237                            const X86Subtarget *Subtarget) {
6238   SDLoc DL(BV);
6239   EVT VT = BV->getValueType(0);
6240   unsigned NumElts = VT.getVectorNumElements();
6241   SDValue InVec0 = DAG.getUNDEF(VT);
6242   SDValue InVec1 = DAG.getUNDEF(VT);
6243
6244   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6245           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6246
6247   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6248   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6249   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6250     return SDValue();
6251
6252   // Odd-numbered elements in the input build vector are obtained from
6253   // adding two integer/float elements.
6254   // Even-numbered elements in the input build vector are obtained from
6255   // subtracting two integer/float elements.
6256   unsigned ExpectedOpcode = ISD::FSUB;
6257   unsigned NextExpectedOpcode = ISD::FADD;
6258   bool AddFound = false;
6259   bool SubFound = false;
6260
6261   for (unsigned i = 0, e = NumElts; i != e; i++) {
6262     SDValue Op = BV->getOperand(i);
6263       
6264     // Skip 'undef' values.
6265     unsigned Opcode = Op.getOpcode();
6266     if (Opcode == ISD::UNDEF) {
6267       std::swap(ExpectedOpcode, NextExpectedOpcode);
6268       continue;
6269     }
6270       
6271     // Early exit if we found an unexpected opcode.
6272     if (Opcode != ExpectedOpcode)
6273       return SDValue();
6274
6275     SDValue Op0 = Op.getOperand(0);
6276     SDValue Op1 = Op.getOperand(1);
6277
6278     // Try to match the following pattern:
6279     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6280     // Early exit if we cannot match that sequence.
6281     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6282         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6283         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6284         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6285         Op0.getOperand(1) != Op1.getOperand(1))
6286       return SDValue();
6287
6288     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6289     if (I0 != i)
6290       return SDValue();
6291
6292     // We found a valid add/sub node. Update the information accordingly.
6293     if (i & 1)
6294       AddFound = true;
6295     else
6296       SubFound = true;
6297
6298     // Update InVec0 and InVec1.
6299     if (InVec0.getOpcode() == ISD::UNDEF)
6300       InVec0 = Op0.getOperand(0);
6301     if (InVec1.getOpcode() == ISD::UNDEF)
6302       InVec1 = Op1.getOperand(0);
6303
6304     // Make sure that operands in input to each add/sub node always
6305     // come from a same pair of vectors.
6306     if (InVec0 != Op0.getOperand(0)) {
6307       if (ExpectedOpcode == ISD::FSUB)
6308         return SDValue();
6309
6310       // FADD is commutable. Try to commute the operands
6311       // and then test again.
6312       std::swap(Op0, Op1);
6313       if (InVec0 != Op0.getOperand(0))
6314         return SDValue();
6315     }
6316
6317     if (InVec1 != Op1.getOperand(0))
6318       return SDValue();
6319
6320     // Update the pair of expected opcodes.
6321     std::swap(ExpectedOpcode, NextExpectedOpcode);
6322   }
6323
6324   // Don't try to fold this build_vector into a VSELECT if it has
6325   // too many UNDEF operands.
6326   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6327       InVec1.getOpcode() != ISD::UNDEF) {
6328     // Emit a sequence of vector add and sub followed by a VSELECT.
6329     // The new VSELECT will be lowered into a BLENDI.
6330     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6331     // and emit a single ADDSUB instruction.
6332     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6333     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6334
6335     // Construct the VSELECT mask.
6336     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6337     EVT SVT = MaskVT.getVectorElementType();
6338     unsigned SVTBits = SVT.getSizeInBits();
6339     SmallVector<SDValue, 8> Ops;
6340
6341     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6342       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6343                             APInt::getAllOnesValue(SVTBits);
6344       SDValue Constant = DAG.getConstant(Value, SVT);
6345       Ops.push_back(Constant);
6346     }
6347
6348     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6349     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6350   }
6351   
6352   return SDValue();
6353 }
6354
6355 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6356                                           const X86Subtarget *Subtarget) {
6357   SDLoc DL(N);
6358   EVT VT = N->getValueType(0);
6359   unsigned NumElts = VT.getVectorNumElements();
6360   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6361   SDValue InVec0, InVec1;
6362
6363   // Try to match an ADDSUB.
6364   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6365       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6366     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6367     if (Value.getNode())
6368       return Value;
6369   }
6370
6371   // Try to match horizontal ADD/SUB.
6372   unsigned NumUndefsLO = 0;
6373   unsigned NumUndefsHI = 0;
6374   unsigned Half = NumElts/2;
6375
6376   // Count the number of UNDEF operands in the build_vector in input.
6377   for (unsigned i = 0, e = Half; i != e; ++i)
6378     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6379       NumUndefsLO++;
6380
6381   for (unsigned i = Half, e = NumElts; i != e; ++i)
6382     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6383       NumUndefsHI++;
6384
6385   // Early exit if this is either a build_vector of all UNDEFs or all the
6386   // operands but one are UNDEF.
6387   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6388     return SDValue();
6389
6390   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6391     // Try to match an SSE3 float HADD/HSUB.
6392     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6393       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6394     
6395     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6396       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6397   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6398     // Try to match an SSSE3 integer HADD/HSUB.
6399     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6400       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6401     
6402     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6403       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6404   }
6405   
6406   if (!Subtarget->hasAVX())
6407     return SDValue();
6408
6409   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6410     // Try to match an AVX horizontal add/sub of packed single/double
6411     // precision floating point values from 256-bit vectors.
6412     SDValue InVec2, InVec3;
6413     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6414         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6415         ((InVec0.getOpcode() == ISD::UNDEF ||
6416           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6417         ((InVec1.getOpcode() == ISD::UNDEF ||
6418           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6419       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6420
6421     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6422         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6423         ((InVec0.getOpcode() == ISD::UNDEF ||
6424           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6425         ((InVec1.getOpcode() == ISD::UNDEF ||
6426           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6427       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6428   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6429     // Try to match an AVX2 horizontal add/sub of signed integers.
6430     SDValue InVec2, InVec3;
6431     unsigned X86Opcode;
6432     bool CanFold = true;
6433
6434     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6435         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6436         ((InVec0.getOpcode() == ISD::UNDEF ||
6437           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6438         ((InVec1.getOpcode() == ISD::UNDEF ||
6439           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6440       X86Opcode = X86ISD::HADD;
6441     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6442         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6443         ((InVec0.getOpcode() == ISD::UNDEF ||
6444           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6445         ((InVec1.getOpcode() == ISD::UNDEF ||
6446           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6447       X86Opcode = X86ISD::HSUB;
6448     else
6449       CanFold = false;
6450
6451     if (CanFold) {
6452       // Fold this build_vector into a single horizontal add/sub.
6453       // Do this only if the target has AVX2.
6454       if (Subtarget->hasAVX2())
6455         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6456  
6457       // Do not try to expand this build_vector into a pair of horizontal
6458       // add/sub if we can emit a pair of scalar add/sub.
6459       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6460         return SDValue();
6461
6462       // Convert this build_vector into a pair of horizontal binop followed by
6463       // a concat vector.
6464       bool isUndefLO = NumUndefsLO == Half;
6465       bool isUndefHI = NumUndefsHI == Half;
6466       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6467                                    isUndefLO, isUndefHI);
6468     }
6469   }
6470
6471   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6472        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6473     unsigned X86Opcode;
6474     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6475       X86Opcode = X86ISD::HADD;
6476     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6477       X86Opcode = X86ISD::HSUB;
6478     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6479       X86Opcode = X86ISD::FHADD;
6480     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6481       X86Opcode = X86ISD::FHSUB;
6482     else
6483       return SDValue();
6484
6485     // Don't try to expand this build_vector into a pair of horizontal add/sub
6486     // if we can simply emit a pair of scalar add/sub.
6487     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6488       return SDValue();
6489
6490     // Convert this build_vector into two horizontal add/sub followed by
6491     // a concat vector.
6492     bool isUndefLO = NumUndefsLO == Half;
6493     bool isUndefHI = NumUndefsHI == Half;
6494     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6495                                  isUndefLO, isUndefHI);
6496   }
6497
6498   return SDValue();
6499 }
6500
6501 SDValue
6502 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6503   SDLoc dl(Op);
6504
6505   MVT VT = Op.getSimpleValueType();
6506   MVT ExtVT = VT.getVectorElementType();
6507   unsigned NumElems = Op.getNumOperands();
6508
6509   // Generate vectors for predicate vectors.
6510   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6511     return LowerBUILD_VECTORvXi1(Op, DAG);
6512
6513   // Vectors containing all zeros can be matched by pxor and xorps later
6514   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6515     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6516     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6517     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6518       return Op;
6519
6520     return getZeroVector(VT, Subtarget, DAG, dl);
6521   }
6522
6523   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6524   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6525   // vpcmpeqd on 256-bit vectors.
6526   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6527     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6528       return Op;
6529
6530     if (!VT.is512BitVector())
6531       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6532   }
6533
6534   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6535   if (Broadcast.getNode())
6536     return Broadcast;
6537
6538   unsigned EVTBits = ExtVT.getSizeInBits();
6539
6540   unsigned NumZero  = 0;
6541   unsigned NumNonZero = 0;
6542   unsigned NonZeros = 0;
6543   bool IsAllConstants = true;
6544   SmallSet<SDValue, 8> Values;
6545   for (unsigned i = 0; i < NumElems; ++i) {
6546     SDValue Elt = Op.getOperand(i);
6547     if (Elt.getOpcode() == ISD::UNDEF)
6548       continue;
6549     Values.insert(Elt);
6550     if (Elt.getOpcode() != ISD::Constant &&
6551         Elt.getOpcode() != ISD::ConstantFP)
6552       IsAllConstants = false;
6553     if (X86::isZeroNode(Elt))
6554       NumZero++;
6555     else {
6556       NonZeros |= (1 << i);
6557       NumNonZero++;
6558     }
6559   }
6560
6561   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6562   if (NumNonZero == 0)
6563     return DAG.getUNDEF(VT);
6564
6565   // Special case for single non-zero, non-undef, element.
6566   if (NumNonZero == 1) {
6567     unsigned Idx = countTrailingZeros(NonZeros);
6568     SDValue Item = Op.getOperand(Idx);
6569
6570     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6571     // the value are obviously zero, truncate the value to i32 and do the
6572     // insertion that way.  Only do this if the value is non-constant or if the
6573     // value is a constant being inserted into element 0.  It is cheaper to do
6574     // a constant pool load than it is to do a movd + shuffle.
6575     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6576         (!IsAllConstants || Idx == 0)) {
6577       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6578         // Handle SSE only.
6579         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6580         EVT VecVT = MVT::v4i32;
6581         unsigned VecElts = 4;
6582
6583         // Truncate the value (which may itself be a constant) to i32, and
6584         // convert it to a vector with movd (S2V+shuffle to zero extend).
6585         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6586         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6587         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6588
6589         // Now we have our 32-bit value zero extended in the low element of
6590         // a vector.  If Idx != 0, swizzle it into place.
6591         if (Idx != 0) {
6592           SmallVector<int, 4> Mask;
6593           Mask.push_back(Idx);
6594           for (unsigned i = 1; i != VecElts; ++i)
6595             Mask.push_back(i);
6596           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6597                                       &Mask[0]);
6598         }
6599         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6600       }
6601     }
6602
6603     // If we have a constant or non-constant insertion into the low element of
6604     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6605     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6606     // depending on what the source datatype is.
6607     if (Idx == 0) {
6608       if (NumZero == 0)
6609         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6610
6611       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6612           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6613         if (VT.is256BitVector() || VT.is512BitVector()) {
6614           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6615           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6616                              Item, DAG.getIntPtrConstant(0));
6617         }
6618         assert(VT.is128BitVector() && "Expected an SSE value type!");
6619         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6620         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6621         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6622       }
6623
6624       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6625         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6626         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6627         if (VT.is256BitVector()) {
6628           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6629           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6630         } else {
6631           assert(VT.is128BitVector() && "Expected an SSE value type!");
6632           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6633         }
6634         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6635       }
6636     }
6637
6638     // Is it a vector logical left shift?
6639     if (NumElems == 2 && Idx == 1 &&
6640         X86::isZeroNode(Op.getOperand(0)) &&
6641         !X86::isZeroNode(Op.getOperand(1))) {
6642       unsigned NumBits = VT.getSizeInBits();
6643       return getVShift(true, VT,
6644                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6645                                    VT, Op.getOperand(1)),
6646                        NumBits/2, DAG, *this, dl);
6647     }
6648
6649     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6650       return SDValue();
6651
6652     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6653     // is a non-constant being inserted into an element other than the low one,
6654     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6655     // movd/movss) to move this into the low element, then shuffle it into
6656     // place.
6657     if (EVTBits == 32) {
6658       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6659
6660       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6661       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6662       SmallVector<int, 8> MaskVec;
6663       for (unsigned i = 0; i != NumElems; ++i)
6664         MaskVec.push_back(i == Idx ? 0 : 1);
6665       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6666     }
6667   }
6668
6669   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6670   if (Values.size() == 1) {
6671     if (EVTBits == 32) {
6672       // Instead of a shuffle like this:
6673       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6674       // Check if it's possible to issue this instead.
6675       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6676       unsigned Idx = countTrailingZeros(NonZeros);
6677       SDValue Item = Op.getOperand(Idx);
6678       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6679         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6680     }
6681     return SDValue();
6682   }
6683
6684   // A vector full of immediates; various special cases are already
6685   // handled, so this is best done with a single constant-pool load.
6686   if (IsAllConstants)
6687     return SDValue();
6688
6689   // For AVX-length vectors, build the individual 128-bit pieces and use
6690   // shuffles to put them in place.
6691   if (VT.is256BitVector() || VT.is512BitVector()) {
6692     SmallVector<SDValue, 64> V;
6693     for (unsigned i = 0; i != NumElems; ++i)
6694       V.push_back(Op.getOperand(i));
6695
6696     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6697
6698     // Build both the lower and upper subvector.
6699     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6700                                 makeArrayRef(&V[0], NumElems/2));
6701     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6702                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6703
6704     // Recreate the wider vector with the lower and upper part.
6705     if (VT.is256BitVector())
6706       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6707     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6708   }
6709
6710   // Let legalizer expand 2-wide build_vectors.
6711   if (EVTBits == 64) {
6712     if (NumNonZero == 1) {
6713       // One half is zero or undef.
6714       unsigned Idx = countTrailingZeros(NonZeros);
6715       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6716                                  Op.getOperand(Idx));
6717       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6718     }
6719     return SDValue();
6720   }
6721
6722   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6723   if (EVTBits == 8 && NumElems == 16) {
6724     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6725                                         Subtarget, *this);
6726     if (V.getNode()) return V;
6727   }
6728
6729   if (EVTBits == 16 && NumElems == 8) {
6730     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6731                                       Subtarget, *this);
6732     if (V.getNode()) return V;
6733   }
6734
6735   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6736   if (EVTBits == 32 && NumElems == 4) {
6737     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6738                                       NumZero, DAG, Subtarget, *this);
6739     if (V.getNode())
6740       return V;
6741   }
6742
6743   // If element VT is == 32 bits, turn it into a number of shuffles.
6744   SmallVector<SDValue, 8> V(NumElems);
6745   if (NumElems == 4 && NumZero > 0) {
6746     for (unsigned i = 0; i < 4; ++i) {
6747       bool isZero = !(NonZeros & (1 << i));
6748       if (isZero)
6749         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6750       else
6751         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6752     }
6753
6754     for (unsigned i = 0; i < 2; ++i) {
6755       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6756         default: break;
6757         case 0:
6758           V[i] = V[i*2];  // Must be a zero vector.
6759           break;
6760         case 1:
6761           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6762           break;
6763         case 2:
6764           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6765           break;
6766         case 3:
6767           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6768           break;
6769       }
6770     }
6771
6772     bool Reverse1 = (NonZeros & 0x3) == 2;
6773     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6774     int MaskVec[] = {
6775       Reverse1 ? 1 : 0,
6776       Reverse1 ? 0 : 1,
6777       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6778       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6779     };
6780     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6781   }
6782
6783   if (Values.size() > 1 && VT.is128BitVector()) {
6784     // Check for a build vector of consecutive loads.
6785     for (unsigned i = 0; i < NumElems; ++i)
6786       V[i] = Op.getOperand(i);
6787
6788     // Check for elements which are consecutive loads.
6789     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6790     if (LD.getNode())
6791       return LD;
6792
6793     // Check for a build vector from mostly shuffle plus few inserting.
6794     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6795     if (Sh.getNode())
6796       return Sh;
6797
6798     // For SSE 4.1, use insertps to put the high elements into the low element.
6799     if (getSubtarget()->hasSSE41()) {
6800       SDValue Result;
6801       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6802         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6803       else
6804         Result = DAG.getUNDEF(VT);
6805
6806       for (unsigned i = 1; i < NumElems; ++i) {
6807         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6808         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6809                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6810       }
6811       return Result;
6812     }
6813
6814     // Otherwise, expand into a number of unpckl*, start by extending each of
6815     // our (non-undef) elements to the full vector width with the element in the
6816     // bottom slot of the vector (which generates no code for SSE).
6817     for (unsigned i = 0; i < NumElems; ++i) {
6818       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6819         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6820       else
6821         V[i] = DAG.getUNDEF(VT);
6822     }
6823
6824     // Next, we iteratively mix elements, e.g. for v4f32:
6825     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6826     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6827     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6828     unsigned EltStride = NumElems >> 1;
6829     while (EltStride != 0) {
6830       for (unsigned i = 0; i < EltStride; ++i) {
6831         // If V[i+EltStride] is undef and this is the first round of mixing,
6832         // then it is safe to just drop this shuffle: V[i] is already in the
6833         // right place, the one element (since it's the first round) being
6834         // inserted as undef can be dropped.  This isn't safe for successive
6835         // rounds because they will permute elements within both vectors.
6836         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6837             EltStride == NumElems/2)
6838           continue;
6839
6840         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6841       }
6842       EltStride >>= 1;
6843     }
6844     return V[0];
6845   }
6846   return SDValue();
6847 }
6848
6849 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6850 // to create 256-bit vectors from two other 128-bit ones.
6851 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6852   SDLoc dl(Op);
6853   MVT ResVT = Op.getSimpleValueType();
6854
6855   assert((ResVT.is256BitVector() ||
6856           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6857
6858   SDValue V1 = Op.getOperand(0);
6859   SDValue V2 = Op.getOperand(1);
6860   unsigned NumElems = ResVT.getVectorNumElements();
6861   if(ResVT.is256BitVector())
6862     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6863
6864   if (Op.getNumOperands() == 4) {
6865     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6866                                 ResVT.getVectorNumElements()/2);
6867     SDValue V3 = Op.getOperand(2);
6868     SDValue V4 = Op.getOperand(3);
6869     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6870       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6871   }
6872   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6873 }
6874
6875 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6876   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6877   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6878          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6879           Op.getNumOperands() == 4)));
6880
6881   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6882   // from two other 128-bit ones.
6883
6884   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6885   return LowerAVXCONCAT_VECTORS(Op, DAG);
6886 }
6887
6888
6889 //===----------------------------------------------------------------------===//
6890 // Vector shuffle lowering
6891 //
6892 // This is an experimental code path for lowering vector shuffles on x86. It is
6893 // designed to handle arbitrary vector shuffles and blends, gracefully
6894 // degrading performance as necessary. It works hard to recognize idiomatic
6895 // shuffles and lower them to optimal instruction patterns without leaving
6896 // a framework that allows reasonably efficient handling of all vector shuffle
6897 // patterns.
6898 //===----------------------------------------------------------------------===//
6899
6900 /// \brief Tiny helper function to identify a no-op mask.
6901 ///
6902 /// This is a somewhat boring predicate function. It checks whether the mask
6903 /// array input, which is assumed to be a single-input shuffle mask of the kind
6904 /// used by the X86 shuffle instructions (not a fully general
6905 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6906 /// in-place shuffle are 'no-op's.
6907 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6908   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6909     if (Mask[i] != -1 && Mask[i] != i)
6910       return false;
6911   return true;
6912 }
6913
6914 /// \brief Helper function to classify a mask as a single-input mask.
6915 ///
6916 /// This isn't a generic single-input test because in the vector shuffle
6917 /// lowering we canonicalize single inputs to be the first input operand. This
6918 /// means we can more quickly test for a single input by only checking whether
6919 /// an input from the second operand exists. We also assume that the size of
6920 /// mask corresponds to the size of the input vectors which isn't true in the
6921 /// fully general case.
6922 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6923   for (int M : Mask)
6924     if (M >= (int)Mask.size())
6925       return false;
6926   return true;
6927 }
6928
6929 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6930 ///
6931 /// This helper function produces an 8-bit shuffle immediate corresponding to
6932 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6933 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6934 /// example.
6935 ///
6936 /// NB: We rely heavily on "undef" masks preserving the input lane.
6937 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6938                                           SelectionDAG &DAG) {
6939   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6940   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6941   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6942   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6943   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6944
6945   unsigned Imm = 0;
6946   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6947   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6948   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6949   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6950   return DAG.getConstant(Imm, MVT::i8);
6951 }
6952
6953 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6954 ///
6955 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6956 /// support for floating point shuffles but not integer shuffles. These
6957 /// instructions will incur a domain crossing penalty on some chips though so
6958 /// it is better to avoid lowering through this for integer vectors where
6959 /// possible.
6960 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6961                                        const X86Subtarget *Subtarget,
6962                                        SelectionDAG &DAG) {
6963   SDLoc DL(Op);
6964   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6965   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6966   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6967   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6968   ArrayRef<int> Mask = SVOp->getMask();
6969   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6970
6971   if (isSingleInputShuffleMask(Mask)) {
6972     // Straight shuffle of a single input vector. Simulate this by using the
6973     // single input as both of the "inputs" to this instruction..
6974     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6975     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6976                        DAG.getConstant(SHUFPDMask, MVT::i8));
6977   }
6978   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6979   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6980
6981   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6982   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6983                      DAG.getConstant(SHUFPDMask, MVT::i8));
6984 }
6985
6986 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6987 ///
6988 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6989 /// the integer unit to minimize domain crossing penalties. However, for blends
6990 /// it falls back to the floating point shuffle operation with appropriate bit
6991 /// casting.
6992 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6993                                        const X86Subtarget *Subtarget,
6994                                        SelectionDAG &DAG) {
6995   SDLoc DL(Op);
6996   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
6997   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6998   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6999   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7000   ArrayRef<int> Mask = SVOp->getMask();
7001   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7002
7003   if (isSingleInputShuffleMask(Mask)) {
7004     // Straight shuffle of a single input vector. For everything from SSE2
7005     // onward this has a single fast instruction with no scary immediates.
7006     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7007     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7008     int WidenedMask[4] = {
7009         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7010         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7011     return DAG.getNode(
7012         ISD::BITCAST, DL, MVT::v2i64,
7013         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7014                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7015   }
7016
7017   // We implement this with SHUFPD which is pretty lame because it will likely
7018   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7019   // However, all the alternatives are still more cycles and newer chips don't
7020   // have this problem. It would be really nice if x86 had better shuffles here.
7021   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7022   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7023   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7024                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7025 }
7026
7027 /// \brief Lower 4-lane 32-bit floating point shuffles.
7028 ///
7029 /// Uses instructions exclusively from the floating point unit to minimize
7030 /// domain crossing penalties, as these are sufficient to implement all v4f32
7031 /// shuffles.
7032 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7033                                        const X86Subtarget *Subtarget,
7034                                        SelectionDAG &DAG) {
7035   SDLoc DL(Op);
7036   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7037   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7038   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7039   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7040   ArrayRef<int> Mask = SVOp->getMask();
7041   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7042
7043   SDValue LowV = V1, HighV = V2;
7044   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7045
7046   int NumV2Elements =
7047       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7048
7049   if (NumV2Elements == 0)
7050     // Straight shuffle of a single input vector. We pass the input vector to
7051     // both operands to simulate this with a SHUFPS.
7052     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7053                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7054
7055   if (NumV2Elements == 1) {
7056     int V2Index =
7057         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7058         Mask.begin();
7059     // Compute the index adjacent to V2Index and in the same half by toggling
7060     // the low bit.
7061     int V2AdjIndex = V2Index ^ 1;
7062
7063     if (Mask[V2AdjIndex] == -1) {
7064       // Handles all the cases where we have a single V2 element and an undef.
7065       // This will only ever happen in the high lanes because we commute the
7066       // vector otherwise.
7067       if (V2Index < 2)
7068         std::swap(LowV, HighV);
7069       NewMask[V2Index] -= 4;
7070     } else {
7071       // Handle the case where the V2 element ends up adjacent to a V1 element.
7072       // To make this work, blend them together as the first step.
7073       int V1Index = V2AdjIndex;
7074       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7075       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7076                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7077
7078       // Now proceed to reconstruct the final blend as we have the necessary
7079       // high or low half formed.
7080       if (V2Index < 2) {
7081         LowV = V2;
7082         HighV = V1;
7083       } else {
7084         HighV = V2;
7085       }
7086       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7087       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7088     }
7089   } else if (NumV2Elements == 2) {
7090     if (Mask[0] < 4 && Mask[1] < 4) {
7091       // Handle the easy case where we have V1 in the low lanes and V2 in the
7092       // high lanes. We never see this reversed because we sort the shuffle.
7093       NewMask[2] -= 4;
7094       NewMask[3] -= 4;
7095     } else {
7096       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7097       // trying to place elements directly, just blend them and set up the final
7098       // shuffle to place them.
7099
7100       // The first two blend mask elements are for V1, the second two are for
7101       // V2.
7102       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7103                           Mask[2] < 4 ? Mask[2] : Mask[3],
7104                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7105                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7106       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7107                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7108
7109       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7110       // a blend.
7111       LowV = HighV = V1;
7112       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7113       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7114       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7115       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7116     }
7117   }
7118   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7119                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7120 }
7121
7122 /// \brief Lower 4-lane i32 vector shuffles.
7123 ///
7124 /// We try to handle these with integer-domain shuffles where we can, but for
7125 /// blends we use the floating point domain blend instructions.
7126 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7127                                        const X86Subtarget *Subtarget,
7128                                        SelectionDAG &DAG) {
7129   SDLoc DL(Op);
7130   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7131   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7132   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7133   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7134   ArrayRef<int> Mask = SVOp->getMask();
7135   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7136
7137   if (isSingleInputShuffleMask(Mask))
7138     // Straight shuffle of a single input vector. For everything from SSE2
7139     // onward this has a single fast instruction with no scary immediates.
7140     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7141                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7142
7143   // We implement this with SHUFPS because it can blend from two vectors.
7144   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7145   // up the inputs, bypassing domain shift penalties that we would encur if we
7146   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7147   // relevant.
7148   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7149                      DAG.getVectorShuffle(
7150                          MVT::v4f32, DL,
7151                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7152                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7153 }
7154
7155 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7156 /// shuffle lowering, and the most complex part.
7157 ///
7158 /// The lowering strategy is to try to form pairs of input lanes which are
7159 /// targeted at the same half of the final vector, and then use a dword shuffle
7160 /// to place them onto the right half, and finally unpack the paired lanes into
7161 /// their final position.
7162 ///
7163 /// The exact breakdown of how to form these dword pairs and align them on the
7164 /// correct sides is really tricky. See the comments within the function for
7165 /// more of the details.
7166 static SDValue lowerV8I16SingleInputVectorShuffle(
7167     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7168     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7169   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7170   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7171   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7172
7173   SmallVector<int, 4> LoInputs;
7174   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7175                [](int M) { return M >= 0; });
7176   std::sort(LoInputs.begin(), LoInputs.end());
7177   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7178   SmallVector<int, 4> HiInputs;
7179   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7180                [](int M) { return M >= 0; });
7181   std::sort(HiInputs.begin(), HiInputs.end());
7182   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7183   int NumLToL =
7184       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7185   int NumHToL = LoInputs.size() - NumLToL;
7186   int NumLToH =
7187       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7188   int NumHToH = HiInputs.size() - NumLToH;
7189   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7190   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7191   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7192   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7193
7194   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7195   // such inputs we can swap two of the dwords across the half mark and end up
7196   // with <=2 inputs to each half in each half. Once there, we can fall through
7197   // to the generic code below. For example:
7198   //
7199   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7200   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7201   //
7202   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7203   // and 2-2.
7204   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7205                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7206     // Compute the index of dword with only one word among the three inputs in
7207     // a half by taking the sum of the half with three inputs and subtracting
7208     // the sum of the actual three inputs. The difference is the remaining
7209     // slot.
7210     int DWordA = (ThreeInputHalfSum -
7211                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7212                  2;
7213     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7214
7215     int PSHUFDMask[] = {0, 1, 2, 3};
7216     PSHUFDMask[DWordA] = DWordB;
7217     PSHUFDMask[DWordB] = DWordA;
7218     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7219                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7220                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7221                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7222
7223     // Adjust the mask to match the new locations of A and B.
7224     for (int &M : Mask)
7225       if (M != -1 && M/2 == DWordA)
7226         M = 2 * DWordB + M % 2;
7227       else if (M != -1 && M/2 == DWordB)
7228         M = 2 * DWordA + M % 2;
7229
7230     // Recurse back into this routine to re-compute state now that this isn't
7231     // a 3 and 1 problem.
7232     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7233                                 Mask);
7234   };
7235   if (NumLToL == 3 && NumHToL == 1)
7236     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7237   else if (NumLToL == 1 && NumHToL == 3)
7238     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7239   else if (NumLToH == 1 && NumHToH == 3)
7240     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7241   else if (NumLToH == 3 && NumHToH == 1)
7242     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7243
7244   // At this point there are at most two inputs to the low and high halves from
7245   // each half. That means the inputs can always be grouped into dwords and
7246   // those dwords can then be moved to the correct half with a dword shuffle.
7247   // We use at most one low and one high word shuffle to collect these paired
7248   // inputs into dwords, and finally a dword shuffle to place them.
7249   int PSHUFLMask[4] = {-1, -1, -1, -1};
7250   int PSHUFHMask[4] = {-1, -1, -1, -1};
7251   int PSHUFDMask[4] = {-1, -1, -1, -1};
7252
7253   // First fix the masks for all the inputs that are staying in their
7254   // original halves. This will then dictate the targets of the cross-half
7255   // shuffles.
7256   auto fixInPlaceInputs = [&PSHUFDMask](
7257       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7258       MutableArrayRef<int> HalfMask, int HalfOffset) {
7259     if (InPlaceInputs.empty())
7260       return;
7261     if (InPlaceInputs.size() == 1) {
7262       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7263           InPlaceInputs[0] - HalfOffset;
7264       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7265       return;
7266     }
7267
7268     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7269     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7270         InPlaceInputs[0] - HalfOffset;
7271     // Put the second input next to the first so that they are packed into
7272     // a dword. We find the adjacent index by toggling the low bit.
7273     int AdjIndex = InPlaceInputs[0] ^ 1;
7274     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7275     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7276     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7277   };
7278   if (!HToLInputs.empty())
7279     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7280   if (!LToHInputs.empty())
7281     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7282
7283   // Now gather the cross-half inputs and place them into a free dword of
7284   // their target half.
7285   // FIXME: This operation could almost certainly be simplified dramatically to
7286   // look more like the 3-1 fixing operation.
7287   auto moveInputsToRightHalf = [&PSHUFDMask](
7288       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7289       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7290       int SourceOffset, int DestOffset) {
7291     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7292       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7293     };
7294     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7295                                                int Word) {
7296       int LowWord = Word & ~1;
7297       int HighWord = Word | 1;
7298       return isWordClobbered(SourceHalfMask, LowWord) ||
7299              isWordClobbered(SourceHalfMask, HighWord);
7300     };
7301
7302     if (IncomingInputs.empty())
7303       return;
7304
7305     if (ExistingInputs.empty()) {
7306       // Map any dwords with inputs from them into the right half.
7307       for (int Input : IncomingInputs) {
7308         // If the source half mask maps over the inputs, turn those into
7309         // swaps and use the swapped lane.
7310         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7311           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7312             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7313                 Input - SourceOffset;
7314             // We have to swap the uses in our half mask in one sweep.
7315             for (int &M : HalfMask)
7316               if (M == SourceHalfMask[Input - SourceOffset])
7317                 M = Input;
7318               else if (M == Input)
7319                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7320           } else {
7321             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7322                        Input - SourceOffset &&
7323                    "Previous placement doesn't match!");
7324           }
7325           // Note that this correctly re-maps both when we do a swap and when
7326           // we observe the other side of the swap above. We rely on that to
7327           // avoid swapping the members of the input list directly.
7328           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7329         }
7330
7331         // Map the input's dword into the correct half.
7332         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7333           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7334         else
7335           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7336                      Input / 2 &&
7337                  "Previous placement doesn't match!");
7338       }
7339
7340       // And just directly shift any other-half mask elements to be same-half
7341       // as we will have mirrored the dword containing the element into the
7342       // same position within that half.
7343       for (int &M : HalfMask)
7344         if (M >= SourceOffset && M < SourceOffset + 4) {
7345           M = M - SourceOffset + DestOffset;
7346           assert(M >= 0 && "This should never wrap below zero!");
7347         }
7348       return;
7349     }
7350
7351     // Ensure we have the input in a viable dword of its current half. This
7352     // is particularly tricky because the original position may be clobbered
7353     // by inputs being moved and *staying* in that half.
7354     if (IncomingInputs.size() == 1) {
7355       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7356         int InputFixed = std::find(std::begin(SourceHalfMask),
7357                                    std::end(SourceHalfMask), -1) -
7358                          std::begin(SourceHalfMask) + SourceOffset;
7359         SourceHalfMask[InputFixed - SourceOffset] =
7360             IncomingInputs[0] - SourceOffset;
7361         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7362                      InputFixed);
7363         IncomingInputs[0] = InputFixed;
7364       }
7365     } else if (IncomingInputs.size() == 2) {
7366       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7367           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7368         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7369         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7370                "Not all dwords can be clobbered!");
7371         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7372         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7373         for (int &M : HalfMask)
7374           if (M == IncomingInputs[0])
7375             M = SourceDWordBase + SourceOffset;
7376           else if (M == IncomingInputs[1])
7377             M = SourceDWordBase + 1 + SourceOffset;
7378         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7379         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7380       }
7381     } else {
7382       llvm_unreachable("Unhandled input size!");
7383     }
7384
7385     // Now hoist the DWord down to the right half.
7386     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7387     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7388     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7389     for (int Input : IncomingInputs)
7390       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7391                    FreeDWord * 2 + Input % 2);
7392   };
7393   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7394                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7395   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7396                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7397
7398   // Now enact all the shuffles we've computed to move the inputs into their
7399   // target half.
7400   if (!isNoopShuffleMask(PSHUFLMask))
7401     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7402                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7403   if (!isNoopShuffleMask(PSHUFHMask))
7404     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7405                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7406   if (!isNoopShuffleMask(PSHUFDMask))
7407     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7408                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7409                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7410                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7411
7412   // At this point, each half should contain all its inputs, and we can then
7413   // just shuffle them into their final position.
7414   assert(std::count_if(LoMask.begin(), LoMask.end(),
7415                        [](int M) { return M >= 4; }) == 0 &&
7416          "Failed to lift all the high half inputs to the low mask!");
7417   assert(std::count_if(HiMask.begin(), HiMask.end(),
7418                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7419          "Failed to lift all the low half inputs to the high mask!");
7420
7421   // Do a half shuffle for the low mask.
7422   if (!isNoopShuffleMask(LoMask))
7423     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7424                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7425
7426   // Do a half shuffle with the high mask after shifting its values down.
7427   for (int &M : HiMask)
7428     if (M >= 0)
7429       M -= 4;
7430   if (!isNoopShuffleMask(HiMask))
7431     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7432                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7433
7434   return V;
7435 }
7436
7437 /// \brief Detect whether the mask pattern should be lowered through
7438 /// interleaving.
7439 ///
7440 /// This essentially tests whether viewing the mask as an interleaving of two
7441 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7442 /// lowering it through interleaving is a significantly better strategy.
7443 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7444   int NumEvenInputs[2] = {0, 0};
7445   int NumOddInputs[2] = {0, 0};
7446   int NumLoInputs[2] = {0, 0};
7447   int NumHiInputs[2] = {0, 0};
7448   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7449     if (Mask[i] < 0)
7450       continue;
7451
7452     int InputIdx = Mask[i] >= Size;
7453
7454     if (i < Size / 2)
7455       ++NumLoInputs[InputIdx];
7456     else
7457       ++NumHiInputs[InputIdx];
7458
7459     if ((i % 2) == 0)
7460       ++NumEvenInputs[InputIdx];
7461     else
7462       ++NumOddInputs[InputIdx];
7463   }
7464
7465   // The minimum number of cross-input results for both the interleaved and
7466   // split cases. If interleaving results in fewer cross-input results, return
7467   // true.
7468   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7469                                     NumEvenInputs[0] + NumOddInputs[1]);
7470   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7471                               NumLoInputs[0] + NumHiInputs[1]);
7472   return InterleavedCrosses < SplitCrosses;
7473 }
7474
7475 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7476 ///
7477 /// This strategy only works when the inputs from each vector fit into a single
7478 /// half of that vector, and generally there are not so many inputs as to leave
7479 /// the in-place shuffles required highly constrained (and thus expensive). It
7480 /// shifts all the inputs into a single side of both input vectors and then
7481 /// uses an unpack to interleave these inputs in a single vector. At that
7482 /// point, we will fall back on the generic single input shuffle lowering.
7483 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7484                                                  SDValue V2,
7485                                                  MutableArrayRef<int> Mask,
7486                                                  const X86Subtarget *Subtarget,
7487                                                  SelectionDAG &DAG) {
7488   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7489   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7490   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7491   for (int i = 0; i < 8; ++i)
7492     if (Mask[i] >= 0 && Mask[i] < 4)
7493       LoV1Inputs.push_back(i);
7494     else if (Mask[i] >= 4 && Mask[i] < 8)
7495       HiV1Inputs.push_back(i);
7496     else if (Mask[i] >= 8 && Mask[i] < 12)
7497       LoV2Inputs.push_back(i);
7498     else if (Mask[i] >= 12)
7499       HiV2Inputs.push_back(i);
7500
7501   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7502   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7503   (void)NumV1Inputs;
7504   (void)NumV2Inputs;
7505   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7506   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7507   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7508
7509   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7510                      HiV1Inputs.size() + HiV2Inputs.size();
7511
7512   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7513                               ArrayRef<int> HiInputs, bool MoveToLo,
7514                               int MaskOffset) {
7515     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7516     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7517     if (BadInputs.empty())
7518       return V;
7519
7520     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7521     int MoveOffset = MoveToLo ? 0 : 4;
7522
7523     if (GoodInputs.empty()) {
7524       for (int BadInput : BadInputs) {
7525         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7526         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7527       }
7528     } else {
7529       if (GoodInputs.size() == 2) {
7530         // If the low inputs are spread across two dwords, pack them into
7531         // a single dword.
7532         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7533             Mask[GoodInputs[0]] - MaskOffset;
7534         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7535             Mask[GoodInputs[1]] - MaskOffset;
7536         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7537         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7538       } else {
7539         // Otherwise pin the low inputs.
7540         for (int GoodInput : GoodInputs)
7541           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7542       }
7543
7544       int MoveMaskIdx =
7545           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7546           std::begin(MoveMask);
7547       assert(MoveMaskIdx >= MoveOffset && "Established above");
7548
7549       if (BadInputs.size() == 2) {
7550         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7551         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7552         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7553             Mask[BadInputs[0]] - MaskOffset;
7554         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7555             Mask[BadInputs[1]] - MaskOffset;
7556         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7557         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7558       } else {
7559         assert(BadInputs.size() == 1 && "All sizes handled");
7560         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7561         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7562       }
7563     }
7564
7565     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7566                                 MoveMask);
7567   };
7568   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7569                         /*MaskOffset*/ 0);
7570   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7571                         /*MaskOffset*/ 8);
7572
7573   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7574   // cross-half traffic in the final shuffle.
7575
7576   // Munge the mask to be a single-input mask after the unpack merges the
7577   // results.
7578   for (int &M : Mask)
7579     if (M != -1)
7580       M = 2 * (M % 4) + (M / 8);
7581
7582   return DAG.getVectorShuffle(
7583       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7584                                   DL, MVT::v8i16, V1, V2),
7585       DAG.getUNDEF(MVT::v8i16), Mask);
7586 }
7587
7588 /// \brief Generic lowering of 8-lane i16 shuffles.
7589 ///
7590 /// This handles both single-input shuffles and combined shuffle/blends with
7591 /// two inputs. The single input shuffles are immediately delegated to
7592 /// a dedicated lowering routine.
7593 ///
7594 /// The blends are lowered in one of three fundamental ways. If there are few
7595 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7596 /// of the input is significantly cheaper when lowered as an interleaving of
7597 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7598 /// halves of the inputs separately (making them have relatively few inputs)
7599 /// and then concatenate them.
7600 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7601                                        const X86Subtarget *Subtarget,
7602                                        SelectionDAG &DAG) {
7603   SDLoc DL(Op);
7604   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7605   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7606   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7607   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7608   ArrayRef<int> OrigMask = SVOp->getMask();
7609   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7610                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7611   MutableArrayRef<int> Mask(MaskStorage);
7612
7613   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7614
7615   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7616   auto isV2 = [](int M) { return M >= 8; };
7617
7618   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7619   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7620
7621   if (NumV2Inputs == 0)
7622     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7623
7624   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7625                             "to be V1-input shuffles.");
7626
7627   if (NumV1Inputs + NumV2Inputs <= 4)
7628     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7629
7630   // Check whether an interleaving lowering is likely to be more efficient.
7631   // This isn't perfect but it is a strong heuristic that tends to work well on
7632   // the kinds of shuffles that show up in practice.
7633   //
7634   // FIXME: Handle 1x, 2x, and 4x interleaving.
7635   if (shouldLowerAsInterleaving(Mask)) {
7636     // FIXME: Figure out whether we should pack these into the low or high
7637     // halves.
7638
7639     int EMask[8], OMask[8];
7640     for (int i = 0; i < 4; ++i) {
7641       EMask[i] = Mask[2*i];
7642       OMask[i] = Mask[2*i + 1];
7643       EMask[i + 4] = -1;
7644       OMask[i + 4] = -1;
7645     }
7646
7647     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7648     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7649
7650     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7651   }
7652
7653   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7654   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7655
7656   for (int i = 0; i < 4; ++i) {
7657     LoBlendMask[i] = Mask[i];
7658     HiBlendMask[i] = Mask[i + 4];
7659   }
7660
7661   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7662   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7663   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7664   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7665
7666   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7667                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7668 }
7669
7670 /// \brief Generic lowering of v16i8 shuffles.
7671 ///
7672 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7673 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7674 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7675 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7676 /// back together.
7677 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7678                                        const X86Subtarget *Subtarget,
7679                                        SelectionDAG &DAG) {
7680   SDLoc DL(Op);
7681   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7682   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7683   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7684   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7685   ArrayRef<int> OrigMask = SVOp->getMask();
7686   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7687   int MaskStorage[16] = {
7688       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7689       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7690       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7691       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7692   MutableArrayRef<int> Mask(MaskStorage);
7693   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7694   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7695
7696   // For single-input shuffles, there are some nicer lowering tricks we can use.
7697   if (isSingleInputShuffleMask(Mask)) {
7698     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7699     // Notably, this handles splat and partial-splat shuffles more efficiently.
7700     // However, it only makes sense if the pre-duplication shuffle simplifies
7701     // things significantly. Currently, this means we need to be able to
7702     // express the pre-duplication shuffle as an i16 shuffle.
7703     //
7704     // FIXME: We should check for other patterns which can be widened into an
7705     // i16 shuffle as well.
7706     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7707       for (int i = 0; i < 16; i += 2) {
7708         if (Mask[i] != Mask[i + 1])
7709           return false;
7710       }
7711       return true;
7712     };
7713     auto tryToWidenViaDuplication = [&]() -> SDValue {
7714       if (!canWidenViaDuplication(Mask))
7715         return SDValue();
7716       SmallVector<int, 4> LoInputs;
7717       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7718                    [](int M) { return M >= 0 && M < 8; });
7719       std::sort(LoInputs.begin(), LoInputs.end());
7720       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7721                      LoInputs.end());
7722       SmallVector<int, 4> HiInputs;
7723       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7724                    [](int M) { return M >= 8; });
7725       std::sort(HiInputs.begin(), HiInputs.end());
7726       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7727                      HiInputs.end());
7728
7729       bool TargetLo = LoInputs.size() >= HiInputs.size();
7730       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7731       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7732
7733       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7734       SmallDenseMap<int, int, 8> LaneMap;
7735       for (int I : InPlaceInputs) {
7736         PreDupI16Shuffle[I/2] = I/2;
7737         LaneMap[I] = I;
7738       }
7739       int j = TargetLo ? 0 : 4, je = j + 4;
7740       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7741         // Check if j is already a shuffle of this input. This happens when
7742         // there are two adjacent bytes after we move the low one.
7743         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7744           // If we haven't yet mapped the input, search for a slot into which
7745           // we can map it.
7746           while (j < je && PreDupI16Shuffle[j] != -1)
7747             ++j;
7748
7749           if (j == je)
7750             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7751             return SDValue();
7752
7753           // Map this input with the i16 shuffle.
7754           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7755         }
7756
7757         // Update the lane map based on the mapping we ended up with.
7758         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7759       }
7760       V1 = DAG.getNode(
7761           ISD::BITCAST, DL, MVT::v16i8,
7762           DAG.getVectorShuffle(MVT::v8i16, DL,
7763                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7764                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7765
7766       // Unpack the bytes to form the i16s that will be shuffled into place.
7767       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7768                        MVT::v16i8, V1, V1);
7769
7770       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7771       for (int i = 0; i < 16; i += 2) {
7772         if (Mask[i] != -1)
7773           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7774         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7775       }
7776       return DAG.getNode(
7777           ISD::BITCAST, DL, MVT::v16i8,
7778           DAG.getVectorShuffle(MVT::v8i16, DL,
7779                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7780                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7781     };
7782     if (SDValue V = tryToWidenViaDuplication())
7783       return V;
7784   }
7785
7786   // Check whether an interleaving lowering is likely to be more efficient.
7787   // This isn't perfect but it is a strong heuristic that tends to work well on
7788   // the kinds of shuffles that show up in practice.
7789   //
7790   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7791   if (shouldLowerAsInterleaving(Mask)) {
7792     // FIXME: Figure out whether we should pack these into the low or high
7793     // halves.
7794
7795     int EMask[16], OMask[16];
7796     for (int i = 0; i < 8; ++i) {
7797       EMask[i] = Mask[2*i];
7798       OMask[i] = Mask[2*i + 1];
7799       EMask[i + 8] = -1;
7800       OMask[i + 8] = -1;
7801     }
7802
7803     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7804     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7805
7806     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7807   }
7808
7809   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7810   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7811   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7812   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7813
7814   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7815                             MutableArrayRef<int> V1HalfBlendMask,
7816                             MutableArrayRef<int> V2HalfBlendMask) {
7817     for (int i = 0; i < 8; ++i)
7818       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7819         V1HalfBlendMask[i] = HalfMask[i];
7820         HalfMask[i] = i;
7821       } else if (HalfMask[i] >= 16) {
7822         V2HalfBlendMask[i] = HalfMask[i] - 16;
7823         HalfMask[i] = i + 8;
7824       }
7825   };
7826   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7827   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7828
7829   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7830
7831   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
7832                              MutableArrayRef<int> HiBlendMask) {
7833     SDValue V1, V2;
7834     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
7835     // them out and avoid using UNPCK{L,H} to extract the elements of V as
7836     // i16s.
7837     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
7838                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
7839         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
7840                      [](int M) { return M >= 0 && M % 2 == 1; })) {
7841       // Use a mask to drop the high bytes.
7842       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
7843       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
7844                        DAG.getConstant(0x00FF, MVT::v8i16));
7845
7846       // This will be a single vector shuffle instead of a blend so nuke V2.
7847       V2 = DAG.getUNDEF(MVT::v8i16);
7848
7849       // Squash the masks to point directly into V1.
7850       for (int &M : LoBlendMask)
7851         if (M >= 0)
7852           M /= 2;
7853       for (int &M : HiBlendMask)
7854         if (M >= 0)
7855           M /= 2;
7856     } else {
7857       // Otherwise just unpack the low half of V into V1 and the high half into
7858       // V2 so that we can blend them as i16s.
7859       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7860                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
7861       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7862                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
7863     }
7864
7865     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7866     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7867     return std::make_pair(BlendedLo, BlendedHi);
7868   };
7869   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
7870   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
7871   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
7872
7873   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7874   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7875
7876   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7877 }
7878
7879 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7880 ///
7881 /// This routine breaks down the specific type of 128-bit shuffle and
7882 /// dispatches to the lowering routines accordingly.
7883 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7884                                         MVT VT, const X86Subtarget *Subtarget,
7885                                         SelectionDAG &DAG) {
7886   switch (VT.SimpleTy) {
7887   case MVT::v2i64:
7888     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7889   case MVT::v2f64:
7890     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7891   case MVT::v4i32:
7892     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7893   case MVT::v4f32:
7894     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7895   case MVT::v8i16:
7896     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7897   case MVT::v16i8:
7898     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7899
7900   default:
7901     llvm_unreachable("Unimplemented!");
7902   }
7903 }
7904
7905 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7906 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7907   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7908     if (Mask[i] + 1 != Mask[i+1])
7909       return false;
7910
7911   return true;
7912 }
7913
7914 /// \brief Top-level lowering for x86 vector shuffles.
7915 ///
7916 /// This handles decomposition, canonicalization, and lowering of all x86
7917 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7918 /// above in helper routines. The canonicalization attempts to widen shuffles
7919 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7920 /// s.t. only one of the two inputs needs to be tested, etc.
7921 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7922                                   SelectionDAG &DAG) {
7923   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7924   ArrayRef<int> Mask = SVOp->getMask();
7925   SDValue V1 = Op.getOperand(0);
7926   SDValue V2 = Op.getOperand(1);
7927   MVT VT = Op.getSimpleValueType();
7928   int NumElements = VT.getVectorNumElements();
7929   SDLoc dl(Op);
7930
7931   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7932
7933   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7934   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7935   if (V1IsUndef && V2IsUndef)
7936     return DAG.getUNDEF(VT);
7937
7938   // When we create a shuffle node we put the UNDEF node to second operand,
7939   // but in some cases the first operand may be transformed to UNDEF.
7940   // In this case we should just commute the node.
7941   if (V1IsUndef)
7942     return DAG.getCommutedVectorShuffle(*SVOp);
7943
7944   // Check for non-undef masks pointing at an undef vector and make the masks
7945   // undef as well. This makes it easier to match the shuffle based solely on
7946   // the mask.
7947   if (V2IsUndef)
7948     for (int M : Mask)
7949       if (M >= NumElements) {
7950         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7951         for (int &M : NewMask)
7952           if (M >= NumElements)
7953             M = -1;
7954         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7955       }
7956
7957   // For integer vector shuffles, try to collapse them into a shuffle of fewer
7958   // lanes but wider integers. We cap this to not form integers larger than i64
7959   // but it might be interesting to form i128 integers to handle flipping the
7960   // low and high halves of AVX 256-bit vectors.
7961   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7962       areAdjacentMasksSequential(Mask)) {
7963     SmallVector<int, 8> NewMask;
7964     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7965       NewMask.push_back(Mask[i] / 2);
7966     MVT NewVT =
7967         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7968                          VT.getVectorNumElements() / 2);
7969     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7970     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7971     return DAG.getNode(ISD::BITCAST, dl, VT,
7972                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7973   }
7974
7975   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7976   for (int M : SVOp->getMask())
7977     if (M < 0)
7978       ++NumUndefElements;
7979     else if (M < NumElements)
7980       ++NumV1Elements;
7981     else
7982       ++NumV2Elements;
7983
7984   // Commute the shuffle as needed such that more elements come from V1 than
7985   // V2. This allows us to match the shuffle pattern strictly on how many
7986   // elements come from V1 without handling the symmetric cases.
7987   if (NumV2Elements > NumV1Elements)
7988     return DAG.getCommutedVectorShuffle(*SVOp);
7989
7990   // When the number of V1 and V2 elements are the same, try to minimize the
7991   // number of uses of V2 in the low half of the vector.
7992   if (NumV1Elements == NumV2Elements) {
7993     int LowV1Elements = 0, LowV2Elements = 0;
7994     for (int M : SVOp->getMask().slice(0, NumElements / 2))
7995       if (M >= NumElements)
7996         ++LowV2Elements;
7997       else if (M >= 0)
7998         ++LowV1Elements;
7999     if (LowV2Elements > LowV1Elements)
8000       return DAG.getCommutedVectorShuffle(*SVOp);
8001   }
8002
8003   // For each vector width, delegate to a specialized lowering routine.
8004   if (VT.getSizeInBits() == 128)
8005     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8006
8007   llvm_unreachable("Unimplemented!");
8008 }
8009
8010
8011 //===----------------------------------------------------------------------===//
8012 // Legacy vector shuffle lowering
8013 //
8014 // This code is the legacy code handling vector shuffles until the above
8015 // replaces its functionality and performance.
8016 //===----------------------------------------------------------------------===//
8017
8018 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8019                         bool hasInt256, unsigned *MaskOut = nullptr) {
8020   MVT EltVT = VT.getVectorElementType();
8021
8022   // There is no blend with immediate in AVX-512.
8023   if (VT.is512BitVector())
8024     return false;
8025
8026   if (!hasSSE41 || EltVT == MVT::i8)
8027     return false;
8028   if (!hasInt256 && VT == MVT::v16i16)
8029     return false;
8030
8031   unsigned MaskValue = 0;
8032   unsigned NumElems = VT.getVectorNumElements();
8033   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8034   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8035   unsigned NumElemsInLane = NumElems / NumLanes;
8036
8037   // Blend for v16i16 should be symetric for the both lanes.
8038   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8039
8040     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8041     int EltIdx = MaskVals[i];
8042
8043     if ((EltIdx < 0 || EltIdx == (int)i) &&
8044         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8045       continue;
8046
8047     if (((unsigned)EltIdx == (i + NumElems)) &&
8048         (SndLaneEltIdx < 0 ||
8049          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8050       MaskValue |= (1 << i);
8051     else
8052       return false;
8053   }
8054
8055   if (MaskOut)
8056     *MaskOut = MaskValue;
8057   return true;
8058 }
8059
8060 // Try to lower a shuffle node into a simple blend instruction.
8061 // This function assumes isBlendMask returns true for this
8062 // SuffleVectorSDNode
8063 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8064                                           unsigned MaskValue,
8065                                           const X86Subtarget *Subtarget,
8066                                           SelectionDAG &DAG) {
8067   MVT VT = SVOp->getSimpleValueType(0);
8068   MVT EltVT = VT.getVectorElementType();
8069   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8070                      Subtarget->hasInt256() && "Trying to lower a "
8071                                                "VECTOR_SHUFFLE to a Blend but "
8072                                                "with the wrong mask"));
8073   SDValue V1 = SVOp->getOperand(0);
8074   SDValue V2 = SVOp->getOperand(1);
8075   SDLoc dl(SVOp);
8076   unsigned NumElems = VT.getVectorNumElements();
8077
8078   // Convert i32 vectors to floating point if it is not AVX2.
8079   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8080   MVT BlendVT = VT;
8081   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8082     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8083                                NumElems);
8084     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8085     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8086   }
8087
8088   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8089                             DAG.getConstant(MaskValue, MVT::i32));
8090   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8091 }
8092
8093 /// In vector type \p VT, return true if the element at index \p InputIdx
8094 /// falls on a different 128-bit lane than \p OutputIdx.
8095 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8096                                      unsigned OutputIdx) {
8097   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8098   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8099 }
8100
8101 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8102 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8103 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8104 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8105 /// zero.
8106 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8107                          SelectionDAG &DAG) {
8108   MVT VT = V1.getSimpleValueType();
8109   assert(VT.is128BitVector() || VT.is256BitVector());
8110
8111   MVT EltVT = VT.getVectorElementType();
8112   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8113   unsigned NumElts = VT.getVectorNumElements();
8114
8115   SmallVector<SDValue, 32> PshufbMask;
8116   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8117     int InputIdx = MaskVals[OutputIdx];
8118     unsigned InputByteIdx;
8119
8120     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8121       InputByteIdx = 0x80;
8122     else {
8123       // Cross lane is not allowed.
8124       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8125         return SDValue();
8126       InputByteIdx = InputIdx * EltSizeInBytes;
8127       // Index is an byte offset within the 128-bit lane.
8128       InputByteIdx &= 0xf;
8129     }
8130
8131     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8132       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8133       if (InputByteIdx != 0x80)
8134         ++InputByteIdx;
8135     }
8136   }
8137
8138   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8139   if (ShufVT != VT)
8140     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8141   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8142                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8143 }
8144
8145 // v8i16 shuffles - Prefer shuffles in the following order:
8146 // 1. [all]   pshuflw, pshufhw, optional move
8147 // 2. [ssse3] 1 x pshufb
8148 // 3. [ssse3] 2 x pshufb + 1 x por
8149 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8150 static SDValue
8151 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8152                          SelectionDAG &DAG) {
8153   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8154   SDValue V1 = SVOp->getOperand(0);
8155   SDValue V2 = SVOp->getOperand(1);
8156   SDLoc dl(SVOp);
8157   SmallVector<int, 8> MaskVals;
8158
8159   // Determine if more than 1 of the words in each of the low and high quadwords
8160   // of the result come from the same quadword of one of the two inputs.  Undef
8161   // mask values count as coming from any quadword, for better codegen.
8162   //
8163   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8164   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8165   unsigned LoQuad[] = { 0, 0, 0, 0 };
8166   unsigned HiQuad[] = { 0, 0, 0, 0 };
8167   // Indices of quads used.
8168   std::bitset<4> InputQuads;
8169   for (unsigned i = 0; i < 8; ++i) {
8170     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8171     int EltIdx = SVOp->getMaskElt(i);
8172     MaskVals.push_back(EltIdx);
8173     if (EltIdx < 0) {
8174       ++Quad[0];
8175       ++Quad[1];
8176       ++Quad[2];
8177       ++Quad[3];
8178       continue;
8179     }
8180     ++Quad[EltIdx / 4];
8181     InputQuads.set(EltIdx / 4);
8182   }
8183
8184   int BestLoQuad = -1;
8185   unsigned MaxQuad = 1;
8186   for (unsigned i = 0; i < 4; ++i) {
8187     if (LoQuad[i] > MaxQuad) {
8188       BestLoQuad = i;
8189       MaxQuad = LoQuad[i];
8190     }
8191   }
8192
8193   int BestHiQuad = -1;
8194   MaxQuad = 1;
8195   for (unsigned i = 0; i < 4; ++i) {
8196     if (HiQuad[i] > MaxQuad) {
8197       BestHiQuad = i;
8198       MaxQuad = HiQuad[i];
8199     }
8200   }
8201
8202   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8203   // of the two input vectors, shuffle them into one input vector so only a
8204   // single pshufb instruction is necessary. If there are more than 2 input
8205   // quads, disable the next transformation since it does not help SSSE3.
8206   bool V1Used = InputQuads[0] || InputQuads[1];
8207   bool V2Used = InputQuads[2] || InputQuads[3];
8208   if (Subtarget->hasSSSE3()) {
8209     if (InputQuads.count() == 2 && V1Used && V2Used) {
8210       BestLoQuad = InputQuads[0] ? 0 : 1;
8211       BestHiQuad = InputQuads[2] ? 2 : 3;
8212     }
8213     if (InputQuads.count() > 2) {
8214       BestLoQuad = -1;
8215       BestHiQuad = -1;
8216     }
8217   }
8218
8219   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8220   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8221   // words from all 4 input quadwords.
8222   SDValue NewV;
8223   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8224     int MaskV[] = {
8225       BestLoQuad < 0 ? 0 : BestLoQuad,
8226       BestHiQuad < 0 ? 1 : BestHiQuad
8227     };
8228     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8229                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8230                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8231     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8232
8233     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8234     // source words for the shuffle, to aid later transformations.
8235     bool AllWordsInNewV = true;
8236     bool InOrder[2] = { true, true };
8237     for (unsigned i = 0; i != 8; ++i) {
8238       int idx = MaskVals[i];
8239       if (idx != (int)i)
8240         InOrder[i/4] = false;
8241       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8242         continue;
8243       AllWordsInNewV = false;
8244       break;
8245     }
8246
8247     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8248     if (AllWordsInNewV) {
8249       for (int i = 0; i != 8; ++i) {
8250         int idx = MaskVals[i];
8251         if (idx < 0)
8252           continue;
8253         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8254         if ((idx != i) && idx < 4)
8255           pshufhw = false;
8256         if ((idx != i) && idx > 3)
8257           pshuflw = false;
8258       }
8259       V1 = NewV;
8260       V2Used = false;
8261       BestLoQuad = 0;
8262       BestHiQuad = 1;
8263     }
8264
8265     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8266     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8267     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8268       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8269       unsigned TargetMask = 0;
8270       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8271                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8272       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8273       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8274                              getShufflePSHUFLWImmediate(SVOp);
8275       V1 = NewV.getOperand(0);
8276       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8277     }
8278   }
8279
8280   // Promote splats to a larger type which usually leads to more efficient code.
8281   // FIXME: Is this true if pshufb is available?
8282   if (SVOp->isSplat())
8283     return PromoteSplat(SVOp, DAG);
8284
8285   // If we have SSSE3, and all words of the result are from 1 input vector,
8286   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8287   // is present, fall back to case 4.
8288   if (Subtarget->hasSSSE3()) {
8289     SmallVector<SDValue,16> pshufbMask;
8290
8291     // If we have elements from both input vectors, set the high bit of the
8292     // shuffle mask element to zero out elements that come from V2 in the V1
8293     // mask, and elements that come from V1 in the V2 mask, so that the two
8294     // results can be OR'd together.
8295     bool TwoInputs = V1Used && V2Used;
8296     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8297     if (!TwoInputs)
8298       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8299
8300     // Calculate the shuffle mask for the second input, shuffle it, and
8301     // OR it with the first shuffled input.
8302     CommuteVectorShuffleMask(MaskVals, 8);
8303     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8304     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8305     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8306   }
8307
8308   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8309   // and update MaskVals with new element order.
8310   std::bitset<8> InOrder;
8311   if (BestLoQuad >= 0) {
8312     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8313     for (int i = 0; i != 4; ++i) {
8314       int idx = MaskVals[i];
8315       if (idx < 0) {
8316         InOrder.set(i);
8317       } else if ((idx / 4) == BestLoQuad) {
8318         MaskV[i] = idx & 3;
8319         InOrder.set(i);
8320       }
8321     }
8322     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8323                                 &MaskV[0]);
8324
8325     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8326       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8327       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8328                                   NewV.getOperand(0),
8329                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8330     }
8331   }
8332
8333   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8334   // and update MaskVals with the new element order.
8335   if (BestHiQuad >= 0) {
8336     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8337     for (unsigned i = 4; i != 8; ++i) {
8338       int idx = MaskVals[i];
8339       if (idx < 0) {
8340         InOrder.set(i);
8341       } else if ((idx / 4) == BestHiQuad) {
8342         MaskV[i] = (idx & 3) + 4;
8343         InOrder.set(i);
8344       }
8345     }
8346     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8347                                 &MaskV[0]);
8348
8349     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8350       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8351       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8352                                   NewV.getOperand(0),
8353                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8354     }
8355   }
8356
8357   // In case BestHi & BestLo were both -1, which means each quadword has a word
8358   // from each of the four input quadwords, calculate the InOrder bitvector now
8359   // before falling through to the insert/extract cleanup.
8360   if (BestLoQuad == -1 && BestHiQuad == -1) {
8361     NewV = V1;
8362     for (int i = 0; i != 8; ++i)
8363       if (MaskVals[i] < 0 || MaskVals[i] == i)
8364         InOrder.set(i);
8365   }
8366
8367   // The other elements are put in the right place using pextrw and pinsrw.
8368   for (unsigned i = 0; i != 8; ++i) {
8369     if (InOrder[i])
8370       continue;
8371     int EltIdx = MaskVals[i];
8372     if (EltIdx < 0)
8373       continue;
8374     SDValue ExtOp = (EltIdx < 8) ?
8375       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8376                   DAG.getIntPtrConstant(EltIdx)) :
8377       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8378                   DAG.getIntPtrConstant(EltIdx - 8));
8379     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8380                        DAG.getIntPtrConstant(i));
8381   }
8382   return NewV;
8383 }
8384
8385 /// \brief v16i16 shuffles
8386 ///
8387 /// FIXME: We only support generation of a single pshufb currently.  We can
8388 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8389 /// well (e.g 2 x pshufb + 1 x por).
8390 static SDValue
8391 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8392   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8393   SDValue V1 = SVOp->getOperand(0);
8394   SDValue V2 = SVOp->getOperand(1);
8395   SDLoc dl(SVOp);
8396
8397   if (V2.getOpcode() != ISD::UNDEF)
8398     return SDValue();
8399
8400   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8401   return getPSHUFB(MaskVals, V1, dl, DAG);
8402 }
8403
8404 // v16i8 shuffles - Prefer shuffles in the following order:
8405 // 1. [ssse3] 1 x pshufb
8406 // 2. [ssse3] 2 x pshufb + 1 x por
8407 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8408 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8409                                         const X86Subtarget* Subtarget,
8410                                         SelectionDAG &DAG) {
8411   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8412   SDValue V1 = SVOp->getOperand(0);
8413   SDValue V2 = SVOp->getOperand(1);
8414   SDLoc dl(SVOp);
8415   ArrayRef<int> MaskVals = SVOp->getMask();
8416
8417   // Promote splats to a larger type which usually leads to more efficient code.
8418   // FIXME: Is this true if pshufb is available?
8419   if (SVOp->isSplat())
8420     return PromoteSplat(SVOp, DAG);
8421
8422   // If we have SSSE3, case 1 is generated when all result bytes come from
8423   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8424   // present, fall back to case 3.
8425
8426   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8427   if (Subtarget->hasSSSE3()) {
8428     SmallVector<SDValue,16> pshufbMask;
8429
8430     // If all result elements are from one input vector, then only translate
8431     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8432     //
8433     // Otherwise, we have elements from both input vectors, and must zero out
8434     // elements that come from V2 in the first mask, and V1 in the second mask
8435     // so that we can OR them together.
8436     for (unsigned i = 0; i != 16; ++i) {
8437       int EltIdx = MaskVals[i];
8438       if (EltIdx < 0 || EltIdx >= 16)
8439         EltIdx = 0x80;
8440       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8441     }
8442     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8443                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8444                                  MVT::v16i8, pshufbMask));
8445
8446     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8447     // the 2nd operand if it's undefined or zero.
8448     if (V2.getOpcode() == ISD::UNDEF ||
8449         ISD::isBuildVectorAllZeros(V2.getNode()))
8450       return V1;
8451
8452     // Calculate the shuffle mask for the second input, shuffle it, and
8453     // OR it with the first shuffled input.
8454     pshufbMask.clear();
8455     for (unsigned i = 0; i != 16; ++i) {
8456       int EltIdx = MaskVals[i];
8457       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8458       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8459     }
8460     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8461                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8462                                  MVT::v16i8, pshufbMask));
8463     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8464   }
8465
8466   // No SSSE3 - Calculate in place words and then fix all out of place words
8467   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8468   // the 16 different words that comprise the two doublequadword input vectors.
8469   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8470   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8471   SDValue NewV = V1;
8472   for (int i = 0; i != 8; ++i) {
8473     int Elt0 = MaskVals[i*2];
8474     int Elt1 = MaskVals[i*2+1];
8475
8476     // This word of the result is all undef, skip it.
8477     if (Elt0 < 0 && Elt1 < 0)
8478       continue;
8479
8480     // This word of the result is already in the correct place, skip it.
8481     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8482       continue;
8483
8484     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8485     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8486     SDValue InsElt;
8487
8488     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8489     // using a single extract together, load it and store it.
8490     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8491       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8492                            DAG.getIntPtrConstant(Elt1 / 2));
8493       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8494                         DAG.getIntPtrConstant(i));
8495       continue;
8496     }
8497
8498     // If Elt1 is defined, extract it from the appropriate source.  If the
8499     // source byte is not also odd, shift the extracted word left 8 bits
8500     // otherwise clear the bottom 8 bits if we need to do an or.
8501     if (Elt1 >= 0) {
8502       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8503                            DAG.getIntPtrConstant(Elt1 / 2));
8504       if ((Elt1 & 1) == 0)
8505         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8506                              DAG.getConstant(8,
8507                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8508       else if (Elt0 >= 0)
8509         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8510                              DAG.getConstant(0xFF00, MVT::i16));
8511     }
8512     // If Elt0 is defined, extract it from the appropriate source.  If the
8513     // source byte is not also even, shift the extracted word right 8 bits. If
8514     // Elt1 was also defined, OR the extracted values together before
8515     // inserting them in the result.
8516     if (Elt0 >= 0) {
8517       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8518                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8519       if ((Elt0 & 1) != 0)
8520         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8521                               DAG.getConstant(8,
8522                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8523       else if (Elt1 >= 0)
8524         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8525                              DAG.getConstant(0x00FF, MVT::i16));
8526       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8527                          : InsElt0;
8528     }
8529     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8530                        DAG.getIntPtrConstant(i));
8531   }
8532   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8533 }
8534
8535 // v32i8 shuffles - Translate to VPSHUFB if possible.
8536 static
8537 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8538                                  const X86Subtarget *Subtarget,
8539                                  SelectionDAG &DAG) {
8540   MVT VT = SVOp->getSimpleValueType(0);
8541   SDValue V1 = SVOp->getOperand(0);
8542   SDValue V2 = SVOp->getOperand(1);
8543   SDLoc dl(SVOp);
8544   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8545
8546   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8547   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8548   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8549
8550   // VPSHUFB may be generated if
8551   // (1) one of input vector is undefined or zeroinitializer.
8552   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8553   // And (2) the mask indexes don't cross the 128-bit lane.
8554   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8555       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8556     return SDValue();
8557
8558   if (V1IsAllZero && !V2IsAllZero) {
8559     CommuteVectorShuffleMask(MaskVals, 32);
8560     V1 = V2;
8561   }
8562   return getPSHUFB(MaskVals, V1, dl, DAG);
8563 }
8564
8565 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8566 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8567 /// done when every pair / quad of shuffle mask elements point to elements in
8568 /// the right sequence. e.g.
8569 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8570 static
8571 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8572                                  SelectionDAG &DAG) {
8573   MVT VT = SVOp->getSimpleValueType(0);
8574   SDLoc dl(SVOp);
8575   unsigned NumElems = VT.getVectorNumElements();
8576   MVT NewVT;
8577   unsigned Scale;
8578   switch (VT.SimpleTy) {
8579   default: llvm_unreachable("Unexpected!");
8580   case MVT::v2i64:
8581   case MVT::v2f64:
8582            return SDValue(SVOp, 0);
8583   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8584   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8585   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8586   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8587   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8588   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8589   }
8590
8591   SmallVector<int, 8> MaskVec;
8592   for (unsigned i = 0; i != NumElems; i += Scale) {
8593     int StartIdx = -1;
8594     for (unsigned j = 0; j != Scale; ++j) {
8595       int EltIdx = SVOp->getMaskElt(i+j);
8596       if (EltIdx < 0)
8597         continue;
8598       if (StartIdx < 0)
8599         StartIdx = (EltIdx / Scale);
8600       if (EltIdx != (int)(StartIdx*Scale + j))
8601         return SDValue();
8602     }
8603     MaskVec.push_back(StartIdx);
8604   }
8605
8606   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8607   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8608   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8609 }
8610
8611 /// getVZextMovL - Return a zero-extending vector move low node.
8612 ///
8613 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8614                             SDValue SrcOp, SelectionDAG &DAG,
8615                             const X86Subtarget *Subtarget, SDLoc dl) {
8616   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8617     LoadSDNode *LD = nullptr;
8618     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8619       LD = dyn_cast<LoadSDNode>(SrcOp);
8620     if (!LD) {
8621       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8622       // instead.
8623       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8624       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8625           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8626           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8627           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8628         // PR2108
8629         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8630         return DAG.getNode(ISD::BITCAST, dl, VT,
8631                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8632                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8633                                                    OpVT,
8634                                                    SrcOp.getOperand(0)
8635                                                           .getOperand(0))));
8636       }
8637     }
8638   }
8639
8640   return DAG.getNode(ISD::BITCAST, dl, VT,
8641                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8642                                  DAG.getNode(ISD::BITCAST, dl,
8643                                              OpVT, SrcOp)));
8644 }
8645
8646 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8647 /// which could not be matched by any known target speficic shuffle
8648 static SDValue
8649 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8650
8651   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8652   if (NewOp.getNode())
8653     return NewOp;
8654
8655   MVT VT = SVOp->getSimpleValueType(0);
8656
8657   unsigned NumElems = VT.getVectorNumElements();
8658   unsigned NumLaneElems = NumElems / 2;
8659
8660   SDLoc dl(SVOp);
8661   MVT EltVT = VT.getVectorElementType();
8662   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8663   SDValue Output[2];
8664
8665   SmallVector<int, 16> Mask;
8666   for (unsigned l = 0; l < 2; ++l) {
8667     // Build a shuffle mask for the output, discovering on the fly which
8668     // input vectors to use as shuffle operands (recorded in InputUsed).
8669     // If building a suitable shuffle vector proves too hard, then bail
8670     // out with UseBuildVector set.
8671     bool UseBuildVector = false;
8672     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8673     unsigned LaneStart = l * NumLaneElems;
8674     for (unsigned i = 0; i != NumLaneElems; ++i) {
8675       // The mask element.  This indexes into the input.
8676       int Idx = SVOp->getMaskElt(i+LaneStart);
8677       if (Idx < 0) {
8678         // the mask element does not index into any input vector.
8679         Mask.push_back(-1);
8680         continue;
8681       }
8682
8683       // The input vector this mask element indexes into.
8684       int Input = Idx / NumLaneElems;
8685
8686       // Turn the index into an offset from the start of the input vector.
8687       Idx -= Input * NumLaneElems;
8688
8689       // Find or create a shuffle vector operand to hold this input.
8690       unsigned OpNo;
8691       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8692         if (InputUsed[OpNo] == Input)
8693           // This input vector is already an operand.
8694           break;
8695         if (InputUsed[OpNo] < 0) {
8696           // Create a new operand for this input vector.
8697           InputUsed[OpNo] = Input;
8698           break;
8699         }
8700       }
8701
8702       if (OpNo >= array_lengthof(InputUsed)) {
8703         // More than two input vectors used!  Give up on trying to create a
8704         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8705         UseBuildVector = true;
8706         break;
8707       }
8708
8709       // Add the mask index for the new shuffle vector.
8710       Mask.push_back(Idx + OpNo * NumLaneElems);
8711     }
8712
8713     if (UseBuildVector) {
8714       SmallVector<SDValue, 16> SVOps;
8715       for (unsigned i = 0; i != NumLaneElems; ++i) {
8716         // The mask element.  This indexes into the input.
8717         int Idx = SVOp->getMaskElt(i+LaneStart);
8718         if (Idx < 0) {
8719           SVOps.push_back(DAG.getUNDEF(EltVT));
8720           continue;
8721         }
8722
8723         // The input vector this mask element indexes into.
8724         int Input = Idx / NumElems;
8725
8726         // Turn the index into an offset from the start of the input vector.
8727         Idx -= Input * NumElems;
8728
8729         // Extract the vector element by hand.
8730         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8731                                     SVOp->getOperand(Input),
8732                                     DAG.getIntPtrConstant(Idx)));
8733       }
8734
8735       // Construct the output using a BUILD_VECTOR.
8736       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8737     } else if (InputUsed[0] < 0) {
8738       // No input vectors were used! The result is undefined.
8739       Output[l] = DAG.getUNDEF(NVT);
8740     } else {
8741       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8742                                         (InputUsed[0] % 2) * NumLaneElems,
8743                                         DAG, dl);
8744       // If only one input was used, use an undefined vector for the other.
8745       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8746         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8747                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8748       // At least one input vector was used. Create a new shuffle vector.
8749       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8750     }
8751
8752     Mask.clear();
8753   }
8754
8755   // Concatenate the result back
8756   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8757 }
8758
8759 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8760 /// 4 elements, and match them with several different shuffle types.
8761 static SDValue
8762 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8763   SDValue V1 = SVOp->getOperand(0);
8764   SDValue V2 = SVOp->getOperand(1);
8765   SDLoc dl(SVOp);
8766   MVT VT = SVOp->getSimpleValueType(0);
8767
8768   assert(VT.is128BitVector() && "Unsupported vector size");
8769
8770   std::pair<int, int> Locs[4];
8771   int Mask1[] = { -1, -1, -1, -1 };
8772   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8773
8774   unsigned NumHi = 0;
8775   unsigned NumLo = 0;
8776   for (unsigned i = 0; i != 4; ++i) {
8777     int Idx = PermMask[i];
8778     if (Idx < 0) {
8779       Locs[i] = std::make_pair(-1, -1);
8780     } else {
8781       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8782       if (Idx < 4) {
8783         Locs[i] = std::make_pair(0, NumLo);
8784         Mask1[NumLo] = Idx;
8785         NumLo++;
8786       } else {
8787         Locs[i] = std::make_pair(1, NumHi);
8788         if (2+NumHi < 4)
8789           Mask1[2+NumHi] = Idx;
8790         NumHi++;
8791       }
8792     }
8793   }
8794
8795   if (NumLo <= 2 && NumHi <= 2) {
8796     // If no more than two elements come from either vector. This can be
8797     // implemented with two shuffles. First shuffle gather the elements.
8798     // The second shuffle, which takes the first shuffle as both of its
8799     // vector operands, put the elements into the right order.
8800     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8801
8802     int Mask2[] = { -1, -1, -1, -1 };
8803
8804     for (unsigned i = 0; i != 4; ++i)
8805       if (Locs[i].first != -1) {
8806         unsigned Idx = (i < 2) ? 0 : 4;
8807         Idx += Locs[i].first * 2 + Locs[i].second;
8808         Mask2[i] = Idx;
8809       }
8810
8811     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8812   }
8813
8814   if (NumLo == 3 || NumHi == 3) {
8815     // Otherwise, we must have three elements from one vector, call it X, and
8816     // one element from the other, call it Y.  First, use a shufps to build an
8817     // intermediate vector with the one element from Y and the element from X
8818     // that will be in the same half in the final destination (the indexes don't
8819     // matter). Then, use a shufps to build the final vector, taking the half
8820     // containing the element from Y from the intermediate, and the other half
8821     // from X.
8822     if (NumHi == 3) {
8823       // Normalize it so the 3 elements come from V1.
8824       CommuteVectorShuffleMask(PermMask, 4);
8825       std::swap(V1, V2);
8826     }
8827
8828     // Find the element from V2.
8829     unsigned HiIndex;
8830     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8831       int Val = PermMask[HiIndex];
8832       if (Val < 0)
8833         continue;
8834       if (Val >= 4)
8835         break;
8836     }
8837
8838     Mask1[0] = PermMask[HiIndex];
8839     Mask1[1] = -1;
8840     Mask1[2] = PermMask[HiIndex^1];
8841     Mask1[3] = -1;
8842     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8843
8844     if (HiIndex >= 2) {
8845       Mask1[0] = PermMask[0];
8846       Mask1[1] = PermMask[1];
8847       Mask1[2] = HiIndex & 1 ? 6 : 4;
8848       Mask1[3] = HiIndex & 1 ? 4 : 6;
8849       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8850     }
8851
8852     Mask1[0] = HiIndex & 1 ? 2 : 0;
8853     Mask1[1] = HiIndex & 1 ? 0 : 2;
8854     Mask1[2] = PermMask[2];
8855     Mask1[3] = PermMask[3];
8856     if (Mask1[2] >= 0)
8857       Mask1[2] += 4;
8858     if (Mask1[3] >= 0)
8859       Mask1[3] += 4;
8860     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8861   }
8862
8863   // Break it into (shuffle shuffle_hi, shuffle_lo).
8864   int LoMask[] = { -1, -1, -1, -1 };
8865   int HiMask[] = { -1, -1, -1, -1 };
8866
8867   int *MaskPtr = LoMask;
8868   unsigned MaskIdx = 0;
8869   unsigned LoIdx = 0;
8870   unsigned HiIdx = 2;
8871   for (unsigned i = 0; i != 4; ++i) {
8872     if (i == 2) {
8873       MaskPtr = HiMask;
8874       MaskIdx = 1;
8875       LoIdx = 0;
8876       HiIdx = 2;
8877     }
8878     int Idx = PermMask[i];
8879     if (Idx < 0) {
8880       Locs[i] = std::make_pair(-1, -1);
8881     } else if (Idx < 4) {
8882       Locs[i] = std::make_pair(MaskIdx, LoIdx);
8883       MaskPtr[LoIdx] = Idx;
8884       LoIdx++;
8885     } else {
8886       Locs[i] = std::make_pair(MaskIdx, HiIdx);
8887       MaskPtr[HiIdx] = Idx;
8888       HiIdx++;
8889     }
8890   }
8891
8892   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8893   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8894   int MaskOps[] = { -1, -1, -1, -1 };
8895   for (unsigned i = 0; i != 4; ++i)
8896     if (Locs[i].first != -1)
8897       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8898   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8899 }
8900
8901 static bool MayFoldVectorLoad(SDValue V) {
8902   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8903     V = V.getOperand(0);
8904
8905   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8906     V = V.getOperand(0);
8907   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8908       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8909     // BUILD_VECTOR (load), undef
8910     V = V.getOperand(0);
8911
8912   return MayFoldLoad(V);
8913 }
8914
8915 static
8916 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8917   MVT VT = Op.getSimpleValueType();
8918
8919   // Canonizalize to v2f64.
8920   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8921   return DAG.getNode(ISD::BITCAST, dl, VT,
8922                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8923                                           V1, DAG));
8924 }
8925
8926 static
8927 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8928                         bool HasSSE2) {
8929   SDValue V1 = Op.getOperand(0);
8930   SDValue V2 = Op.getOperand(1);
8931   MVT VT = Op.getSimpleValueType();
8932
8933   assert(VT != MVT::v2i64 && "unsupported shuffle type");
8934
8935   if (HasSSE2 && VT == MVT::v2f64)
8936     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8937
8938   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8939   return DAG.getNode(ISD::BITCAST, dl, VT,
8940                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8941                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8942                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8943 }
8944
8945 static
8946 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8947   SDValue V1 = Op.getOperand(0);
8948   SDValue V2 = Op.getOperand(1);
8949   MVT VT = Op.getSimpleValueType();
8950
8951   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8952          "unsupported shuffle type");
8953
8954   if (V2.getOpcode() == ISD::UNDEF)
8955     V2 = V1;
8956
8957   // v4i32 or v4f32
8958   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8959 }
8960
8961 static
8962 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8963   SDValue V1 = Op.getOperand(0);
8964   SDValue V2 = Op.getOperand(1);
8965   MVT VT = Op.getSimpleValueType();
8966   unsigned NumElems = VT.getVectorNumElements();
8967
8968   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8969   // operand of these instructions is only memory, so check if there's a
8970   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8971   // same masks.
8972   bool CanFoldLoad = false;
8973
8974   // Trivial case, when V2 comes from a load.
8975   if (MayFoldVectorLoad(V2))
8976     CanFoldLoad = true;
8977
8978   // When V1 is a load, it can be folded later into a store in isel, example:
8979   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8980   //    turns into:
8981   //  (MOVLPSmr addr:$src1, VR128:$src2)
8982   // So, recognize this potential and also use MOVLPS or MOVLPD
8983   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8984     CanFoldLoad = true;
8985
8986   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8987   if (CanFoldLoad) {
8988     if (HasSSE2 && NumElems == 2)
8989       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
8990
8991     if (NumElems == 4)
8992       // If we don't care about the second element, proceed to use movss.
8993       if (SVOp->getMaskElt(1) != -1)
8994         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
8995   }
8996
8997   // movl and movlp will both match v2i64, but v2i64 is never matched by
8998   // movl earlier because we make it strict to avoid messing with the movlp load
8999   // folding logic (see the code above getMOVLP call). Match it here then,
9000   // this is horrible, but will stay like this until we move all shuffle
9001   // matching to x86 specific nodes. Note that for the 1st condition all
9002   // types are matched with movsd.
9003   if (HasSSE2) {
9004     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9005     // as to remove this logic from here, as much as possible
9006     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9007       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9008     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9009   }
9010
9011   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9012
9013   // Invert the operand order and use SHUFPS to match it.
9014   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9015                               getShuffleSHUFImmediate(SVOp), DAG);
9016 }
9017
9018 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9019                                          SelectionDAG &DAG) {
9020   SDLoc dl(Load);
9021   MVT VT = Load->getSimpleValueType(0);
9022   MVT EVT = VT.getVectorElementType();
9023   SDValue Addr = Load->getOperand(1);
9024   SDValue NewAddr = DAG.getNode(
9025       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9026       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9027
9028   SDValue NewLoad =
9029       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9030                   DAG.getMachineFunction().getMachineMemOperand(
9031                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9032   return NewLoad;
9033 }
9034
9035 // It is only safe to call this function if isINSERTPSMask is true for
9036 // this shufflevector mask.
9037 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9038                            SelectionDAG &DAG) {
9039   // Generate an insertps instruction when inserting an f32 from memory onto a
9040   // v4f32 or when copying a member from one v4f32 to another.
9041   // We also use it for transferring i32 from one register to another,
9042   // since it simply copies the same bits.
9043   // If we're transferring an i32 from memory to a specific element in a
9044   // register, we output a generic DAG that will match the PINSRD
9045   // instruction.
9046   MVT VT = SVOp->getSimpleValueType(0);
9047   MVT EVT = VT.getVectorElementType();
9048   SDValue V1 = SVOp->getOperand(0);
9049   SDValue V2 = SVOp->getOperand(1);
9050   auto Mask = SVOp->getMask();
9051   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9052          "unsupported vector type for insertps/pinsrd");
9053
9054   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9055   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9056   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9057
9058   SDValue From;
9059   SDValue To;
9060   unsigned DestIndex;
9061   if (FromV1 == 1) {
9062     From = V1;
9063     To = V2;
9064     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9065                 Mask.begin();
9066
9067     // If we have 1 element from each vector, we have to check if we're
9068     // changing V1's element's place. If so, we're done. Otherwise, we
9069     // should assume we're changing V2's element's place and behave
9070     // accordingly.
9071     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9072     assert(DestIndex <= INT32_MAX && "truncated destination index");
9073     if (FromV1 == FromV2 &&
9074         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9075       From = V2;
9076       To = V1;
9077       DestIndex =
9078           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9079     }
9080   } else {
9081     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9082            "More than one element from V1 and from V2, or no elements from one "
9083            "of the vectors. This case should not have returned true from "
9084            "isINSERTPSMask");
9085     From = V2;
9086     To = V1;
9087     DestIndex =
9088         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9089   }
9090
9091   // Get an index into the source vector in the range [0,4) (the mask is
9092   // in the range [0,8) because it can address V1 and V2)
9093   unsigned SrcIndex = Mask[DestIndex] % 4;
9094   if (MayFoldLoad(From)) {
9095     // Trivial case, when From comes from a load and is only used by the
9096     // shuffle. Make it use insertps from the vector that we need from that
9097     // load.
9098     SDValue NewLoad =
9099         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9100     if (!NewLoad.getNode())
9101       return SDValue();
9102
9103     if (EVT == MVT::f32) {
9104       // Create this as a scalar to vector to match the instruction pattern.
9105       SDValue LoadScalarToVector =
9106           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9107       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9108       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9109                          InsertpsMask);
9110     } else { // EVT == MVT::i32
9111       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9112       // instruction, to match the PINSRD instruction, which loads an i32 to a
9113       // certain vector element.
9114       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9115                          DAG.getConstant(DestIndex, MVT::i32));
9116     }
9117   }
9118
9119   // Vector-element-to-vector
9120   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9121   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9122 }
9123
9124 // Reduce a vector shuffle to zext.
9125 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9126                                     SelectionDAG &DAG) {
9127   // PMOVZX is only available from SSE41.
9128   if (!Subtarget->hasSSE41())
9129     return SDValue();
9130
9131   MVT VT = Op.getSimpleValueType();
9132
9133   // Only AVX2 support 256-bit vector integer extending.
9134   if (!Subtarget->hasInt256() && VT.is256BitVector())
9135     return SDValue();
9136
9137   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9138   SDLoc DL(Op);
9139   SDValue V1 = Op.getOperand(0);
9140   SDValue V2 = Op.getOperand(1);
9141   unsigned NumElems = VT.getVectorNumElements();
9142
9143   // Extending is an unary operation and the element type of the source vector
9144   // won't be equal to or larger than i64.
9145   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9146       VT.getVectorElementType() == MVT::i64)
9147     return SDValue();
9148
9149   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9150   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9151   while ((1U << Shift) < NumElems) {
9152     if (SVOp->getMaskElt(1U << Shift) == 1)
9153       break;
9154     Shift += 1;
9155     // The maximal ratio is 8, i.e. from i8 to i64.
9156     if (Shift > 3)
9157       return SDValue();
9158   }
9159
9160   // Check the shuffle mask.
9161   unsigned Mask = (1U << Shift) - 1;
9162   for (unsigned i = 0; i != NumElems; ++i) {
9163     int EltIdx = SVOp->getMaskElt(i);
9164     if ((i & Mask) != 0 && EltIdx != -1)
9165       return SDValue();
9166     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9167       return SDValue();
9168   }
9169
9170   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9171   MVT NeVT = MVT::getIntegerVT(NBits);
9172   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9173
9174   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9175     return SDValue();
9176
9177   // Simplify the operand as it's prepared to be fed into shuffle.
9178   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9179   if (V1.getOpcode() == ISD::BITCAST &&
9180       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9181       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9182       V1.getOperand(0).getOperand(0)
9183         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9184     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9185     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9186     ConstantSDNode *CIdx =
9187       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9188     // If it's foldable, i.e. normal load with single use, we will let code
9189     // selection to fold it. Otherwise, we will short the conversion sequence.
9190     if (CIdx && CIdx->getZExtValue() == 0 &&
9191         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9192       MVT FullVT = V.getSimpleValueType();
9193       MVT V1VT = V1.getSimpleValueType();
9194       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9195         // The "ext_vec_elt" node is wider than the result node.
9196         // In this case we should extract subvector from V.
9197         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9198         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9199         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9200                                         FullVT.getVectorNumElements()/Ratio);
9201         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9202                         DAG.getIntPtrConstant(0));
9203       }
9204       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9205     }
9206   }
9207
9208   return DAG.getNode(ISD::BITCAST, DL, VT,
9209                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9210 }
9211
9212 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9213                                       SelectionDAG &DAG) {
9214   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9215   MVT VT = Op.getSimpleValueType();
9216   SDLoc dl(Op);
9217   SDValue V1 = Op.getOperand(0);
9218   SDValue V2 = Op.getOperand(1);
9219
9220   if (isZeroShuffle(SVOp))
9221     return getZeroVector(VT, Subtarget, DAG, dl);
9222
9223   // Handle splat operations
9224   if (SVOp->isSplat()) {
9225     // Use vbroadcast whenever the splat comes from a foldable load
9226     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9227     if (Broadcast.getNode())
9228       return Broadcast;
9229   }
9230
9231   // Check integer expanding shuffles.
9232   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9233   if (NewOp.getNode())
9234     return NewOp;
9235
9236   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9237   // do it!
9238   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9239       VT == MVT::v32i8) {
9240     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9241     if (NewOp.getNode())
9242       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9243   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9244     // FIXME: Figure out a cleaner way to do this.
9245     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9246       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9247       if (NewOp.getNode()) {
9248         MVT NewVT = NewOp.getSimpleValueType();
9249         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9250                                NewVT, true, false))
9251           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9252                               dl);
9253       }
9254     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9255       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9256       if (NewOp.getNode()) {
9257         MVT NewVT = NewOp.getSimpleValueType();
9258         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9259           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9260                               dl);
9261       }
9262     }
9263   }
9264   return SDValue();
9265 }
9266
9267 SDValue
9268 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9269   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9270   SDValue V1 = Op.getOperand(0);
9271   SDValue V2 = Op.getOperand(1);
9272   MVT VT = Op.getSimpleValueType();
9273   SDLoc dl(Op);
9274   unsigned NumElems = VT.getVectorNumElements();
9275   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9276   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9277   bool V1IsSplat = false;
9278   bool V2IsSplat = false;
9279   bool HasSSE2 = Subtarget->hasSSE2();
9280   bool HasFp256    = Subtarget->hasFp256();
9281   bool HasInt256   = Subtarget->hasInt256();
9282   MachineFunction &MF = DAG.getMachineFunction();
9283   bool OptForSize = MF.getFunction()->getAttributes().
9284     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9285
9286   // Check if we should use the experimental vector shuffle lowering. If so,
9287   // delegate completely to that code path.
9288   if (ExperimentalVectorShuffleLowering)
9289     return lowerVectorShuffle(Op, Subtarget, DAG);
9290
9291   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9292
9293   if (V1IsUndef && V2IsUndef)
9294     return DAG.getUNDEF(VT);
9295
9296   // When we create a shuffle node we put the UNDEF node to second operand,
9297   // but in some cases the first operand may be transformed to UNDEF.
9298   // In this case we should just commute the node.
9299   if (V1IsUndef)
9300     return DAG.getCommutedVectorShuffle(*SVOp);
9301
9302   // Vector shuffle lowering takes 3 steps:
9303   //
9304   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9305   //    narrowing and commutation of operands should be handled.
9306   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9307   //    shuffle nodes.
9308   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9309   //    so the shuffle can be broken into other shuffles and the legalizer can
9310   //    try the lowering again.
9311   //
9312   // The general idea is that no vector_shuffle operation should be left to
9313   // be matched during isel, all of them must be converted to a target specific
9314   // node here.
9315
9316   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9317   // narrowing and commutation of operands should be handled. The actual code
9318   // doesn't include all of those, work in progress...
9319   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9320   if (NewOp.getNode())
9321     return NewOp;
9322
9323   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9324
9325   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9326   // unpckh_undef). Only use pshufd if speed is more important than size.
9327   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9328     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9329   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9330     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9331
9332   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9333       V2IsUndef && MayFoldVectorLoad(V1))
9334     return getMOVDDup(Op, dl, V1, DAG);
9335
9336   if (isMOVHLPS_v_undef_Mask(M, VT))
9337     return getMOVHighToLow(Op, dl, DAG);
9338
9339   // Use to match splats
9340   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9341       (VT == MVT::v2f64 || VT == MVT::v2i64))
9342     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9343
9344   if (isPSHUFDMask(M, VT)) {
9345     // The actual implementation will match the mask in the if above and then
9346     // during isel it can match several different instructions, not only pshufd
9347     // as its name says, sad but true, emulate the behavior for now...
9348     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9349       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9350
9351     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9352
9353     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9354       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9355
9356     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9357       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9358                                   DAG);
9359
9360     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9361                                 TargetMask, DAG);
9362   }
9363
9364   if (isPALIGNRMask(M, VT, Subtarget))
9365     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9366                                 getShufflePALIGNRImmediate(SVOp),
9367                                 DAG);
9368
9369   // Check if this can be converted into a logical shift.
9370   bool isLeft = false;
9371   unsigned ShAmt = 0;
9372   SDValue ShVal;
9373   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9374   if (isShift && ShVal.hasOneUse()) {
9375     // If the shifted value has multiple uses, it may be cheaper to use
9376     // v_set0 + movlhps or movhlps, etc.
9377     MVT EltVT = VT.getVectorElementType();
9378     ShAmt *= EltVT.getSizeInBits();
9379     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9380   }
9381
9382   if (isMOVLMask(M, VT)) {
9383     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9384       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9385     if (!isMOVLPMask(M, VT)) {
9386       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9387         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9388
9389       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9390         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9391     }
9392   }
9393
9394   // FIXME: fold these into legal mask.
9395   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9396     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9397
9398   if (isMOVHLPSMask(M, VT))
9399     return getMOVHighToLow(Op, dl, DAG);
9400
9401   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9402     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9403
9404   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9405     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9406
9407   if (isMOVLPMask(M, VT))
9408     return getMOVLP(Op, dl, DAG, HasSSE2);
9409
9410   if (ShouldXformToMOVHLPS(M, VT) ||
9411       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9412     return DAG.getCommutedVectorShuffle(*SVOp);
9413
9414   if (isShift) {
9415     // No better options. Use a vshldq / vsrldq.
9416     MVT EltVT = VT.getVectorElementType();
9417     ShAmt *= EltVT.getSizeInBits();
9418     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9419   }
9420
9421   bool Commuted = false;
9422   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9423   // 1,1,1,1 -> v8i16 though.
9424   BitVector UndefElements;
9425   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9426     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9427       V1IsSplat = true;
9428   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9429     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9430       V2IsSplat = true;
9431
9432   // Canonicalize the splat or undef, if present, to be on the RHS.
9433   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9434     CommuteVectorShuffleMask(M, NumElems);
9435     std::swap(V1, V2);
9436     std::swap(V1IsSplat, V2IsSplat);
9437     Commuted = true;
9438   }
9439
9440   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9441     // Shuffling low element of v1 into undef, just return v1.
9442     if (V2IsUndef)
9443       return V1;
9444     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9445     // the instruction selector will not match, so get a canonical MOVL with
9446     // swapped operands to undo the commute.
9447     return getMOVL(DAG, dl, VT, V2, V1);
9448   }
9449
9450   if (isUNPCKLMask(M, VT, HasInt256))
9451     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9452
9453   if (isUNPCKHMask(M, VT, HasInt256))
9454     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9455
9456   if (V2IsSplat) {
9457     // Normalize mask so all entries that point to V2 points to its first
9458     // element then try to match unpck{h|l} again. If match, return a
9459     // new vector_shuffle with the corrected mask.p
9460     SmallVector<int, 8> NewMask(M.begin(), M.end());
9461     NormalizeMask(NewMask, NumElems);
9462     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9463       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9464     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9465       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9466   }
9467
9468   if (Commuted) {
9469     // Commute is back and try unpck* again.
9470     // FIXME: this seems wrong.
9471     CommuteVectorShuffleMask(M, NumElems);
9472     std::swap(V1, V2);
9473     std::swap(V1IsSplat, V2IsSplat);
9474
9475     if (isUNPCKLMask(M, VT, HasInt256))
9476       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9477
9478     if (isUNPCKHMask(M, VT, HasInt256))
9479       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9480   }
9481
9482   // Normalize the node to match x86 shuffle ops if needed
9483   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9484     return DAG.getCommutedVectorShuffle(*SVOp);
9485
9486   // The checks below are all present in isShuffleMaskLegal, but they are
9487   // inlined here right now to enable us to directly emit target specific
9488   // nodes, and remove one by one until they don't return Op anymore.
9489
9490   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9491       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9492     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9493       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9494   }
9495
9496   if (isPSHUFHWMask(M, VT, HasInt256))
9497     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9498                                 getShufflePSHUFHWImmediate(SVOp),
9499                                 DAG);
9500
9501   if (isPSHUFLWMask(M, VT, HasInt256))
9502     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9503                                 getShufflePSHUFLWImmediate(SVOp),
9504                                 DAG);
9505
9506   unsigned MaskValue;
9507   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9508                   &MaskValue))
9509     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9510
9511   if (isSHUFPMask(M, VT))
9512     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9513                                 getShuffleSHUFImmediate(SVOp), DAG);
9514
9515   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9516     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9517   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9518     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9519
9520   //===--------------------------------------------------------------------===//
9521   // Generate target specific nodes for 128 or 256-bit shuffles only
9522   // supported in the AVX instruction set.
9523   //
9524
9525   // Handle VMOVDDUPY permutations
9526   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9527     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9528
9529   // Handle VPERMILPS/D* permutations
9530   if (isVPERMILPMask(M, VT)) {
9531     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9532       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9533                                   getShuffleSHUFImmediate(SVOp), DAG);
9534     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9535                                 getShuffleSHUFImmediate(SVOp), DAG);
9536   }
9537
9538   unsigned Idx;
9539   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9540     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9541                               Idx*(NumElems/2), DAG, dl);
9542
9543   // Handle VPERM2F128/VPERM2I128 permutations
9544   if (isVPERM2X128Mask(M, VT, HasFp256))
9545     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9546                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9547
9548   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9549     return getINSERTPS(SVOp, dl, DAG);
9550
9551   unsigned Imm8;
9552   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9553     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9554
9555   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9556       VT.is512BitVector()) {
9557     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9558     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9559     SmallVector<SDValue, 16> permclMask;
9560     for (unsigned i = 0; i != NumElems; ++i) {
9561       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9562     }
9563
9564     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9565     if (V2IsUndef)
9566       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9567       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9568                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9569     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9570                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9571   }
9572
9573   //===--------------------------------------------------------------------===//
9574   // Since no target specific shuffle was selected for this generic one,
9575   // lower it into other known shuffles. FIXME: this isn't true yet, but
9576   // this is the plan.
9577   //
9578
9579   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9580   if (VT == MVT::v8i16) {
9581     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9582     if (NewOp.getNode())
9583       return NewOp;
9584   }
9585
9586   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9587     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9588     if (NewOp.getNode())
9589       return NewOp;
9590   }
9591
9592   if (VT == MVT::v16i8) {
9593     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9594     if (NewOp.getNode())
9595       return NewOp;
9596   }
9597
9598   if (VT == MVT::v32i8) {
9599     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9600     if (NewOp.getNode())
9601       return NewOp;
9602   }
9603
9604   // Handle all 128-bit wide vectors with 4 elements, and match them with
9605   // several different shuffle types.
9606   if (NumElems == 4 && VT.is128BitVector())
9607     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9608
9609   // Handle general 256-bit shuffles
9610   if (VT.is256BitVector())
9611     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9612
9613   return SDValue();
9614 }
9615
9616 // This function assumes its argument is a BUILD_VECTOR of constants or
9617 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9618 // true.
9619 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9620                                     unsigned &MaskValue) {
9621   MaskValue = 0;
9622   unsigned NumElems = BuildVector->getNumOperands();
9623   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9624   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9625   unsigned NumElemsInLane = NumElems / NumLanes;
9626
9627   // Blend for v16i16 should be symetric for the both lanes.
9628   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9629     SDValue EltCond = BuildVector->getOperand(i);
9630     SDValue SndLaneEltCond =
9631         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9632
9633     int Lane1Cond = -1, Lane2Cond = -1;
9634     if (isa<ConstantSDNode>(EltCond))
9635       Lane1Cond = !isZero(EltCond);
9636     if (isa<ConstantSDNode>(SndLaneEltCond))
9637       Lane2Cond = !isZero(SndLaneEltCond);
9638
9639     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9640       // Lane1Cond != 0, means we want the first argument.
9641       // Lane1Cond == 0, means we want the second argument.
9642       // The encoding of this argument is 0 for the first argument, 1
9643       // for the second. Therefore, invert the condition.
9644       MaskValue |= !Lane1Cond << i;
9645     else if (Lane1Cond < 0)
9646       MaskValue |= !Lane2Cond << i;
9647     else
9648       return false;
9649   }
9650   return true;
9651 }
9652
9653 // Try to lower a vselect node into a simple blend instruction.
9654 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9655                                    SelectionDAG &DAG) {
9656   SDValue Cond = Op.getOperand(0);
9657   SDValue LHS = Op.getOperand(1);
9658   SDValue RHS = Op.getOperand(2);
9659   SDLoc dl(Op);
9660   MVT VT = Op.getSimpleValueType();
9661   MVT EltVT = VT.getVectorElementType();
9662   unsigned NumElems = VT.getVectorNumElements();
9663
9664   // There is no blend with immediate in AVX-512.
9665   if (VT.is512BitVector())
9666     return SDValue();
9667
9668   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9669     return SDValue();
9670   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9671     return SDValue();
9672
9673   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9674     return SDValue();
9675
9676   // Check the mask for BLEND and build the value.
9677   unsigned MaskValue = 0;
9678   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9679     return SDValue();
9680
9681   // Convert i32 vectors to floating point if it is not AVX2.
9682   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9683   MVT BlendVT = VT;
9684   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9685     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9686                                NumElems);
9687     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9688     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9689   }
9690
9691   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9692                             DAG.getConstant(MaskValue, MVT::i32));
9693   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9694 }
9695
9696 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9697   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9698   if (BlendOp.getNode())
9699     return BlendOp;
9700
9701   // Some types for vselect were previously set to Expand, not Legal or
9702   // Custom. Return an empty SDValue so we fall-through to Expand, after
9703   // the Custom lowering phase.
9704   MVT VT = Op.getSimpleValueType();
9705   switch (VT.SimpleTy) {
9706   default:
9707     break;
9708   case MVT::v8i16:
9709   case MVT::v16i16:
9710     return SDValue();
9711   }
9712
9713   // We couldn't create a "Blend with immediate" node.
9714   // This node should still be legal, but we'll have to emit a blendv*
9715   // instruction.
9716   return Op;
9717 }
9718
9719 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9720   MVT VT = Op.getSimpleValueType();
9721   SDLoc dl(Op);
9722
9723   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9724     return SDValue();
9725
9726   if (VT.getSizeInBits() == 8) {
9727     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9728                                   Op.getOperand(0), Op.getOperand(1));
9729     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9730                                   DAG.getValueType(VT));
9731     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9732   }
9733
9734   if (VT.getSizeInBits() == 16) {
9735     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9736     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9737     if (Idx == 0)
9738       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9739                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9740                                      DAG.getNode(ISD::BITCAST, dl,
9741                                                  MVT::v4i32,
9742                                                  Op.getOperand(0)),
9743                                      Op.getOperand(1)));
9744     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9745                                   Op.getOperand(0), Op.getOperand(1));
9746     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9747                                   DAG.getValueType(VT));
9748     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9749   }
9750
9751   if (VT == MVT::f32) {
9752     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9753     // the result back to FR32 register. It's only worth matching if the
9754     // result has a single use which is a store or a bitcast to i32.  And in
9755     // the case of a store, it's not worth it if the index is a constant 0,
9756     // because a MOVSSmr can be used instead, which is smaller and faster.
9757     if (!Op.hasOneUse())
9758       return SDValue();
9759     SDNode *User = *Op.getNode()->use_begin();
9760     if ((User->getOpcode() != ISD::STORE ||
9761          (isa<ConstantSDNode>(Op.getOperand(1)) &&
9762           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9763         (User->getOpcode() != ISD::BITCAST ||
9764          User->getValueType(0) != MVT::i32))
9765       return SDValue();
9766     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9767                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9768                                               Op.getOperand(0)),
9769                                               Op.getOperand(1));
9770     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9771   }
9772
9773   if (VT == MVT::i32 || VT == MVT::i64) {
9774     // ExtractPS/pextrq works with constant index.
9775     if (isa<ConstantSDNode>(Op.getOperand(1)))
9776       return Op;
9777   }
9778   return SDValue();
9779 }
9780
9781 /// Extract one bit from mask vector, like v16i1 or v8i1.
9782 /// AVX-512 feature.
9783 SDValue
9784 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9785   SDValue Vec = Op.getOperand(0);
9786   SDLoc dl(Vec);
9787   MVT VecVT = Vec.getSimpleValueType();
9788   SDValue Idx = Op.getOperand(1);
9789   MVT EltVT = Op.getSimpleValueType();
9790
9791   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9792
9793   // variable index can't be handled in mask registers,
9794   // extend vector to VR512
9795   if (!isa<ConstantSDNode>(Idx)) {
9796     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9797     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9798     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9799                               ExtVT.getVectorElementType(), Ext, Idx);
9800     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9801   }
9802
9803   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9804   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9805   unsigned MaxSift = rc->getSize()*8 - 1;
9806   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9807                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9808   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9809                     DAG.getConstant(MaxSift, MVT::i8));
9810   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9811                        DAG.getIntPtrConstant(0));
9812 }
9813
9814 SDValue
9815 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9816                                            SelectionDAG &DAG) const {
9817   SDLoc dl(Op);
9818   SDValue Vec = Op.getOperand(0);
9819   MVT VecVT = Vec.getSimpleValueType();
9820   SDValue Idx = Op.getOperand(1);
9821
9822   if (Op.getSimpleValueType() == MVT::i1)
9823     return ExtractBitFromMaskVector(Op, DAG);
9824
9825   if (!isa<ConstantSDNode>(Idx)) {
9826     if (VecVT.is512BitVector() ||
9827         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9828          VecVT.getVectorElementType().getSizeInBits() == 32)) {
9829
9830       MVT MaskEltVT =
9831         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9832       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9833                                     MaskEltVT.getSizeInBits());
9834
9835       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9836       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9837                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
9838                                 Idx, DAG.getConstant(0, getPointerTy()));
9839       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9840       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9841                         Perm, DAG.getConstant(0, getPointerTy()));
9842     }
9843     return SDValue();
9844   }
9845
9846   // If this is a 256-bit vector result, first extract the 128-bit vector and
9847   // then extract the element from the 128-bit vector.
9848   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9849
9850     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9851     // Get the 128-bit vector.
9852     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9853     MVT EltVT = VecVT.getVectorElementType();
9854
9855     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9856
9857     //if (IdxVal >= NumElems/2)
9858     //  IdxVal -= NumElems/2;
9859     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9860     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9861                        DAG.getConstant(IdxVal, MVT::i32));
9862   }
9863
9864   assert(VecVT.is128BitVector() && "Unexpected vector length");
9865
9866   if (Subtarget->hasSSE41()) {
9867     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9868     if (Res.getNode())
9869       return Res;
9870   }
9871
9872   MVT VT = Op.getSimpleValueType();
9873   // TODO: handle v16i8.
9874   if (VT.getSizeInBits() == 16) {
9875     SDValue Vec = Op.getOperand(0);
9876     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9877     if (Idx == 0)
9878       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9879                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9880                                      DAG.getNode(ISD::BITCAST, dl,
9881                                                  MVT::v4i32, Vec),
9882                                      Op.getOperand(1)));
9883     // Transform it so it match pextrw which produces a 32-bit result.
9884     MVT EltVT = MVT::i32;
9885     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9886                                   Op.getOperand(0), Op.getOperand(1));
9887     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9888                                   DAG.getValueType(VT));
9889     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9890   }
9891
9892   if (VT.getSizeInBits() == 32) {
9893     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9894     if (Idx == 0)
9895       return Op;
9896
9897     // SHUFPS the element to the lowest double word, then movss.
9898     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9899     MVT VVT = Op.getOperand(0).getSimpleValueType();
9900     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9901                                        DAG.getUNDEF(VVT), Mask);
9902     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9903                        DAG.getIntPtrConstant(0));
9904   }
9905
9906   if (VT.getSizeInBits() == 64) {
9907     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9908     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9909     //        to match extract_elt for f64.
9910     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9911     if (Idx == 0)
9912       return Op;
9913
9914     // UNPCKHPD the element to the lowest double word, then movsd.
9915     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9916     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9917     int Mask[2] = { 1, -1 };
9918     MVT VVT = Op.getOperand(0).getSimpleValueType();
9919     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9920                                        DAG.getUNDEF(VVT), Mask);
9921     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9922                        DAG.getIntPtrConstant(0));
9923   }
9924
9925   return SDValue();
9926 }
9927
9928 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9929   MVT VT = Op.getSimpleValueType();
9930   MVT EltVT = VT.getVectorElementType();
9931   SDLoc dl(Op);
9932
9933   SDValue N0 = Op.getOperand(0);
9934   SDValue N1 = Op.getOperand(1);
9935   SDValue N2 = Op.getOperand(2);
9936
9937   if (!VT.is128BitVector())
9938     return SDValue();
9939
9940   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9941       isa<ConstantSDNode>(N2)) {
9942     unsigned Opc;
9943     if (VT == MVT::v8i16)
9944       Opc = X86ISD::PINSRW;
9945     else if (VT == MVT::v16i8)
9946       Opc = X86ISD::PINSRB;
9947     else
9948       Opc = X86ISD::PINSRB;
9949
9950     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9951     // argument.
9952     if (N1.getValueType() != MVT::i32)
9953       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9954     if (N2.getValueType() != MVT::i32)
9955       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9956     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9957   }
9958
9959   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9960     // Bits [7:6] of the constant are the source select.  This will always be
9961     //  zero here.  The DAG Combiner may combine an extract_elt index into these
9962     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
9963     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
9964     // Bits [5:4] of the constant are the destination select.  This is the
9965     //  value of the incoming immediate.
9966     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
9967     //   combine either bitwise AND or insert of float 0.0 to set these bits.
9968     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9969     // Create this as a scalar to vector..
9970     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9971     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9972   }
9973
9974   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9975     // PINSR* works with constant index.
9976     return Op;
9977   }
9978   return SDValue();
9979 }
9980
9981 /// Insert one bit to mask vector, like v16i1 or v8i1.
9982 /// AVX-512 feature.
9983 SDValue 
9984 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9985   SDLoc dl(Op);
9986   SDValue Vec = Op.getOperand(0);
9987   SDValue Elt = Op.getOperand(1);
9988   SDValue Idx = Op.getOperand(2);
9989   MVT VecVT = Vec.getSimpleValueType();
9990
9991   if (!isa<ConstantSDNode>(Idx)) {
9992     // Non constant index. Extend source and destination,
9993     // insert element and then truncate the result.
9994     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9995     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
9996     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
9997       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9998       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9999     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10000   }
10001
10002   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10003   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10004   if (Vec.getOpcode() == ISD::UNDEF)
10005     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10006                        DAG.getConstant(IdxVal, MVT::i8));
10007   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10008   unsigned MaxSift = rc->getSize()*8 - 1;
10009   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10010                     DAG.getConstant(MaxSift, MVT::i8));
10011   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10012                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10013   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10014 }
10015 SDValue
10016 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10017   MVT VT = Op.getSimpleValueType();
10018   MVT EltVT = VT.getVectorElementType();
10019   
10020   if (EltVT == MVT::i1)
10021     return InsertBitToMaskVector(Op, DAG);
10022
10023   SDLoc dl(Op);
10024   SDValue N0 = Op.getOperand(0);
10025   SDValue N1 = Op.getOperand(1);
10026   SDValue N2 = Op.getOperand(2);
10027
10028   // If this is a 256-bit vector result, first extract the 128-bit vector,
10029   // insert the element into the extracted half and then place it back.
10030   if (VT.is256BitVector() || VT.is512BitVector()) {
10031     if (!isa<ConstantSDNode>(N2))
10032       return SDValue();
10033
10034     // Get the desired 128-bit vector half.
10035     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10036     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10037
10038     // Insert the element into the desired half.
10039     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10040     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10041
10042     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10043                     DAG.getConstant(IdxIn128, MVT::i32));
10044
10045     // Insert the changed part back to the 256-bit vector
10046     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10047   }
10048
10049   if (Subtarget->hasSSE41())
10050     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10051
10052   if (EltVT == MVT::i8)
10053     return SDValue();
10054
10055   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10056     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10057     // as its second argument.
10058     if (N1.getValueType() != MVT::i32)
10059       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10060     if (N2.getValueType() != MVT::i32)
10061       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10062     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10063   }
10064   return SDValue();
10065 }
10066
10067 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10068   SDLoc dl(Op);
10069   MVT OpVT = Op.getSimpleValueType();
10070
10071   // If this is a 256-bit vector result, first insert into a 128-bit
10072   // vector and then insert into the 256-bit vector.
10073   if (!OpVT.is128BitVector()) {
10074     // Insert into a 128-bit vector.
10075     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10076     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10077                                  OpVT.getVectorNumElements() / SizeFactor);
10078
10079     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10080
10081     // Insert the 128-bit vector.
10082     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10083   }
10084
10085   if (OpVT == MVT::v1i64 &&
10086       Op.getOperand(0).getValueType() == MVT::i64)
10087     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10088
10089   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10090   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10091   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10092                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10093 }
10094
10095 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10096 // a simple subregister reference or explicit instructions to grab
10097 // upper bits of a vector.
10098 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10099                                       SelectionDAG &DAG) {
10100   SDLoc dl(Op);
10101   SDValue In =  Op.getOperand(0);
10102   SDValue Idx = Op.getOperand(1);
10103   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10104   MVT ResVT   = Op.getSimpleValueType();
10105   MVT InVT    = In.getSimpleValueType();
10106
10107   if (Subtarget->hasFp256()) {
10108     if (ResVT.is128BitVector() &&
10109         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10110         isa<ConstantSDNode>(Idx)) {
10111       return Extract128BitVector(In, IdxVal, DAG, dl);
10112     }
10113     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10114         isa<ConstantSDNode>(Idx)) {
10115       return Extract256BitVector(In, IdxVal, DAG, dl);
10116     }
10117   }
10118   return SDValue();
10119 }
10120
10121 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10122 // simple superregister reference or explicit instructions to insert
10123 // the upper bits of a vector.
10124 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10125                                      SelectionDAG &DAG) {
10126   if (Subtarget->hasFp256()) {
10127     SDLoc dl(Op.getNode());
10128     SDValue Vec = Op.getNode()->getOperand(0);
10129     SDValue SubVec = Op.getNode()->getOperand(1);
10130     SDValue Idx = Op.getNode()->getOperand(2);
10131
10132     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10133          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10134         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10135         isa<ConstantSDNode>(Idx)) {
10136       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10137       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10138     }
10139
10140     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10141         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10142         isa<ConstantSDNode>(Idx)) {
10143       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10144       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10145     }
10146   }
10147   return SDValue();
10148 }
10149
10150 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10151 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10152 // one of the above mentioned nodes. It has to be wrapped because otherwise
10153 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10154 // be used to form addressing mode. These wrapped nodes will be selected
10155 // into MOV32ri.
10156 SDValue
10157 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10158   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10159
10160   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10161   // global base reg.
10162   unsigned char OpFlag = 0;
10163   unsigned WrapperKind = X86ISD::Wrapper;
10164   CodeModel::Model M = DAG.getTarget().getCodeModel();
10165
10166   if (Subtarget->isPICStyleRIPRel() &&
10167       (M == CodeModel::Small || M == CodeModel::Kernel))
10168     WrapperKind = X86ISD::WrapperRIP;
10169   else if (Subtarget->isPICStyleGOT())
10170     OpFlag = X86II::MO_GOTOFF;
10171   else if (Subtarget->isPICStyleStubPIC())
10172     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10173
10174   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10175                                              CP->getAlignment(),
10176                                              CP->getOffset(), OpFlag);
10177   SDLoc DL(CP);
10178   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10179   // With PIC, the address is actually $g + Offset.
10180   if (OpFlag) {
10181     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10182                          DAG.getNode(X86ISD::GlobalBaseReg,
10183                                      SDLoc(), getPointerTy()),
10184                          Result);
10185   }
10186
10187   return Result;
10188 }
10189
10190 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10191   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10192
10193   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10194   // global base reg.
10195   unsigned char OpFlag = 0;
10196   unsigned WrapperKind = X86ISD::Wrapper;
10197   CodeModel::Model M = DAG.getTarget().getCodeModel();
10198
10199   if (Subtarget->isPICStyleRIPRel() &&
10200       (M == CodeModel::Small || M == CodeModel::Kernel))
10201     WrapperKind = X86ISD::WrapperRIP;
10202   else if (Subtarget->isPICStyleGOT())
10203     OpFlag = X86II::MO_GOTOFF;
10204   else if (Subtarget->isPICStyleStubPIC())
10205     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10206
10207   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10208                                           OpFlag);
10209   SDLoc DL(JT);
10210   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10211
10212   // With PIC, the address is actually $g + Offset.
10213   if (OpFlag)
10214     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10215                          DAG.getNode(X86ISD::GlobalBaseReg,
10216                                      SDLoc(), getPointerTy()),
10217                          Result);
10218
10219   return Result;
10220 }
10221
10222 SDValue
10223 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10224   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10225
10226   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10227   // global base reg.
10228   unsigned char OpFlag = 0;
10229   unsigned WrapperKind = X86ISD::Wrapper;
10230   CodeModel::Model M = DAG.getTarget().getCodeModel();
10231
10232   if (Subtarget->isPICStyleRIPRel() &&
10233       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10234     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10235       OpFlag = X86II::MO_GOTPCREL;
10236     WrapperKind = X86ISD::WrapperRIP;
10237   } else if (Subtarget->isPICStyleGOT()) {
10238     OpFlag = X86II::MO_GOT;
10239   } else if (Subtarget->isPICStyleStubPIC()) {
10240     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10241   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10242     OpFlag = X86II::MO_DARWIN_NONLAZY;
10243   }
10244
10245   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10246
10247   SDLoc DL(Op);
10248   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10249
10250   // With PIC, the address is actually $g + Offset.
10251   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10252       !Subtarget->is64Bit()) {
10253     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10254                          DAG.getNode(X86ISD::GlobalBaseReg,
10255                                      SDLoc(), getPointerTy()),
10256                          Result);
10257   }
10258
10259   // For symbols that require a load from a stub to get the address, emit the
10260   // load.
10261   if (isGlobalStubReference(OpFlag))
10262     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10263                          MachinePointerInfo::getGOT(), false, false, false, 0);
10264
10265   return Result;
10266 }
10267
10268 SDValue
10269 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10270   // Create the TargetBlockAddressAddress node.
10271   unsigned char OpFlags =
10272     Subtarget->ClassifyBlockAddressReference();
10273   CodeModel::Model M = DAG.getTarget().getCodeModel();
10274   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10275   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10276   SDLoc dl(Op);
10277   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10278                                              OpFlags);
10279
10280   if (Subtarget->isPICStyleRIPRel() &&
10281       (M == CodeModel::Small || M == CodeModel::Kernel))
10282     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10283   else
10284     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10285
10286   // With PIC, the address is actually $g + Offset.
10287   if (isGlobalRelativeToPICBase(OpFlags)) {
10288     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10289                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10290                          Result);
10291   }
10292
10293   return Result;
10294 }
10295
10296 SDValue
10297 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10298                                       int64_t Offset, SelectionDAG &DAG) const {
10299   // Create the TargetGlobalAddress node, folding in the constant
10300   // offset if it is legal.
10301   unsigned char OpFlags =
10302       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10303   CodeModel::Model M = DAG.getTarget().getCodeModel();
10304   SDValue Result;
10305   if (OpFlags == X86II::MO_NO_FLAG &&
10306       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10307     // A direct static reference to a global.
10308     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10309     Offset = 0;
10310   } else {
10311     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10312   }
10313
10314   if (Subtarget->isPICStyleRIPRel() &&
10315       (M == CodeModel::Small || M == CodeModel::Kernel))
10316     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10317   else
10318     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10319
10320   // With PIC, the address is actually $g + Offset.
10321   if (isGlobalRelativeToPICBase(OpFlags)) {
10322     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10323                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10324                          Result);
10325   }
10326
10327   // For globals that require a load from a stub to get the address, emit the
10328   // load.
10329   if (isGlobalStubReference(OpFlags))
10330     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10331                          MachinePointerInfo::getGOT(), false, false, false, 0);
10332
10333   // If there was a non-zero offset that we didn't fold, create an explicit
10334   // addition for it.
10335   if (Offset != 0)
10336     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10337                          DAG.getConstant(Offset, getPointerTy()));
10338
10339   return Result;
10340 }
10341
10342 SDValue
10343 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10344   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10345   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10346   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10347 }
10348
10349 static SDValue
10350 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10351            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10352            unsigned char OperandFlags, bool LocalDynamic = false) {
10353   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10354   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10355   SDLoc dl(GA);
10356   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10357                                            GA->getValueType(0),
10358                                            GA->getOffset(),
10359                                            OperandFlags);
10360
10361   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10362                                            : X86ISD::TLSADDR;
10363
10364   if (InFlag) {
10365     SDValue Ops[] = { Chain,  TGA, *InFlag };
10366     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10367   } else {
10368     SDValue Ops[]  = { Chain, TGA };
10369     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10370   }
10371
10372   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10373   MFI->setAdjustsStack(true);
10374
10375   SDValue Flag = Chain.getValue(1);
10376   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10377 }
10378
10379 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10380 static SDValue
10381 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10382                                 const EVT PtrVT) {
10383   SDValue InFlag;
10384   SDLoc dl(GA);  // ? function entry point might be better
10385   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10386                                    DAG.getNode(X86ISD::GlobalBaseReg,
10387                                                SDLoc(), PtrVT), InFlag);
10388   InFlag = Chain.getValue(1);
10389
10390   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10391 }
10392
10393 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10394 static SDValue
10395 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10396                                 const EVT PtrVT) {
10397   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10398                     X86::RAX, X86II::MO_TLSGD);
10399 }
10400
10401 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10402                                            SelectionDAG &DAG,
10403                                            const EVT PtrVT,
10404                                            bool is64Bit) {
10405   SDLoc dl(GA);
10406
10407   // Get the start address of the TLS block for this module.
10408   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10409       .getInfo<X86MachineFunctionInfo>();
10410   MFI->incNumLocalDynamicTLSAccesses();
10411
10412   SDValue Base;
10413   if (is64Bit) {
10414     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10415                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10416   } else {
10417     SDValue InFlag;
10418     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10419         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10420     InFlag = Chain.getValue(1);
10421     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10422                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10423   }
10424
10425   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10426   // of Base.
10427
10428   // Build x@dtpoff.
10429   unsigned char OperandFlags = X86II::MO_DTPOFF;
10430   unsigned WrapperKind = X86ISD::Wrapper;
10431   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10432                                            GA->getValueType(0),
10433                                            GA->getOffset(), OperandFlags);
10434   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10435
10436   // Add x@dtpoff with the base.
10437   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10438 }
10439
10440 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10441 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10442                                    const EVT PtrVT, TLSModel::Model model,
10443                                    bool is64Bit, bool isPIC) {
10444   SDLoc dl(GA);
10445
10446   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10447   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10448                                                          is64Bit ? 257 : 256));
10449
10450   SDValue ThreadPointer =
10451       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10452                   MachinePointerInfo(Ptr), false, false, false, 0);
10453
10454   unsigned char OperandFlags = 0;
10455   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10456   // initialexec.
10457   unsigned WrapperKind = X86ISD::Wrapper;
10458   if (model == TLSModel::LocalExec) {
10459     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10460   } else if (model == TLSModel::InitialExec) {
10461     if (is64Bit) {
10462       OperandFlags = X86II::MO_GOTTPOFF;
10463       WrapperKind = X86ISD::WrapperRIP;
10464     } else {
10465       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10466     }
10467   } else {
10468     llvm_unreachable("Unexpected model");
10469   }
10470
10471   // emit "addl x@ntpoff,%eax" (local exec)
10472   // or "addl x@indntpoff,%eax" (initial exec)
10473   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10474   SDValue TGA =
10475       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10476                                  GA->getOffset(), OperandFlags);
10477   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10478
10479   if (model == TLSModel::InitialExec) {
10480     if (isPIC && !is64Bit) {
10481       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10482                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10483                            Offset);
10484     }
10485
10486     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10487                          MachinePointerInfo::getGOT(), false, false, false, 0);
10488   }
10489
10490   // The address of the thread local variable is the add of the thread
10491   // pointer with the offset of the variable.
10492   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10493 }
10494
10495 SDValue
10496 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10497
10498   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10499   const GlobalValue *GV = GA->getGlobal();
10500
10501   if (Subtarget->isTargetELF()) {
10502     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10503
10504     switch (model) {
10505       case TLSModel::GeneralDynamic:
10506         if (Subtarget->is64Bit())
10507           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10508         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10509       case TLSModel::LocalDynamic:
10510         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10511                                            Subtarget->is64Bit());
10512       case TLSModel::InitialExec:
10513       case TLSModel::LocalExec:
10514         return LowerToTLSExecModel(
10515             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10516             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10517     }
10518     llvm_unreachable("Unknown TLS model.");
10519   }
10520
10521   if (Subtarget->isTargetDarwin()) {
10522     // Darwin only has one model of TLS.  Lower to that.
10523     unsigned char OpFlag = 0;
10524     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10525                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10526
10527     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10528     // global base reg.
10529     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10530                  !Subtarget->is64Bit();
10531     if (PIC32)
10532       OpFlag = X86II::MO_TLVP_PIC_BASE;
10533     else
10534       OpFlag = X86II::MO_TLVP;
10535     SDLoc DL(Op);
10536     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10537                                                 GA->getValueType(0),
10538                                                 GA->getOffset(), OpFlag);
10539     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10540
10541     // With PIC32, the address is actually $g + Offset.
10542     if (PIC32)
10543       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10544                            DAG.getNode(X86ISD::GlobalBaseReg,
10545                                        SDLoc(), getPointerTy()),
10546                            Offset);
10547
10548     // Lowering the machine isd will make sure everything is in the right
10549     // location.
10550     SDValue Chain = DAG.getEntryNode();
10551     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10552     SDValue Args[] = { Chain, Offset };
10553     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10554
10555     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10556     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10557     MFI->setAdjustsStack(true);
10558
10559     // And our return value (tls address) is in the standard call return value
10560     // location.
10561     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10562     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10563                               Chain.getValue(1));
10564   }
10565
10566   if (Subtarget->isTargetKnownWindowsMSVC() ||
10567       Subtarget->isTargetWindowsGNU()) {
10568     // Just use the implicit TLS architecture
10569     // Need to generate someting similar to:
10570     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10571     //                                  ; from TEB
10572     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10573     //   mov     rcx, qword [rdx+rcx*8]
10574     //   mov     eax, .tls$:tlsvar
10575     //   [rax+rcx] contains the address
10576     // Windows 64bit: gs:0x58
10577     // Windows 32bit: fs:__tls_array
10578
10579     SDLoc dl(GA);
10580     SDValue Chain = DAG.getEntryNode();
10581
10582     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10583     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10584     // use its literal value of 0x2C.
10585     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10586                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10587                                                              256)
10588                                         : Type::getInt32PtrTy(*DAG.getContext(),
10589                                                               257));
10590
10591     SDValue TlsArray =
10592         Subtarget->is64Bit()
10593             ? DAG.getIntPtrConstant(0x58)
10594             : (Subtarget->isTargetWindowsGNU()
10595                    ? DAG.getIntPtrConstant(0x2C)
10596                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10597
10598     SDValue ThreadPointer =
10599         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10600                     MachinePointerInfo(Ptr), false, false, false, 0);
10601
10602     // Load the _tls_index variable
10603     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10604     if (Subtarget->is64Bit())
10605       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10606                            IDX, MachinePointerInfo(), MVT::i32,
10607                            false, false, 0);
10608     else
10609       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10610                         false, false, false, 0);
10611
10612     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10613                                     getPointerTy());
10614     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10615
10616     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10617     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10618                       false, false, false, 0);
10619
10620     // Get the offset of start of .tls section
10621     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10622                                              GA->getValueType(0),
10623                                              GA->getOffset(), X86II::MO_SECREL);
10624     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10625
10626     // The address of the thread local variable is the add of the thread
10627     // pointer with the offset of the variable.
10628     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10629   }
10630
10631   llvm_unreachable("TLS not implemented for this target.");
10632 }
10633
10634 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10635 /// and take a 2 x i32 value to shift plus a shift amount.
10636 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10637   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10638   MVT VT = Op.getSimpleValueType();
10639   unsigned VTBits = VT.getSizeInBits();
10640   SDLoc dl(Op);
10641   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10642   SDValue ShOpLo = Op.getOperand(0);
10643   SDValue ShOpHi = Op.getOperand(1);
10644   SDValue ShAmt  = Op.getOperand(2);
10645   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10646   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10647   // during isel.
10648   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10649                                   DAG.getConstant(VTBits - 1, MVT::i8));
10650   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10651                                      DAG.getConstant(VTBits - 1, MVT::i8))
10652                        : DAG.getConstant(0, VT);
10653
10654   SDValue Tmp2, Tmp3;
10655   if (Op.getOpcode() == ISD::SHL_PARTS) {
10656     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10657     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10658   } else {
10659     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10660     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10661   }
10662
10663   // If the shift amount is larger or equal than the width of a part we can't
10664   // rely on the results of shld/shrd. Insert a test and select the appropriate
10665   // values for large shift amounts.
10666   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10667                                 DAG.getConstant(VTBits, MVT::i8));
10668   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10669                              AndNode, DAG.getConstant(0, MVT::i8));
10670
10671   SDValue Hi, Lo;
10672   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10673   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10674   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10675
10676   if (Op.getOpcode() == ISD::SHL_PARTS) {
10677     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10678     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10679   } else {
10680     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10681     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10682   }
10683
10684   SDValue Ops[2] = { Lo, Hi };
10685   return DAG.getMergeValues(Ops, dl);
10686 }
10687
10688 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10689                                            SelectionDAG &DAG) const {
10690   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10691
10692   if (SrcVT.isVector())
10693     return SDValue();
10694
10695   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10696          "Unknown SINT_TO_FP to lower!");
10697
10698   // These are really Legal; return the operand so the caller accepts it as
10699   // Legal.
10700   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10701     return Op;
10702   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10703       Subtarget->is64Bit()) {
10704     return Op;
10705   }
10706
10707   SDLoc dl(Op);
10708   unsigned Size = SrcVT.getSizeInBits()/8;
10709   MachineFunction &MF = DAG.getMachineFunction();
10710   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10711   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10712   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10713                                StackSlot,
10714                                MachinePointerInfo::getFixedStack(SSFI),
10715                                false, false, 0);
10716   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10717 }
10718
10719 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10720                                      SDValue StackSlot,
10721                                      SelectionDAG &DAG) const {
10722   // Build the FILD
10723   SDLoc DL(Op);
10724   SDVTList Tys;
10725   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10726   if (useSSE)
10727     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10728   else
10729     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10730
10731   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10732
10733   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10734   MachineMemOperand *MMO;
10735   if (FI) {
10736     int SSFI = FI->getIndex();
10737     MMO =
10738       DAG.getMachineFunction()
10739       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10740                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10741   } else {
10742     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10743     StackSlot = StackSlot.getOperand(1);
10744   }
10745   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10746   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10747                                            X86ISD::FILD, DL,
10748                                            Tys, Ops, SrcVT, MMO);
10749
10750   if (useSSE) {
10751     Chain = Result.getValue(1);
10752     SDValue InFlag = Result.getValue(2);
10753
10754     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10755     // shouldn't be necessary except that RFP cannot be live across
10756     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10757     MachineFunction &MF = DAG.getMachineFunction();
10758     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10759     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10760     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10761     Tys = DAG.getVTList(MVT::Other);
10762     SDValue Ops[] = {
10763       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10764     };
10765     MachineMemOperand *MMO =
10766       DAG.getMachineFunction()
10767       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10768                             MachineMemOperand::MOStore, SSFISize, SSFISize);
10769
10770     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10771                                     Ops, Op.getValueType(), MMO);
10772     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10773                          MachinePointerInfo::getFixedStack(SSFI),
10774                          false, false, false, 0);
10775   }
10776
10777   return Result;
10778 }
10779
10780 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10781 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10782                                                SelectionDAG &DAG) const {
10783   // This algorithm is not obvious. Here it is what we're trying to output:
10784   /*
10785      movq       %rax,  %xmm0
10786      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10787      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10788      #ifdef __SSE3__
10789        haddpd   %xmm0, %xmm0
10790      #else
10791        pshufd   $0x4e, %xmm0, %xmm1
10792        addpd    %xmm1, %xmm0
10793      #endif
10794   */
10795
10796   SDLoc dl(Op);
10797   LLVMContext *Context = DAG.getContext();
10798
10799   // Build some magic constants.
10800   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10801   Constant *C0 = ConstantDataVector::get(*Context, CV0);
10802   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10803
10804   SmallVector<Constant*,2> CV1;
10805   CV1.push_back(
10806     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10807                                       APInt(64, 0x4330000000000000ULL))));
10808   CV1.push_back(
10809     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10810                                       APInt(64, 0x4530000000000000ULL))));
10811   Constant *C1 = ConstantVector::get(CV1);
10812   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10813
10814   // Load the 64-bit value into an XMM register.
10815   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10816                             Op.getOperand(0));
10817   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10818                               MachinePointerInfo::getConstantPool(),
10819                               false, false, false, 16);
10820   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10821                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10822                               CLod0);
10823
10824   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10825                               MachinePointerInfo::getConstantPool(),
10826                               false, false, false, 16);
10827   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10828   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10829   SDValue Result;
10830
10831   if (Subtarget->hasSSE3()) {
10832     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10833     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10834   } else {
10835     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10836     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10837                                            S2F, 0x4E, DAG);
10838     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10839                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10840                          Sub);
10841   }
10842
10843   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10844                      DAG.getIntPtrConstant(0));
10845 }
10846
10847 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10848 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10849                                                SelectionDAG &DAG) const {
10850   SDLoc dl(Op);
10851   // FP constant to bias correct the final result.
10852   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10853                                    MVT::f64);
10854
10855   // Load the 32-bit value into an XMM register.
10856   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10857                              Op.getOperand(0));
10858
10859   // Zero out the upper parts of the register.
10860   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10861
10862   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10863                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10864                      DAG.getIntPtrConstant(0));
10865
10866   // Or the load with the bias.
10867   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10868                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10869                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10870                                                    MVT::v2f64, Load)),
10871                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10872                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10873                                                    MVT::v2f64, Bias)));
10874   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10875                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10876                    DAG.getIntPtrConstant(0));
10877
10878   // Subtract the bias.
10879   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10880
10881   // Handle final rounding.
10882   EVT DestVT = Op.getValueType();
10883
10884   if (DestVT.bitsLT(MVT::f64))
10885     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10886                        DAG.getIntPtrConstant(0));
10887   if (DestVT.bitsGT(MVT::f64))
10888     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10889
10890   // Handle final rounding.
10891   return Sub;
10892 }
10893
10894 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10895                                                SelectionDAG &DAG) const {
10896   SDValue N0 = Op.getOperand(0);
10897   MVT SVT = N0.getSimpleValueType();
10898   SDLoc dl(Op);
10899
10900   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10901           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10902          "Custom UINT_TO_FP is not supported!");
10903
10904   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10905   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10906                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10907 }
10908
10909 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10910                                            SelectionDAG &DAG) const {
10911   SDValue N0 = Op.getOperand(0);
10912   SDLoc dl(Op);
10913
10914   if (Op.getValueType().isVector())
10915     return lowerUINT_TO_FP_vec(Op, DAG);
10916
10917   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10918   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10919   // the optimization here.
10920   if (DAG.SignBitIsZero(N0))
10921     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10922
10923   MVT SrcVT = N0.getSimpleValueType();
10924   MVT DstVT = Op.getSimpleValueType();
10925   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10926     return LowerUINT_TO_FP_i64(Op, DAG);
10927   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10928     return LowerUINT_TO_FP_i32(Op, DAG);
10929   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10930     return SDValue();
10931
10932   // Make a 64-bit buffer, and use it to build an FILD.
10933   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10934   if (SrcVT == MVT::i32) {
10935     SDValue WordOff = DAG.getConstant(4, getPointerTy());
10936     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10937                                      getPointerTy(), StackSlot, WordOff);
10938     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10939                                   StackSlot, MachinePointerInfo(),
10940                                   false, false, 0);
10941     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10942                                   OffsetSlot, MachinePointerInfo(),
10943                                   false, false, 0);
10944     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10945     return Fild;
10946   }
10947
10948   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10949   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10950                                StackSlot, MachinePointerInfo(),
10951                                false, false, 0);
10952   // For i64 source, we need to add the appropriate power of 2 if the input
10953   // was negative.  This is the same as the optimization in
10954   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10955   // we must be careful to do the computation in x87 extended precision, not
10956   // in SSE. (The generic code can't know it's OK to do this, or how to.)
10957   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10958   MachineMemOperand *MMO =
10959     DAG.getMachineFunction()
10960     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10961                           MachineMemOperand::MOLoad, 8, 8);
10962
10963   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10964   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10965   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10966                                          MVT::i64, MMO);
10967
10968   APInt FF(32, 0x5F800000ULL);
10969
10970   // Check whether the sign bit is set.
10971   SDValue SignSet = DAG.getSetCC(dl,
10972                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
10973                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10974                                  ISD::SETLT);
10975
10976   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10977   SDValue FudgePtr = DAG.getConstantPool(
10978                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10979                                          getPointerTy());
10980
10981   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10982   SDValue Zero = DAG.getIntPtrConstant(0);
10983   SDValue Four = DAG.getIntPtrConstant(4);
10984   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10985                                Zero, Four);
10986   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10987
10988   // Load the value out, extending it from f32 to f80.
10989   // FIXME: Avoid the extend by constructing the right constant pool?
10990   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10991                                  FudgePtr, MachinePointerInfo::getConstantPool(),
10992                                  MVT::f32, false, false, 4);
10993   // Extend everything to 80 bits to force it to be done on x87.
10994   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10995   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10996 }
10997
10998 std::pair<SDValue,SDValue>
10999 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11000                                     bool IsSigned, bool IsReplace) const {
11001   SDLoc DL(Op);
11002
11003   EVT DstTy = Op.getValueType();
11004
11005   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11006     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11007     DstTy = MVT::i64;
11008   }
11009
11010   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11011          DstTy.getSimpleVT() >= MVT::i16 &&
11012          "Unknown FP_TO_INT to lower!");
11013
11014   // These are really Legal.
11015   if (DstTy == MVT::i32 &&
11016       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11017     return std::make_pair(SDValue(), SDValue());
11018   if (Subtarget->is64Bit() &&
11019       DstTy == MVT::i64 &&
11020       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11021     return std::make_pair(SDValue(), SDValue());
11022
11023   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11024   // stack slot, or into the FTOL runtime function.
11025   MachineFunction &MF = DAG.getMachineFunction();
11026   unsigned MemSize = DstTy.getSizeInBits()/8;
11027   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11028   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11029
11030   unsigned Opc;
11031   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11032     Opc = X86ISD::WIN_FTOL;
11033   else
11034     switch (DstTy.getSimpleVT().SimpleTy) {
11035     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11036     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11037     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11038     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11039     }
11040
11041   SDValue Chain = DAG.getEntryNode();
11042   SDValue Value = Op.getOperand(0);
11043   EVT TheVT = Op.getOperand(0).getValueType();
11044   // FIXME This causes a redundant load/store if the SSE-class value is already
11045   // in memory, such as if it is on the callstack.
11046   if (isScalarFPTypeInSSEReg(TheVT)) {
11047     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11048     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11049                          MachinePointerInfo::getFixedStack(SSFI),
11050                          false, false, 0);
11051     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11052     SDValue Ops[] = {
11053       Chain, StackSlot, DAG.getValueType(TheVT)
11054     };
11055
11056     MachineMemOperand *MMO =
11057       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11058                               MachineMemOperand::MOLoad, MemSize, MemSize);
11059     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11060     Chain = Value.getValue(1);
11061     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11062     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11063   }
11064
11065   MachineMemOperand *MMO =
11066     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11067                             MachineMemOperand::MOStore, MemSize, MemSize);
11068
11069   if (Opc != X86ISD::WIN_FTOL) {
11070     // Build the FP_TO_INT*_IN_MEM
11071     SDValue Ops[] = { Chain, Value, StackSlot };
11072     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11073                                            Ops, DstTy, MMO);
11074     return std::make_pair(FIST, StackSlot);
11075   } else {
11076     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11077       DAG.getVTList(MVT::Other, MVT::Glue),
11078       Chain, Value);
11079     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11080       MVT::i32, ftol.getValue(1));
11081     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11082       MVT::i32, eax.getValue(2));
11083     SDValue Ops[] = { eax, edx };
11084     SDValue pair = IsReplace
11085       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11086       : DAG.getMergeValues(Ops, DL);
11087     return std::make_pair(pair, SDValue());
11088   }
11089 }
11090
11091 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11092                               const X86Subtarget *Subtarget) {
11093   MVT VT = Op->getSimpleValueType(0);
11094   SDValue In = Op->getOperand(0);
11095   MVT InVT = In.getSimpleValueType();
11096   SDLoc dl(Op);
11097
11098   // Optimize vectors in AVX mode:
11099   //
11100   //   v8i16 -> v8i32
11101   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11102   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11103   //   Concat upper and lower parts.
11104   //
11105   //   v4i32 -> v4i64
11106   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11107   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11108   //   Concat upper and lower parts.
11109   //
11110
11111   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11112       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11113       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11114     return SDValue();
11115
11116   if (Subtarget->hasInt256())
11117     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11118
11119   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11120   SDValue Undef = DAG.getUNDEF(InVT);
11121   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11122   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11123   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11124
11125   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11126                              VT.getVectorNumElements()/2);
11127
11128   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11129   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11130
11131   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11132 }
11133
11134 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11135                                         SelectionDAG &DAG) {
11136   MVT VT = Op->getSimpleValueType(0);
11137   SDValue In = Op->getOperand(0);
11138   MVT InVT = In.getSimpleValueType();
11139   SDLoc DL(Op);
11140   unsigned int NumElts = VT.getVectorNumElements();
11141   if (NumElts != 8 && NumElts != 16)
11142     return SDValue();
11143
11144   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11145     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11146
11147   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11148   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11149   // Now we have only mask extension
11150   assert(InVT.getVectorElementType() == MVT::i1);
11151   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11152   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11153   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11154   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11155   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11156                            MachinePointerInfo::getConstantPool(),
11157                            false, false, false, Alignment);
11158
11159   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11160   if (VT.is512BitVector())
11161     return Brcst;
11162   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11163 }
11164
11165 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11166                                SelectionDAG &DAG) {
11167   if (Subtarget->hasFp256()) {
11168     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11169     if (Res.getNode())
11170       return Res;
11171   }
11172
11173   return SDValue();
11174 }
11175
11176 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11177                                 SelectionDAG &DAG) {
11178   SDLoc DL(Op);
11179   MVT VT = Op.getSimpleValueType();
11180   SDValue In = Op.getOperand(0);
11181   MVT SVT = In.getSimpleValueType();
11182
11183   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11184     return LowerZERO_EXTEND_AVX512(Op, DAG);
11185
11186   if (Subtarget->hasFp256()) {
11187     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11188     if (Res.getNode())
11189       return Res;
11190   }
11191
11192   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11193          VT.getVectorNumElements() != SVT.getVectorNumElements());
11194   return SDValue();
11195 }
11196
11197 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11198   SDLoc DL(Op);
11199   MVT VT = Op.getSimpleValueType();
11200   SDValue In = Op.getOperand(0);
11201   MVT InVT = In.getSimpleValueType();
11202
11203   if (VT == MVT::i1) {
11204     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11205            "Invalid scalar TRUNCATE operation");
11206     if (InVT == MVT::i32)
11207       return SDValue();
11208     if (InVT.getSizeInBits() == 64)
11209       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11210     else if (InVT.getSizeInBits() < 32)
11211       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11212     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11213   }
11214   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11215          "Invalid TRUNCATE operation");
11216
11217   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11218     if (VT.getVectorElementType().getSizeInBits() >=8)
11219       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11220
11221     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11222     unsigned NumElts = InVT.getVectorNumElements();
11223     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11224     if (InVT.getSizeInBits() < 512) {
11225       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11226       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11227       InVT = ExtVT;
11228     }
11229     
11230     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11231     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11232     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11233     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11234     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11235                            MachinePointerInfo::getConstantPool(),
11236                            false, false, false, Alignment);
11237     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11238     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11239     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11240   }
11241
11242   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11243     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11244     if (Subtarget->hasInt256()) {
11245       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11246       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11247       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11248                                 ShufMask);
11249       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11250                          DAG.getIntPtrConstant(0));
11251     }
11252
11253     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11254                                DAG.getIntPtrConstant(0));
11255     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11256                                DAG.getIntPtrConstant(2));
11257     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11258     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11259     static const int ShufMask[] = {0, 2, 4, 6};
11260     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11261   }
11262
11263   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11264     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11265     if (Subtarget->hasInt256()) {
11266       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11267
11268       SmallVector<SDValue,32> pshufbMask;
11269       for (unsigned i = 0; i < 2; ++i) {
11270         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11271         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11272         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11273         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11274         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11275         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11276         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11277         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11278         for (unsigned j = 0; j < 8; ++j)
11279           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11280       }
11281       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11282       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11283       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11284
11285       static const int ShufMask[] = {0,  2,  -1,  -1};
11286       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11287                                 &ShufMask[0]);
11288       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11289                        DAG.getIntPtrConstant(0));
11290       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11291     }
11292
11293     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11294                                DAG.getIntPtrConstant(0));
11295
11296     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11297                                DAG.getIntPtrConstant(4));
11298
11299     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11300     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11301
11302     // The PSHUFB mask:
11303     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11304                                    -1, -1, -1, -1, -1, -1, -1, -1};
11305
11306     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11307     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11308     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11309
11310     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11311     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11312
11313     // The MOVLHPS Mask:
11314     static const int ShufMask2[] = {0, 1, 4, 5};
11315     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11316     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11317   }
11318
11319   // Handle truncation of V256 to V128 using shuffles.
11320   if (!VT.is128BitVector() || !InVT.is256BitVector())
11321     return SDValue();
11322
11323   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11324
11325   unsigned NumElems = VT.getVectorNumElements();
11326   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11327
11328   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11329   // Prepare truncation shuffle mask
11330   for (unsigned i = 0; i != NumElems; ++i)
11331     MaskVec[i] = i * 2;
11332   SDValue V = DAG.getVectorShuffle(NVT, DL,
11333                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11334                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11335   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11336                      DAG.getIntPtrConstant(0));
11337 }
11338
11339 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11340                                            SelectionDAG &DAG) const {
11341   assert(!Op.getSimpleValueType().isVector());
11342
11343   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11344     /*IsSigned=*/ true, /*IsReplace=*/ false);
11345   SDValue FIST = Vals.first, StackSlot = Vals.second;
11346   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11347   if (!FIST.getNode()) return Op;
11348
11349   if (StackSlot.getNode())
11350     // Load the result.
11351     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11352                        FIST, StackSlot, MachinePointerInfo(),
11353                        false, false, false, 0);
11354
11355   // The node is the result.
11356   return FIST;
11357 }
11358
11359 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11360                                            SelectionDAG &DAG) const {
11361   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11362     /*IsSigned=*/ false, /*IsReplace=*/ false);
11363   SDValue FIST = Vals.first, StackSlot = Vals.second;
11364   assert(FIST.getNode() && "Unexpected failure");
11365
11366   if (StackSlot.getNode())
11367     // Load the result.
11368     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11369                        FIST, StackSlot, MachinePointerInfo(),
11370                        false, false, false, 0);
11371
11372   // The node is the result.
11373   return FIST;
11374 }
11375
11376 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11377   SDLoc DL(Op);
11378   MVT VT = Op.getSimpleValueType();
11379   SDValue In = Op.getOperand(0);
11380   MVT SVT = In.getSimpleValueType();
11381
11382   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11383
11384   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11385                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11386                                  In, DAG.getUNDEF(SVT)));
11387 }
11388
11389 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11390   LLVMContext *Context = DAG.getContext();
11391   SDLoc dl(Op);
11392   MVT VT = Op.getSimpleValueType();
11393   MVT EltVT = VT;
11394   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11395   if (VT.isVector()) {
11396     EltVT = VT.getVectorElementType();
11397     NumElts = VT.getVectorNumElements();
11398   }
11399   Constant *C;
11400   if (EltVT == MVT::f64)
11401     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11402                                           APInt(64, ~(1ULL << 63))));
11403   else
11404     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11405                                           APInt(32, ~(1U << 31))));
11406   C = ConstantVector::getSplat(NumElts, C);
11407   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11408   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11409   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11410   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11411                              MachinePointerInfo::getConstantPool(),
11412                              false, false, false, Alignment);
11413   if (VT.isVector()) {
11414     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11415     return DAG.getNode(ISD::BITCAST, dl, VT,
11416                        DAG.getNode(ISD::AND, dl, ANDVT,
11417                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11418                                                Op.getOperand(0)),
11419                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11420   }
11421   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11422 }
11423
11424 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11425   LLVMContext *Context = DAG.getContext();
11426   SDLoc dl(Op);
11427   MVT VT = Op.getSimpleValueType();
11428   MVT EltVT = VT;
11429   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11430   if (VT.isVector()) {
11431     EltVT = VT.getVectorElementType();
11432     NumElts = VT.getVectorNumElements();
11433   }
11434   Constant *C;
11435   if (EltVT == MVT::f64)
11436     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11437                                           APInt(64, 1ULL << 63)));
11438   else
11439     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11440                                           APInt(32, 1U << 31)));
11441   C = ConstantVector::getSplat(NumElts, C);
11442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11443   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11444   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11445   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11446                              MachinePointerInfo::getConstantPool(),
11447                              false, false, false, Alignment);
11448   if (VT.isVector()) {
11449     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11450     return DAG.getNode(ISD::BITCAST, dl, VT,
11451                        DAG.getNode(ISD::XOR, dl, XORVT,
11452                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11453                                                Op.getOperand(0)),
11454                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11455   }
11456
11457   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11458 }
11459
11460 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11461   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11462   LLVMContext *Context = DAG.getContext();
11463   SDValue Op0 = Op.getOperand(0);
11464   SDValue Op1 = Op.getOperand(1);
11465   SDLoc dl(Op);
11466   MVT VT = Op.getSimpleValueType();
11467   MVT SrcVT = Op1.getSimpleValueType();
11468
11469   // If second operand is smaller, extend it first.
11470   if (SrcVT.bitsLT(VT)) {
11471     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11472     SrcVT = VT;
11473   }
11474   // And if it is bigger, shrink it first.
11475   if (SrcVT.bitsGT(VT)) {
11476     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11477     SrcVT = VT;
11478   }
11479
11480   // At this point the operands and the result should have the same
11481   // type, and that won't be f80 since that is not custom lowered.
11482
11483   // First get the sign bit of second operand.
11484   SmallVector<Constant*,4> CV;
11485   if (SrcVT == MVT::f64) {
11486     const fltSemantics &Sem = APFloat::IEEEdouble;
11487     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11488     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11489   } else {
11490     const fltSemantics &Sem = APFloat::IEEEsingle;
11491     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11492     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11493     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11494     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11495   }
11496   Constant *C = ConstantVector::get(CV);
11497   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11498   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11499                               MachinePointerInfo::getConstantPool(),
11500                               false, false, false, 16);
11501   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11502
11503   // Shift sign bit right or left if the two operands have different types.
11504   if (SrcVT.bitsGT(VT)) {
11505     // Op0 is MVT::f32, Op1 is MVT::f64.
11506     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11507     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11508                           DAG.getConstant(32, MVT::i32));
11509     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11510     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11511                           DAG.getIntPtrConstant(0));
11512   }
11513
11514   // Clear first operand sign bit.
11515   CV.clear();
11516   if (VT == MVT::f64) {
11517     const fltSemantics &Sem = APFloat::IEEEdouble;
11518     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11519                                                    APInt(64, ~(1ULL << 63)))));
11520     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11521   } else {
11522     const fltSemantics &Sem = APFloat::IEEEsingle;
11523     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11524                                                    APInt(32, ~(1U << 31)))));
11525     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11526     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11527     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11528   }
11529   C = ConstantVector::get(CV);
11530   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11531   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11532                               MachinePointerInfo::getConstantPool(),
11533                               false, false, false, 16);
11534   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11535
11536   // Or the value with the sign bit.
11537   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11538 }
11539
11540 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11541   SDValue N0 = Op.getOperand(0);
11542   SDLoc dl(Op);
11543   MVT VT = Op.getSimpleValueType();
11544
11545   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11546   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11547                                   DAG.getConstant(1, VT));
11548   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11549 }
11550
11551 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11552 //
11553 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11554                                       SelectionDAG &DAG) {
11555   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11556
11557   if (!Subtarget->hasSSE41())
11558     return SDValue();
11559
11560   if (!Op->hasOneUse())
11561     return SDValue();
11562
11563   SDNode *N = Op.getNode();
11564   SDLoc DL(N);
11565
11566   SmallVector<SDValue, 8> Opnds;
11567   DenseMap<SDValue, unsigned> VecInMap;
11568   SmallVector<SDValue, 8> VecIns;
11569   EVT VT = MVT::Other;
11570
11571   // Recognize a special case where a vector is casted into wide integer to
11572   // test all 0s.
11573   Opnds.push_back(N->getOperand(0));
11574   Opnds.push_back(N->getOperand(1));
11575
11576   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11577     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11578     // BFS traverse all OR'd operands.
11579     if (I->getOpcode() == ISD::OR) {
11580       Opnds.push_back(I->getOperand(0));
11581       Opnds.push_back(I->getOperand(1));
11582       // Re-evaluate the number of nodes to be traversed.
11583       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11584       continue;
11585     }
11586
11587     // Quit if a non-EXTRACT_VECTOR_ELT
11588     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11589       return SDValue();
11590
11591     // Quit if without a constant index.
11592     SDValue Idx = I->getOperand(1);
11593     if (!isa<ConstantSDNode>(Idx))
11594       return SDValue();
11595
11596     SDValue ExtractedFromVec = I->getOperand(0);
11597     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11598     if (M == VecInMap.end()) {
11599       VT = ExtractedFromVec.getValueType();
11600       // Quit if not 128/256-bit vector.
11601       if (!VT.is128BitVector() && !VT.is256BitVector())
11602         return SDValue();
11603       // Quit if not the same type.
11604       if (VecInMap.begin() != VecInMap.end() &&
11605           VT != VecInMap.begin()->first.getValueType())
11606         return SDValue();
11607       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11608       VecIns.push_back(ExtractedFromVec);
11609     }
11610     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11611   }
11612
11613   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11614          "Not extracted from 128-/256-bit vector.");
11615
11616   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11617
11618   for (DenseMap<SDValue, unsigned>::const_iterator
11619         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11620     // Quit if not all elements are used.
11621     if (I->second != FullMask)
11622       return SDValue();
11623   }
11624
11625   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11626
11627   // Cast all vectors into TestVT for PTEST.
11628   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11629     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11630
11631   // If more than one full vectors are evaluated, OR them first before PTEST.
11632   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11633     // Each iteration will OR 2 nodes and append the result until there is only
11634     // 1 node left, i.e. the final OR'd value of all vectors.
11635     SDValue LHS = VecIns[Slot];
11636     SDValue RHS = VecIns[Slot + 1];
11637     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11638   }
11639
11640   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11641                      VecIns.back(), VecIns.back());
11642 }
11643
11644 /// \brief return true if \c Op has a use that doesn't just read flags.
11645 static bool hasNonFlagsUse(SDValue Op) {
11646   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11647        ++UI) {
11648     SDNode *User = *UI;
11649     unsigned UOpNo = UI.getOperandNo();
11650     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11651       // Look pass truncate.
11652       UOpNo = User->use_begin().getOperandNo();
11653       User = *User->use_begin();
11654     }
11655
11656     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11657         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11658       return true;
11659   }
11660   return false;
11661 }
11662
11663 /// Emit nodes that will be selected as "test Op0,Op0", or something
11664 /// equivalent.
11665 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11666                                     SelectionDAG &DAG) const {
11667   if (Op.getValueType() == MVT::i1)
11668     // KORTEST instruction should be selected
11669     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11670                        DAG.getConstant(0, Op.getValueType()));
11671
11672   // CF and OF aren't always set the way we want. Determine which
11673   // of these we need.
11674   bool NeedCF = false;
11675   bool NeedOF = false;
11676   switch (X86CC) {
11677   default: break;
11678   case X86::COND_A: case X86::COND_AE:
11679   case X86::COND_B: case X86::COND_BE:
11680     NeedCF = true;
11681     break;
11682   case X86::COND_G: case X86::COND_GE:
11683   case X86::COND_L: case X86::COND_LE:
11684   case X86::COND_O: case X86::COND_NO: {
11685     // Check if we really need to set the
11686     // Overflow flag. If NoSignedWrap is present
11687     // that is not actually needed.
11688     switch (Op->getOpcode()) {
11689     case ISD::ADD:
11690     case ISD::SUB:
11691     case ISD::MUL:
11692     case ISD::SHL: {
11693       const BinaryWithFlagsSDNode *BinNode =
11694           cast<BinaryWithFlagsSDNode>(Op.getNode());
11695       if (BinNode->hasNoSignedWrap())
11696         break;
11697     }
11698     default:
11699       NeedOF = true;
11700       break;
11701     }
11702     break;
11703   }
11704   }
11705   // See if we can use the EFLAGS value from the operand instead of
11706   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11707   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11708   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11709     // Emit a CMP with 0, which is the TEST pattern.
11710     //if (Op.getValueType() == MVT::i1)
11711     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11712     //                     DAG.getConstant(0, MVT::i1));
11713     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11714                        DAG.getConstant(0, Op.getValueType()));
11715   }
11716   unsigned Opcode = 0;
11717   unsigned NumOperands = 0;
11718
11719   // Truncate operations may prevent the merge of the SETCC instruction
11720   // and the arithmetic instruction before it. Attempt to truncate the operands
11721   // of the arithmetic instruction and use a reduced bit-width instruction.
11722   bool NeedTruncation = false;
11723   SDValue ArithOp = Op;
11724   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11725     SDValue Arith = Op->getOperand(0);
11726     // Both the trunc and the arithmetic op need to have one user each.
11727     if (Arith->hasOneUse())
11728       switch (Arith.getOpcode()) {
11729         default: break;
11730         case ISD::ADD:
11731         case ISD::SUB:
11732         case ISD::AND:
11733         case ISD::OR:
11734         case ISD::XOR: {
11735           NeedTruncation = true;
11736           ArithOp = Arith;
11737         }
11738       }
11739   }
11740
11741   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11742   // which may be the result of a CAST.  We use the variable 'Op', which is the
11743   // non-casted variable when we check for possible users.
11744   switch (ArithOp.getOpcode()) {
11745   case ISD::ADD:
11746     // Due to an isel shortcoming, be conservative if this add is likely to be
11747     // selected as part of a load-modify-store instruction. When the root node
11748     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11749     // uses of other nodes in the match, such as the ADD in this case. This
11750     // leads to the ADD being left around and reselected, with the result being
11751     // two adds in the output.  Alas, even if none our users are stores, that
11752     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11753     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11754     // climbing the DAG back to the root, and it doesn't seem to be worth the
11755     // effort.
11756     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11757          UE = Op.getNode()->use_end(); UI != UE; ++UI)
11758       if (UI->getOpcode() != ISD::CopyToReg &&
11759           UI->getOpcode() != ISD::SETCC &&
11760           UI->getOpcode() != ISD::STORE)
11761         goto default_case;
11762
11763     if (ConstantSDNode *C =
11764         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11765       // An add of one will be selected as an INC.
11766       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11767         Opcode = X86ISD::INC;
11768         NumOperands = 1;
11769         break;
11770       }
11771
11772       // An add of negative one (subtract of one) will be selected as a DEC.
11773       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11774         Opcode = X86ISD::DEC;
11775         NumOperands = 1;
11776         break;
11777       }
11778     }
11779
11780     // Otherwise use a regular EFLAGS-setting add.
11781     Opcode = X86ISD::ADD;
11782     NumOperands = 2;
11783     break;
11784   case ISD::SHL:
11785   case ISD::SRL:
11786     // If we have a constant logical shift that's only used in a comparison
11787     // against zero turn it into an equivalent AND. This allows turning it into
11788     // a TEST instruction later.
11789     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11790         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11791       EVT VT = Op.getValueType();
11792       unsigned BitWidth = VT.getSizeInBits();
11793       unsigned ShAmt = Op->getConstantOperandVal(1);
11794       if (ShAmt >= BitWidth) // Avoid undefined shifts.
11795         break;
11796       APInt Mask = ArithOp.getOpcode() == ISD::SRL
11797                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11798                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11799       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11800         break;
11801       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11802                                 DAG.getConstant(Mask, VT));
11803       DAG.ReplaceAllUsesWith(Op, New);
11804       Op = New;
11805     }
11806     break;
11807
11808   case ISD::AND:
11809     // If the primary and result isn't used, don't bother using X86ISD::AND,
11810     // because a TEST instruction will be better.
11811     if (!hasNonFlagsUse(Op))
11812       break;
11813     // FALL THROUGH
11814   case ISD::SUB:
11815   case ISD::OR:
11816   case ISD::XOR:
11817     // Due to the ISEL shortcoming noted above, be conservative if this op is
11818     // likely to be selected as part of a load-modify-store instruction.
11819     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11820            UE = Op.getNode()->use_end(); UI != UE; ++UI)
11821       if (UI->getOpcode() == ISD::STORE)
11822         goto default_case;
11823
11824     // Otherwise use a regular EFLAGS-setting instruction.
11825     switch (ArithOp.getOpcode()) {
11826     default: llvm_unreachable("unexpected operator!");
11827     case ISD::SUB: Opcode = X86ISD::SUB; break;
11828     case ISD::XOR: Opcode = X86ISD::XOR; break;
11829     case ISD::AND: Opcode = X86ISD::AND; break;
11830     case ISD::OR: {
11831       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11832         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11833         if (EFLAGS.getNode())
11834           return EFLAGS;
11835       }
11836       Opcode = X86ISD::OR;
11837       break;
11838     }
11839     }
11840
11841     NumOperands = 2;
11842     break;
11843   case X86ISD::ADD:
11844   case X86ISD::SUB:
11845   case X86ISD::INC:
11846   case X86ISD::DEC:
11847   case X86ISD::OR:
11848   case X86ISD::XOR:
11849   case X86ISD::AND:
11850     return SDValue(Op.getNode(), 1);
11851   default:
11852   default_case:
11853     break;
11854   }
11855
11856   // If we found that truncation is beneficial, perform the truncation and
11857   // update 'Op'.
11858   if (NeedTruncation) {
11859     EVT VT = Op.getValueType();
11860     SDValue WideVal = Op->getOperand(0);
11861     EVT WideVT = WideVal.getValueType();
11862     unsigned ConvertedOp = 0;
11863     // Use a target machine opcode to prevent further DAGCombine
11864     // optimizations that may separate the arithmetic operations
11865     // from the setcc node.
11866     switch (WideVal.getOpcode()) {
11867       default: break;
11868       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11869       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11870       case ISD::AND: ConvertedOp = X86ISD::AND; break;
11871       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
11872       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11873     }
11874
11875     if (ConvertedOp) {
11876       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11877       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11878         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11879         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11880         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11881       }
11882     }
11883   }
11884
11885   if (Opcode == 0)
11886     // Emit a CMP with 0, which is the TEST pattern.
11887     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11888                        DAG.getConstant(0, Op.getValueType()));
11889
11890   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11891   SmallVector<SDValue, 4> Ops;
11892   for (unsigned i = 0; i != NumOperands; ++i)
11893     Ops.push_back(Op.getOperand(i));
11894
11895   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11896   DAG.ReplaceAllUsesWith(Op, New);
11897   return SDValue(New.getNode(), 1);
11898 }
11899
11900 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11901 /// equivalent.
11902 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11903                                    SDLoc dl, SelectionDAG &DAG) const {
11904   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11905     if (C->getAPIntValue() == 0)
11906       return EmitTest(Op0, X86CC, dl, DAG);
11907
11908      if (Op0.getValueType() == MVT::i1)
11909        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11910   }
11911  
11912   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11913        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11914     // Do the comparison at i32 if it's smaller, besides the Atom case. 
11915     // This avoids subregister aliasing issues. Keep the smaller reference 
11916     // if we're optimizing for size, however, as that'll allow better folding 
11917     // of memory operations.
11918     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11919         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11920              AttributeSet::FunctionIndex, Attribute::MinSize) &&
11921         !Subtarget->isAtom()) {
11922       unsigned ExtendOp =
11923           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11924       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11925       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11926     }
11927     // Use SUB instead of CMP to enable CSE between SUB and CMP.
11928     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11929     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11930                               Op0, Op1);
11931     return SDValue(Sub.getNode(), 1);
11932   }
11933   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11934 }
11935
11936 /// Convert a comparison if required by the subtarget.
11937 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11938                                                  SelectionDAG &DAG) const {
11939   // If the subtarget does not support the FUCOMI instruction, floating-point
11940   // comparisons have to be converted.
11941   if (Subtarget->hasCMov() ||
11942       Cmp.getOpcode() != X86ISD::CMP ||
11943       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11944       !Cmp.getOperand(1).getValueType().isFloatingPoint())
11945     return Cmp;
11946
11947   // The instruction selector will select an FUCOM instruction instead of
11948   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11949   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11950   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11951   SDLoc dl(Cmp);
11952   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11953   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11954   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11955                             DAG.getConstant(8, MVT::i8));
11956   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11957   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11958 }
11959
11960 static bool isAllOnes(SDValue V) {
11961   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11962   return C && C->isAllOnesValue();
11963 }
11964
11965 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11966 /// if it's possible.
11967 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11968                                      SDLoc dl, SelectionDAG &DAG) const {
11969   SDValue Op0 = And.getOperand(0);
11970   SDValue Op1 = And.getOperand(1);
11971   if (Op0.getOpcode() == ISD::TRUNCATE)
11972     Op0 = Op0.getOperand(0);
11973   if (Op1.getOpcode() == ISD::TRUNCATE)
11974     Op1 = Op1.getOperand(0);
11975
11976   SDValue LHS, RHS;
11977   if (Op1.getOpcode() == ISD::SHL)
11978     std::swap(Op0, Op1);
11979   if (Op0.getOpcode() == ISD::SHL) {
11980     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11981       if (And00C->getZExtValue() == 1) {
11982         // If we looked past a truncate, check that it's only truncating away
11983         // known zeros.
11984         unsigned BitWidth = Op0.getValueSizeInBits();
11985         unsigned AndBitWidth = And.getValueSizeInBits();
11986         if (BitWidth > AndBitWidth) {
11987           APInt Zeros, Ones;
11988           DAG.computeKnownBits(Op0, Zeros, Ones);
11989           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11990             return SDValue();
11991         }
11992         LHS = Op1;
11993         RHS = Op0.getOperand(1);
11994       }
11995   } else if (Op1.getOpcode() == ISD::Constant) {
11996     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11997     uint64_t AndRHSVal = AndRHS->getZExtValue();
11998     SDValue AndLHS = Op0;
11999
12000     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12001       LHS = AndLHS.getOperand(0);
12002       RHS = AndLHS.getOperand(1);
12003     }
12004
12005     // Use BT if the immediate can't be encoded in a TEST instruction.
12006     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12007       LHS = AndLHS;
12008       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12009     }
12010   }
12011
12012   if (LHS.getNode()) {
12013     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12014     // instruction.  Since the shift amount is in-range-or-undefined, we know
12015     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12016     // the encoding for the i16 version is larger than the i32 version.
12017     // Also promote i16 to i32 for performance / code size reason.
12018     if (LHS.getValueType() == MVT::i8 ||
12019         LHS.getValueType() == MVT::i16)
12020       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12021
12022     // If the operand types disagree, extend the shift amount to match.  Since
12023     // BT ignores high bits (like shifts) we can use anyextend.
12024     if (LHS.getValueType() != RHS.getValueType())
12025       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12026
12027     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12028     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12029     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12030                        DAG.getConstant(Cond, MVT::i8), BT);
12031   }
12032
12033   return SDValue();
12034 }
12035
12036 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12037 /// mask CMPs.
12038 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12039                               SDValue &Op1) {
12040   unsigned SSECC;
12041   bool Swap = false;
12042
12043   // SSE Condition code mapping:
12044   //  0 - EQ
12045   //  1 - LT
12046   //  2 - LE
12047   //  3 - UNORD
12048   //  4 - NEQ
12049   //  5 - NLT
12050   //  6 - NLE
12051   //  7 - ORD
12052   switch (SetCCOpcode) {
12053   default: llvm_unreachable("Unexpected SETCC condition");
12054   case ISD::SETOEQ:
12055   case ISD::SETEQ:  SSECC = 0; break;
12056   case ISD::SETOGT:
12057   case ISD::SETGT:  Swap = true; // Fallthrough
12058   case ISD::SETLT:
12059   case ISD::SETOLT: SSECC = 1; break;
12060   case ISD::SETOGE:
12061   case ISD::SETGE:  Swap = true; // Fallthrough
12062   case ISD::SETLE:
12063   case ISD::SETOLE: SSECC = 2; break;
12064   case ISD::SETUO:  SSECC = 3; break;
12065   case ISD::SETUNE:
12066   case ISD::SETNE:  SSECC = 4; break;
12067   case ISD::SETULE: Swap = true; // Fallthrough
12068   case ISD::SETUGE: SSECC = 5; break;
12069   case ISD::SETULT: Swap = true; // Fallthrough
12070   case ISD::SETUGT: SSECC = 6; break;
12071   case ISD::SETO:   SSECC = 7; break;
12072   case ISD::SETUEQ:
12073   case ISD::SETONE: SSECC = 8; break;
12074   }
12075   if (Swap)
12076     std::swap(Op0, Op1);
12077
12078   return SSECC;
12079 }
12080
12081 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12082 // ones, and then concatenate the result back.
12083 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12084   MVT VT = Op.getSimpleValueType();
12085
12086   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12087          "Unsupported value type for operation");
12088
12089   unsigned NumElems = VT.getVectorNumElements();
12090   SDLoc dl(Op);
12091   SDValue CC = Op.getOperand(2);
12092
12093   // Extract the LHS vectors
12094   SDValue LHS = Op.getOperand(0);
12095   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12096   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12097
12098   // Extract the RHS vectors
12099   SDValue RHS = Op.getOperand(1);
12100   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12101   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12102
12103   // Issue the operation on the smaller types and concatenate the result back
12104   MVT EltVT = VT.getVectorElementType();
12105   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12106   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12107                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12108                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12109 }
12110
12111 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12112                                      const X86Subtarget *Subtarget) {
12113   SDValue Op0 = Op.getOperand(0);
12114   SDValue Op1 = Op.getOperand(1);
12115   SDValue CC = Op.getOperand(2);
12116   MVT VT = Op.getSimpleValueType();
12117   SDLoc dl(Op);
12118
12119   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12120          Op.getValueType().getScalarType() == MVT::i1 &&
12121          "Cannot set masked compare for this operation");
12122
12123   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12124   unsigned  Opc = 0;
12125   bool Unsigned = false;
12126   bool Swap = false;
12127   unsigned SSECC;
12128   switch (SetCCOpcode) {
12129   default: llvm_unreachable("Unexpected SETCC condition");
12130   case ISD::SETNE:  SSECC = 4; break;
12131   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12132   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12133   case ISD::SETLT:  Swap = true; //fall-through
12134   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12135   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12136   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12137   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12138   case ISD::SETULE: Unsigned = true; //fall-through
12139   case ISD::SETLE:  SSECC = 2; break;
12140   }
12141
12142   if (Swap)
12143     std::swap(Op0, Op1);
12144   if (Opc)
12145     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12146   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12147   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12148                      DAG.getConstant(SSECC, MVT::i8));
12149 }
12150
12151 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12152 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12153 /// return an empty value.
12154 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12155 {
12156   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12157   if (!BV)
12158     return SDValue();
12159
12160   MVT VT = Op1.getSimpleValueType();
12161   MVT EVT = VT.getVectorElementType();
12162   unsigned n = VT.getVectorNumElements();
12163   SmallVector<SDValue, 8> ULTOp1;
12164
12165   for (unsigned i = 0; i < n; ++i) {
12166     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12167     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12168       return SDValue();
12169
12170     // Avoid underflow.
12171     APInt Val = Elt->getAPIntValue();
12172     if (Val == 0)
12173       return SDValue();
12174
12175     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12176   }
12177
12178   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12179 }
12180
12181 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12182                            SelectionDAG &DAG) {
12183   SDValue Op0 = Op.getOperand(0);
12184   SDValue Op1 = Op.getOperand(1);
12185   SDValue CC = Op.getOperand(2);
12186   MVT VT = Op.getSimpleValueType();
12187   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12188   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12189   SDLoc dl(Op);
12190
12191   if (isFP) {
12192 #ifndef NDEBUG
12193     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12194     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12195 #endif
12196
12197     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12198     unsigned Opc = X86ISD::CMPP;
12199     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12200       assert(VT.getVectorNumElements() <= 16);
12201       Opc = X86ISD::CMPM;
12202     }
12203     // In the two special cases we can't handle, emit two comparisons.
12204     if (SSECC == 8) {
12205       unsigned CC0, CC1;
12206       unsigned CombineOpc;
12207       if (SetCCOpcode == ISD::SETUEQ) {
12208         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12209       } else {
12210         assert(SetCCOpcode == ISD::SETONE);
12211         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12212       }
12213
12214       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12215                                  DAG.getConstant(CC0, MVT::i8));
12216       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12217                                  DAG.getConstant(CC1, MVT::i8));
12218       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12219     }
12220     // Handle all other FP comparisons here.
12221     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12222                        DAG.getConstant(SSECC, MVT::i8));
12223   }
12224
12225   // Break 256-bit integer vector compare into smaller ones.
12226   if (VT.is256BitVector() && !Subtarget->hasInt256())
12227     return Lower256IntVSETCC(Op, DAG);
12228
12229   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12230   EVT OpVT = Op1.getValueType();
12231   if (Subtarget->hasAVX512()) {
12232     if (Op1.getValueType().is512BitVector() ||
12233         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12234       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12235
12236     // In AVX-512 architecture setcc returns mask with i1 elements,
12237     // But there is no compare instruction for i8 and i16 elements.
12238     // We are not talking about 512-bit operands in this case, these
12239     // types are illegal.
12240     if (MaskResult &&
12241         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12242          OpVT.getVectorElementType().getSizeInBits() >= 8))
12243       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12244                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12245   }
12246
12247   // We are handling one of the integer comparisons here.  Since SSE only has
12248   // GT and EQ comparisons for integer, swapping operands and multiple
12249   // operations may be required for some comparisons.
12250   unsigned Opc;
12251   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12252   bool Subus = false;
12253
12254   switch (SetCCOpcode) {
12255   default: llvm_unreachable("Unexpected SETCC condition");
12256   case ISD::SETNE:  Invert = true;
12257   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12258   case ISD::SETLT:  Swap = true;
12259   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12260   case ISD::SETGE:  Swap = true;
12261   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12262                     Invert = true; break;
12263   case ISD::SETULT: Swap = true;
12264   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12265                     FlipSigns = true; break;
12266   case ISD::SETUGE: Swap = true;
12267   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12268                     FlipSigns = true; Invert = true; break;
12269   }
12270
12271   // Special case: Use min/max operations for SETULE/SETUGE
12272   MVT VET = VT.getVectorElementType();
12273   bool hasMinMax =
12274        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12275     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12276
12277   if (hasMinMax) {
12278     switch (SetCCOpcode) {
12279     default: break;
12280     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12281     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12282     }
12283
12284     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12285   }
12286
12287   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12288   if (!MinMax && hasSubus) {
12289     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12290     // Op0 u<= Op1:
12291     //   t = psubus Op0, Op1
12292     //   pcmpeq t, <0..0>
12293     switch (SetCCOpcode) {
12294     default: break;
12295     case ISD::SETULT: {
12296       // If the comparison is against a constant we can turn this into a
12297       // setule.  With psubus, setule does not require a swap.  This is
12298       // beneficial because the constant in the register is no longer
12299       // destructed as the destination so it can be hoisted out of a loop.
12300       // Only do this pre-AVX since vpcmp* is no longer destructive.
12301       if (Subtarget->hasAVX())
12302         break;
12303       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12304       if (ULEOp1.getNode()) {
12305         Op1 = ULEOp1;
12306         Subus = true; Invert = false; Swap = false;
12307       }
12308       break;
12309     }
12310     // Psubus is better than flip-sign because it requires no inversion.
12311     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12312     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12313     }
12314
12315     if (Subus) {
12316       Opc = X86ISD::SUBUS;
12317       FlipSigns = false;
12318     }
12319   }
12320
12321   if (Swap)
12322     std::swap(Op0, Op1);
12323
12324   // Check that the operation in question is available (most are plain SSE2,
12325   // but PCMPGTQ and PCMPEQQ have different requirements).
12326   if (VT == MVT::v2i64) {
12327     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12328       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12329
12330       // First cast everything to the right type.
12331       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12332       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12333
12334       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12335       // bits of the inputs before performing those operations. The lower
12336       // compare is always unsigned.
12337       SDValue SB;
12338       if (FlipSigns) {
12339         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12340       } else {
12341         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12342         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12343         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12344                          Sign, Zero, Sign, Zero);
12345       }
12346       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12347       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12348
12349       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12350       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12351       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12352
12353       // Create masks for only the low parts/high parts of the 64 bit integers.
12354       static const int MaskHi[] = { 1, 1, 3, 3 };
12355       static const int MaskLo[] = { 0, 0, 2, 2 };
12356       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12357       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12358       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12359
12360       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12361       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12362
12363       if (Invert)
12364         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12365
12366       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12367     }
12368
12369     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12370       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12371       // pcmpeqd + pshufd + pand.
12372       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12373
12374       // First cast everything to the right type.
12375       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12376       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12377
12378       // Do the compare.
12379       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12380
12381       // Make sure the lower and upper halves are both all-ones.
12382       static const int Mask[] = { 1, 0, 3, 2 };
12383       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12384       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12385
12386       if (Invert)
12387         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12388
12389       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12390     }
12391   }
12392
12393   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12394   // bits of the inputs before performing those operations.
12395   if (FlipSigns) {
12396     EVT EltVT = VT.getVectorElementType();
12397     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12398     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12399     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12400   }
12401
12402   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12403
12404   // If the logical-not of the result is required, perform that now.
12405   if (Invert)
12406     Result = DAG.getNOT(dl, Result, VT);
12407
12408   if (MinMax)
12409     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12410
12411   if (Subus)
12412     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12413                          getZeroVector(VT, Subtarget, DAG, dl));
12414
12415   return Result;
12416 }
12417
12418 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12419
12420   MVT VT = Op.getSimpleValueType();
12421
12422   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12423
12424   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12425          && "SetCC type must be 8-bit or 1-bit integer");
12426   SDValue Op0 = Op.getOperand(0);
12427   SDValue Op1 = Op.getOperand(1);
12428   SDLoc dl(Op);
12429   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12430
12431   // Optimize to BT if possible.
12432   // Lower (X & (1 << N)) == 0 to BT(X, N).
12433   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12434   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12435   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12436       Op1.getOpcode() == ISD::Constant &&
12437       cast<ConstantSDNode>(Op1)->isNullValue() &&
12438       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12439     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12440     if (NewSetCC.getNode())
12441       return NewSetCC;
12442   }
12443
12444   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12445   // these.
12446   if (Op1.getOpcode() == ISD::Constant &&
12447       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12448        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12449       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12450
12451     // If the input is a setcc, then reuse the input setcc or use a new one with
12452     // the inverted condition.
12453     if (Op0.getOpcode() == X86ISD::SETCC) {
12454       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12455       bool Invert = (CC == ISD::SETNE) ^
12456         cast<ConstantSDNode>(Op1)->isNullValue();
12457       if (!Invert)
12458         return Op0;
12459
12460       CCode = X86::GetOppositeBranchCondition(CCode);
12461       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12462                                   DAG.getConstant(CCode, MVT::i8),
12463                                   Op0.getOperand(1));
12464       if (VT == MVT::i1)
12465         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12466       return SetCC;
12467     }
12468   }
12469   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12470       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12471       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12472
12473     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12474     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12475   }
12476
12477   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12478   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12479   if (X86CC == X86::COND_INVALID)
12480     return SDValue();
12481
12482   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12483   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12484   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12485                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12486   if (VT == MVT::i1)
12487     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12488   return SetCC;
12489 }
12490
12491 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12492 static bool isX86LogicalCmp(SDValue Op) {
12493   unsigned Opc = Op.getNode()->getOpcode();
12494   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12495       Opc == X86ISD::SAHF)
12496     return true;
12497   if (Op.getResNo() == 1 &&
12498       (Opc == X86ISD::ADD ||
12499        Opc == X86ISD::SUB ||
12500        Opc == X86ISD::ADC ||
12501        Opc == X86ISD::SBB ||
12502        Opc == X86ISD::SMUL ||
12503        Opc == X86ISD::UMUL ||
12504        Opc == X86ISD::INC ||
12505        Opc == X86ISD::DEC ||
12506        Opc == X86ISD::OR ||
12507        Opc == X86ISD::XOR ||
12508        Opc == X86ISD::AND))
12509     return true;
12510
12511   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12512     return true;
12513
12514   return false;
12515 }
12516
12517 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12518   if (V.getOpcode() != ISD::TRUNCATE)
12519     return false;
12520
12521   SDValue VOp0 = V.getOperand(0);
12522   unsigned InBits = VOp0.getValueSizeInBits();
12523   unsigned Bits = V.getValueSizeInBits();
12524   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12525 }
12526
12527 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12528   bool addTest = true;
12529   SDValue Cond  = Op.getOperand(0);
12530   SDValue Op1 = Op.getOperand(1);
12531   SDValue Op2 = Op.getOperand(2);
12532   SDLoc DL(Op);
12533   EVT VT = Op1.getValueType();
12534   SDValue CC;
12535
12536   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12537   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12538   // sequence later on.
12539   if (Cond.getOpcode() == ISD::SETCC &&
12540       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12541        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12542       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12543     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12544     int SSECC = translateX86FSETCC(
12545         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12546
12547     if (SSECC != 8) {
12548       if (Subtarget->hasAVX512()) {
12549         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12550                                   DAG.getConstant(SSECC, MVT::i8));
12551         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12552       }
12553       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12554                                 DAG.getConstant(SSECC, MVT::i8));
12555       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12556       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12557       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12558     }
12559   }
12560
12561   if (Cond.getOpcode() == ISD::SETCC) {
12562     SDValue NewCond = LowerSETCC(Cond, DAG);
12563     if (NewCond.getNode())
12564       Cond = NewCond;
12565   }
12566
12567   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12568   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12569   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12570   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12571   if (Cond.getOpcode() == X86ISD::SETCC &&
12572       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12573       isZero(Cond.getOperand(1).getOperand(1))) {
12574     SDValue Cmp = Cond.getOperand(1);
12575
12576     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12577
12578     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12579         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12580       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12581
12582       SDValue CmpOp0 = Cmp.getOperand(0);
12583       // Apply further optimizations for special cases
12584       // (select (x != 0), -1, 0) -> neg & sbb
12585       // (select (x == 0), 0, -1) -> neg & sbb
12586       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12587         if (YC->isNullValue() &&
12588             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12589           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12590           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12591                                     DAG.getConstant(0, CmpOp0.getValueType()),
12592                                     CmpOp0);
12593           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12594                                     DAG.getConstant(X86::COND_B, MVT::i8),
12595                                     SDValue(Neg.getNode(), 1));
12596           return Res;
12597         }
12598
12599       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12600                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12601       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12602
12603       SDValue Res =   // Res = 0 or -1.
12604         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12605                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12606
12607       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12608         Res = DAG.getNOT(DL, Res, Res.getValueType());
12609
12610       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12611       if (!N2C || !N2C->isNullValue())
12612         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12613       return Res;
12614     }
12615   }
12616
12617   // Look past (and (setcc_carry (cmp ...)), 1).
12618   if (Cond.getOpcode() == ISD::AND &&
12619       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12620     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12621     if (C && C->getAPIntValue() == 1)
12622       Cond = Cond.getOperand(0);
12623   }
12624
12625   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12626   // setting operand in place of the X86ISD::SETCC.
12627   unsigned CondOpcode = Cond.getOpcode();
12628   if (CondOpcode == X86ISD::SETCC ||
12629       CondOpcode == X86ISD::SETCC_CARRY) {
12630     CC = Cond.getOperand(0);
12631
12632     SDValue Cmp = Cond.getOperand(1);
12633     unsigned Opc = Cmp.getOpcode();
12634     MVT VT = Op.getSimpleValueType();
12635
12636     bool IllegalFPCMov = false;
12637     if (VT.isFloatingPoint() && !VT.isVector() &&
12638         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12639       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12640
12641     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12642         Opc == X86ISD::BT) { // FIXME
12643       Cond = Cmp;
12644       addTest = false;
12645     }
12646   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12647              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12648              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12649               Cond.getOperand(0).getValueType() != MVT::i8)) {
12650     SDValue LHS = Cond.getOperand(0);
12651     SDValue RHS = Cond.getOperand(1);
12652     unsigned X86Opcode;
12653     unsigned X86Cond;
12654     SDVTList VTs;
12655     switch (CondOpcode) {
12656     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12657     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12658     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12659     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12660     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12661     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12662     default: llvm_unreachable("unexpected overflowing operator");
12663     }
12664     if (CondOpcode == ISD::UMULO)
12665       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12666                           MVT::i32);
12667     else
12668       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12669
12670     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12671
12672     if (CondOpcode == ISD::UMULO)
12673       Cond = X86Op.getValue(2);
12674     else
12675       Cond = X86Op.getValue(1);
12676
12677     CC = DAG.getConstant(X86Cond, MVT::i8);
12678     addTest = false;
12679   }
12680
12681   if (addTest) {
12682     // Look pass the truncate if the high bits are known zero.
12683     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12684         Cond = Cond.getOperand(0);
12685
12686     // We know the result of AND is compared against zero. Try to match
12687     // it to BT.
12688     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12689       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12690       if (NewSetCC.getNode()) {
12691         CC = NewSetCC.getOperand(0);
12692         Cond = NewSetCC.getOperand(1);
12693         addTest = false;
12694       }
12695     }
12696   }
12697
12698   if (addTest) {
12699     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12700     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12701   }
12702
12703   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12704   // a <  b ?  0 : -1 -> RES = setcc_carry
12705   // a >= b ? -1 :  0 -> RES = setcc_carry
12706   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12707   if (Cond.getOpcode() == X86ISD::SUB) {
12708     Cond = ConvertCmpIfNecessary(Cond, DAG);
12709     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12710
12711     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12712         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12713       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12714                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12715       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12716         return DAG.getNOT(DL, Res, Res.getValueType());
12717       return Res;
12718     }
12719   }
12720
12721   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12722   // widen the cmov and push the truncate through. This avoids introducing a new
12723   // branch during isel and doesn't add any extensions.
12724   if (Op.getValueType() == MVT::i8 &&
12725       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12726     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12727     if (T1.getValueType() == T2.getValueType() &&
12728         // Blacklist CopyFromReg to avoid partial register stalls.
12729         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12730       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12731       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12732       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12733     }
12734   }
12735
12736   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12737   // condition is true.
12738   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12739   SDValue Ops[] = { Op2, Op1, CC, Cond };
12740   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12741 }
12742
12743 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12744   MVT VT = Op->getSimpleValueType(0);
12745   SDValue In = Op->getOperand(0);
12746   MVT InVT = In.getSimpleValueType();
12747   SDLoc dl(Op);
12748
12749   unsigned int NumElts = VT.getVectorNumElements();
12750   if (NumElts != 8 && NumElts != 16)
12751     return SDValue();
12752
12753   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12754     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12755
12756   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12757   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12758
12759   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12760   Constant *C = ConstantInt::get(*DAG.getContext(),
12761     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12762
12763   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12764   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12765   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12766                           MachinePointerInfo::getConstantPool(),
12767                           false, false, false, Alignment);
12768   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12769   if (VT.is512BitVector())
12770     return Brcst;
12771   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12772 }
12773
12774 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12775                                 SelectionDAG &DAG) {
12776   MVT VT = Op->getSimpleValueType(0);
12777   SDValue In = Op->getOperand(0);
12778   MVT InVT = In.getSimpleValueType();
12779   SDLoc dl(Op);
12780
12781   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12782     return LowerSIGN_EXTEND_AVX512(Op, DAG);
12783
12784   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12785       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12786       (VT != MVT::v16i16 || InVT != MVT::v16i8))
12787     return SDValue();
12788
12789   if (Subtarget->hasInt256())
12790     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12791
12792   // Optimize vectors in AVX mode
12793   // Sign extend  v8i16 to v8i32 and
12794   //              v4i32 to v4i64
12795   //
12796   // Divide input vector into two parts
12797   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12798   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12799   // concat the vectors to original VT
12800
12801   unsigned NumElems = InVT.getVectorNumElements();
12802   SDValue Undef = DAG.getUNDEF(InVT);
12803
12804   SmallVector<int,8> ShufMask1(NumElems, -1);
12805   for (unsigned i = 0; i != NumElems/2; ++i)
12806     ShufMask1[i] = i;
12807
12808   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12809
12810   SmallVector<int,8> ShufMask2(NumElems, -1);
12811   for (unsigned i = 0; i != NumElems/2; ++i)
12812     ShufMask2[i] = i + NumElems/2;
12813
12814   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12815
12816   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12817                                 VT.getVectorNumElements()/2);
12818
12819   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12820   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12821
12822   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12823 }
12824
12825 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12826 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12827 // from the AND / OR.
12828 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12829   Opc = Op.getOpcode();
12830   if (Opc != ISD::OR && Opc != ISD::AND)
12831     return false;
12832   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12833           Op.getOperand(0).hasOneUse() &&
12834           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12835           Op.getOperand(1).hasOneUse());
12836 }
12837
12838 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12839 // 1 and that the SETCC node has a single use.
12840 static bool isXor1OfSetCC(SDValue Op) {
12841   if (Op.getOpcode() != ISD::XOR)
12842     return false;
12843   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12844   if (N1C && N1C->getAPIntValue() == 1) {
12845     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12846       Op.getOperand(0).hasOneUse();
12847   }
12848   return false;
12849 }
12850
12851 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12852   bool addTest = true;
12853   SDValue Chain = Op.getOperand(0);
12854   SDValue Cond  = Op.getOperand(1);
12855   SDValue Dest  = Op.getOperand(2);
12856   SDLoc dl(Op);
12857   SDValue CC;
12858   bool Inverted = false;
12859
12860   if (Cond.getOpcode() == ISD::SETCC) {
12861     // Check for setcc([su]{add,sub,mul}o == 0).
12862     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12863         isa<ConstantSDNode>(Cond.getOperand(1)) &&
12864         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12865         Cond.getOperand(0).getResNo() == 1 &&
12866         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12867          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12868          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12869          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12870          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12871          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12872       Inverted = true;
12873       Cond = Cond.getOperand(0);
12874     } else {
12875       SDValue NewCond = LowerSETCC(Cond, DAG);
12876       if (NewCond.getNode())
12877         Cond = NewCond;
12878     }
12879   }
12880 #if 0
12881   // FIXME: LowerXALUO doesn't handle these!!
12882   else if (Cond.getOpcode() == X86ISD::ADD  ||
12883            Cond.getOpcode() == X86ISD::SUB  ||
12884            Cond.getOpcode() == X86ISD::SMUL ||
12885            Cond.getOpcode() == X86ISD::UMUL)
12886     Cond = LowerXALUO(Cond, DAG);
12887 #endif
12888
12889   // Look pass (and (setcc_carry (cmp ...)), 1).
12890   if (Cond.getOpcode() == ISD::AND &&
12891       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12892     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12893     if (C && C->getAPIntValue() == 1)
12894       Cond = Cond.getOperand(0);
12895   }
12896
12897   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12898   // setting operand in place of the X86ISD::SETCC.
12899   unsigned CondOpcode = Cond.getOpcode();
12900   if (CondOpcode == X86ISD::SETCC ||
12901       CondOpcode == X86ISD::SETCC_CARRY) {
12902     CC = Cond.getOperand(0);
12903
12904     SDValue Cmp = Cond.getOperand(1);
12905     unsigned Opc = Cmp.getOpcode();
12906     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12907     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12908       Cond = Cmp;
12909       addTest = false;
12910     } else {
12911       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12912       default: break;
12913       case X86::COND_O:
12914       case X86::COND_B:
12915         // These can only come from an arithmetic instruction with overflow,
12916         // e.g. SADDO, UADDO.
12917         Cond = Cond.getNode()->getOperand(1);
12918         addTest = false;
12919         break;
12920       }
12921     }
12922   }
12923   CondOpcode = Cond.getOpcode();
12924   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12925       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12926       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12927        Cond.getOperand(0).getValueType() != MVT::i8)) {
12928     SDValue LHS = Cond.getOperand(0);
12929     SDValue RHS = Cond.getOperand(1);
12930     unsigned X86Opcode;
12931     unsigned X86Cond;
12932     SDVTList VTs;
12933     // Keep this in sync with LowerXALUO, otherwise we might create redundant
12934     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12935     // X86ISD::INC).
12936     switch (CondOpcode) {
12937     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12938     case ISD::SADDO:
12939       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12940         if (C->isOne()) {
12941           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12942           break;
12943         }
12944       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12945     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12946     case ISD::SSUBO:
12947       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12948         if (C->isOne()) {
12949           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12950           break;
12951         }
12952       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12953     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12954     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12955     default: llvm_unreachable("unexpected overflowing operator");
12956     }
12957     if (Inverted)
12958       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12959     if (CondOpcode == ISD::UMULO)
12960       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12961                           MVT::i32);
12962     else
12963       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12964
12965     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12966
12967     if (CondOpcode == ISD::UMULO)
12968       Cond = X86Op.getValue(2);
12969     else
12970       Cond = X86Op.getValue(1);
12971
12972     CC = DAG.getConstant(X86Cond, MVT::i8);
12973     addTest = false;
12974   } else {
12975     unsigned CondOpc;
12976     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12977       SDValue Cmp = Cond.getOperand(0).getOperand(1);
12978       if (CondOpc == ISD::OR) {
12979         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12980         // two branches instead of an explicit OR instruction with a
12981         // separate test.
12982         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12983             isX86LogicalCmp(Cmp)) {
12984           CC = Cond.getOperand(0).getOperand(0);
12985           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12986                               Chain, Dest, CC, Cmp);
12987           CC = Cond.getOperand(1).getOperand(0);
12988           Cond = Cmp;
12989           addTest = false;
12990         }
12991       } else { // ISD::AND
12992         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12993         // two branches instead of an explicit AND instruction with a
12994         // separate test. However, we only do this if this block doesn't
12995         // have a fall-through edge, because this requires an explicit
12996         // jmp when the condition is false.
12997         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12998             isX86LogicalCmp(Cmp) &&
12999             Op.getNode()->hasOneUse()) {
13000           X86::CondCode CCode =
13001             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13002           CCode = X86::GetOppositeBranchCondition(CCode);
13003           CC = DAG.getConstant(CCode, MVT::i8);
13004           SDNode *User = *Op.getNode()->use_begin();
13005           // Look for an unconditional branch following this conditional branch.
13006           // We need this because we need to reverse the successors in order
13007           // to implement FCMP_OEQ.
13008           if (User->getOpcode() == ISD::BR) {
13009             SDValue FalseBB = User->getOperand(1);
13010             SDNode *NewBR =
13011               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13012             assert(NewBR == User);
13013             (void)NewBR;
13014             Dest = FalseBB;
13015
13016             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13017                                 Chain, Dest, CC, Cmp);
13018             X86::CondCode CCode =
13019               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13020             CCode = X86::GetOppositeBranchCondition(CCode);
13021             CC = DAG.getConstant(CCode, MVT::i8);
13022             Cond = Cmp;
13023             addTest = false;
13024           }
13025         }
13026       }
13027     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13028       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13029       // It should be transformed during dag combiner except when the condition
13030       // is set by a arithmetics with overflow node.
13031       X86::CondCode CCode =
13032         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13033       CCode = X86::GetOppositeBranchCondition(CCode);
13034       CC = DAG.getConstant(CCode, MVT::i8);
13035       Cond = Cond.getOperand(0).getOperand(1);
13036       addTest = false;
13037     } else if (Cond.getOpcode() == ISD::SETCC &&
13038                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13039       // For FCMP_OEQ, we can emit
13040       // two branches instead of an explicit AND instruction with a
13041       // separate test. However, we only do this if this block doesn't
13042       // have a fall-through edge, because this requires an explicit
13043       // jmp when the condition is false.
13044       if (Op.getNode()->hasOneUse()) {
13045         SDNode *User = *Op.getNode()->use_begin();
13046         // Look for an unconditional branch following this conditional branch.
13047         // We need this because we need to reverse the successors in order
13048         // to implement FCMP_OEQ.
13049         if (User->getOpcode() == ISD::BR) {
13050           SDValue FalseBB = User->getOperand(1);
13051           SDNode *NewBR =
13052             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13053           assert(NewBR == User);
13054           (void)NewBR;
13055           Dest = FalseBB;
13056
13057           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13058                                     Cond.getOperand(0), Cond.getOperand(1));
13059           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13060           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13061           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13062                               Chain, Dest, CC, Cmp);
13063           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13064           Cond = Cmp;
13065           addTest = false;
13066         }
13067       }
13068     } else if (Cond.getOpcode() == ISD::SETCC &&
13069                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13070       // For FCMP_UNE, we can emit
13071       // two branches instead of an explicit AND instruction with a
13072       // separate test. However, we only do this if this block doesn't
13073       // have a fall-through edge, because this requires an explicit
13074       // jmp when the condition is false.
13075       if (Op.getNode()->hasOneUse()) {
13076         SDNode *User = *Op.getNode()->use_begin();
13077         // Look for an unconditional branch following this conditional branch.
13078         // We need this because we need to reverse the successors in order
13079         // to implement FCMP_UNE.
13080         if (User->getOpcode() == ISD::BR) {
13081           SDValue FalseBB = User->getOperand(1);
13082           SDNode *NewBR =
13083             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13084           assert(NewBR == User);
13085           (void)NewBR;
13086
13087           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13088                                     Cond.getOperand(0), Cond.getOperand(1));
13089           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13090           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13091           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13092                               Chain, Dest, CC, Cmp);
13093           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13094           Cond = Cmp;
13095           addTest = false;
13096           Dest = FalseBB;
13097         }
13098       }
13099     }
13100   }
13101
13102   if (addTest) {
13103     // Look pass the truncate if the high bits are known zero.
13104     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13105         Cond = Cond.getOperand(0);
13106
13107     // We know the result of AND is compared against zero. Try to match
13108     // it to BT.
13109     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13110       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13111       if (NewSetCC.getNode()) {
13112         CC = NewSetCC.getOperand(0);
13113         Cond = NewSetCC.getOperand(1);
13114         addTest = false;
13115       }
13116     }
13117   }
13118
13119   if (addTest) {
13120     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13121     CC = DAG.getConstant(X86Cond, MVT::i8);
13122     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13123   }
13124   Cond = ConvertCmpIfNecessary(Cond, DAG);
13125   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13126                      Chain, Dest, CC, Cond);
13127 }
13128
13129 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13130 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13131 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13132 // that the guard pages used by the OS virtual memory manager are allocated in
13133 // correct sequence.
13134 SDValue
13135 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13136                                            SelectionDAG &DAG) const {
13137   MachineFunction &MF = DAG.getMachineFunction();
13138   bool SplitStack = MF.shouldSplitStack();
13139   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13140                SplitStack;
13141   SDLoc dl(Op);
13142
13143   if (!Lower) {
13144     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13145     SDNode* Node = Op.getNode();
13146
13147     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13148     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13149         " not tell us which reg is the stack pointer!");
13150     EVT VT = Node->getValueType(0);
13151     SDValue Tmp1 = SDValue(Node, 0);
13152     SDValue Tmp2 = SDValue(Node, 1);
13153     SDValue Tmp3 = Node->getOperand(2);
13154     SDValue Chain = Tmp1.getOperand(0);
13155
13156     // Chain the dynamic stack allocation so that it doesn't modify the stack
13157     // pointer when other instructions are using the stack.
13158     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13159         SDLoc(Node));
13160
13161     SDValue Size = Tmp2.getOperand(1);
13162     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13163     Chain = SP.getValue(1);
13164     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13165     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13166     unsigned StackAlign = TFI.getStackAlignment();
13167     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13168     if (Align > StackAlign)
13169       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13170           DAG.getConstant(-(uint64_t)Align, VT));
13171     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13172
13173     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13174         DAG.getIntPtrConstant(0, true), SDValue(),
13175         SDLoc(Node));
13176
13177     SDValue Ops[2] = { Tmp1, Tmp2 };
13178     return DAG.getMergeValues(Ops, dl);
13179   }
13180
13181   // Get the inputs.
13182   SDValue Chain = Op.getOperand(0);
13183   SDValue Size  = Op.getOperand(1);
13184   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13185   EVT VT = Op.getNode()->getValueType(0);
13186
13187   bool Is64Bit = Subtarget->is64Bit();
13188   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13189
13190   if (SplitStack) {
13191     MachineRegisterInfo &MRI = MF.getRegInfo();
13192
13193     if (Is64Bit) {
13194       // The 64 bit implementation of segmented stacks needs to clobber both r10
13195       // r11. This makes it impossible to use it along with nested parameters.
13196       const Function *F = MF.getFunction();
13197
13198       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13199            I != E; ++I)
13200         if (I->hasNestAttr())
13201           report_fatal_error("Cannot use segmented stacks with functions that "
13202                              "have nested arguments.");
13203     }
13204
13205     const TargetRegisterClass *AddrRegClass =
13206       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13207     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13208     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13209     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13210                                 DAG.getRegister(Vreg, SPTy));
13211     SDValue Ops1[2] = { Value, Chain };
13212     return DAG.getMergeValues(Ops1, dl);
13213   } else {
13214     SDValue Flag;
13215     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13216
13217     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13218     Flag = Chain.getValue(1);
13219     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13220
13221     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13222
13223     const X86RegisterInfo *RegInfo =
13224       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13225     unsigned SPReg = RegInfo->getStackRegister();
13226     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13227     Chain = SP.getValue(1);
13228
13229     if (Align) {
13230       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13231                        DAG.getConstant(-(uint64_t)Align, VT));
13232       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13233     }
13234
13235     SDValue Ops1[2] = { SP, Chain };
13236     return DAG.getMergeValues(Ops1, dl);
13237   }
13238 }
13239
13240 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13241   MachineFunction &MF = DAG.getMachineFunction();
13242   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13243
13244   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13245   SDLoc DL(Op);
13246
13247   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13248     // vastart just stores the address of the VarArgsFrameIndex slot into the
13249     // memory location argument.
13250     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13251                                    getPointerTy());
13252     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13253                         MachinePointerInfo(SV), false, false, 0);
13254   }
13255
13256   // __va_list_tag:
13257   //   gp_offset         (0 - 6 * 8)
13258   //   fp_offset         (48 - 48 + 8 * 16)
13259   //   overflow_arg_area (point to parameters coming in memory).
13260   //   reg_save_area
13261   SmallVector<SDValue, 8> MemOps;
13262   SDValue FIN = Op.getOperand(1);
13263   // Store gp_offset
13264   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13265                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13266                                                MVT::i32),
13267                                FIN, MachinePointerInfo(SV), false, false, 0);
13268   MemOps.push_back(Store);
13269
13270   // Store fp_offset
13271   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13272                     FIN, DAG.getIntPtrConstant(4));
13273   Store = DAG.getStore(Op.getOperand(0), DL,
13274                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13275                                        MVT::i32),
13276                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13277   MemOps.push_back(Store);
13278
13279   // Store ptr to overflow_arg_area
13280   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13281                     FIN, DAG.getIntPtrConstant(4));
13282   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13283                                     getPointerTy());
13284   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13285                        MachinePointerInfo(SV, 8),
13286                        false, false, 0);
13287   MemOps.push_back(Store);
13288
13289   // Store ptr to reg_save_area.
13290   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13291                     FIN, DAG.getIntPtrConstant(8));
13292   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13293                                     getPointerTy());
13294   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13295                        MachinePointerInfo(SV, 16), false, false, 0);
13296   MemOps.push_back(Store);
13297   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13298 }
13299
13300 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13301   assert(Subtarget->is64Bit() &&
13302          "LowerVAARG only handles 64-bit va_arg!");
13303   assert((Subtarget->isTargetLinux() ||
13304           Subtarget->isTargetDarwin()) &&
13305           "Unhandled target in LowerVAARG");
13306   assert(Op.getNode()->getNumOperands() == 4);
13307   SDValue Chain = Op.getOperand(0);
13308   SDValue SrcPtr = Op.getOperand(1);
13309   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13310   unsigned Align = Op.getConstantOperandVal(3);
13311   SDLoc dl(Op);
13312
13313   EVT ArgVT = Op.getNode()->getValueType(0);
13314   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13315   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13316   uint8_t ArgMode;
13317
13318   // Decide which area this value should be read from.
13319   // TODO: Implement the AMD64 ABI in its entirety. This simple
13320   // selection mechanism works only for the basic types.
13321   if (ArgVT == MVT::f80) {
13322     llvm_unreachable("va_arg for f80 not yet implemented");
13323   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13324     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13325   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13326     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13327   } else {
13328     llvm_unreachable("Unhandled argument type in LowerVAARG");
13329   }
13330
13331   if (ArgMode == 2) {
13332     // Sanity Check: Make sure using fp_offset makes sense.
13333     assert(!DAG.getTarget().Options.UseSoftFloat &&
13334            !(DAG.getMachineFunction()
13335                 .getFunction()->getAttributes()
13336                 .hasAttribute(AttributeSet::FunctionIndex,
13337                               Attribute::NoImplicitFloat)) &&
13338            Subtarget->hasSSE1());
13339   }
13340
13341   // Insert VAARG_64 node into the DAG
13342   // VAARG_64 returns two values: Variable Argument Address, Chain
13343   SmallVector<SDValue, 11> InstOps;
13344   InstOps.push_back(Chain);
13345   InstOps.push_back(SrcPtr);
13346   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13347   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13348   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13349   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13350   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13351                                           VTs, InstOps, MVT::i64,
13352                                           MachinePointerInfo(SV),
13353                                           /*Align=*/0,
13354                                           /*Volatile=*/false,
13355                                           /*ReadMem=*/true,
13356                                           /*WriteMem=*/true);
13357   Chain = VAARG.getValue(1);
13358
13359   // Load the next argument and return it
13360   return DAG.getLoad(ArgVT, dl,
13361                      Chain,
13362                      VAARG,
13363                      MachinePointerInfo(),
13364                      false, false, false, 0);
13365 }
13366
13367 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13368                            SelectionDAG &DAG) {
13369   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13370   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13371   SDValue Chain = Op.getOperand(0);
13372   SDValue DstPtr = Op.getOperand(1);
13373   SDValue SrcPtr = Op.getOperand(2);
13374   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13375   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13376   SDLoc DL(Op);
13377
13378   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13379                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13380                        false,
13381                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13382 }
13383
13384 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13385 // amount is a constant. Takes immediate version of shift as input.
13386 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13387                                           SDValue SrcOp, uint64_t ShiftAmt,
13388                                           SelectionDAG &DAG) {
13389   MVT ElementType = VT.getVectorElementType();
13390
13391   // Fold this packed shift into its first operand if ShiftAmt is 0.
13392   if (ShiftAmt == 0)
13393     return SrcOp;
13394
13395   // Check for ShiftAmt >= element width
13396   if (ShiftAmt >= ElementType.getSizeInBits()) {
13397     if (Opc == X86ISD::VSRAI)
13398       ShiftAmt = ElementType.getSizeInBits() - 1;
13399     else
13400       return DAG.getConstant(0, VT);
13401   }
13402
13403   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13404          && "Unknown target vector shift-by-constant node");
13405
13406   // Fold this packed vector shift into a build vector if SrcOp is a
13407   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13408   if (VT == SrcOp.getSimpleValueType() &&
13409       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13410     SmallVector<SDValue, 8> Elts;
13411     unsigned NumElts = SrcOp->getNumOperands();
13412     ConstantSDNode *ND;
13413
13414     switch(Opc) {
13415     default: llvm_unreachable(nullptr);
13416     case X86ISD::VSHLI:
13417       for (unsigned i=0; i!=NumElts; ++i) {
13418         SDValue CurrentOp = SrcOp->getOperand(i);
13419         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13420           Elts.push_back(CurrentOp);
13421           continue;
13422         }
13423         ND = cast<ConstantSDNode>(CurrentOp);
13424         const APInt &C = ND->getAPIntValue();
13425         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13426       }
13427       break;
13428     case X86ISD::VSRLI:
13429       for (unsigned i=0; i!=NumElts; ++i) {
13430         SDValue CurrentOp = SrcOp->getOperand(i);
13431         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13432           Elts.push_back(CurrentOp);
13433           continue;
13434         }
13435         ND = cast<ConstantSDNode>(CurrentOp);
13436         const APInt &C = ND->getAPIntValue();
13437         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13438       }
13439       break;
13440     case X86ISD::VSRAI:
13441       for (unsigned i=0; i!=NumElts; ++i) {
13442         SDValue CurrentOp = SrcOp->getOperand(i);
13443         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13444           Elts.push_back(CurrentOp);
13445           continue;
13446         }
13447         ND = cast<ConstantSDNode>(CurrentOp);
13448         const APInt &C = ND->getAPIntValue();
13449         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13450       }
13451       break;
13452     }
13453
13454     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13455   }
13456
13457   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13458 }
13459
13460 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13461 // may or may not be a constant. Takes immediate version of shift as input.
13462 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13463                                    SDValue SrcOp, SDValue ShAmt,
13464                                    SelectionDAG &DAG) {
13465   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13466
13467   // Catch shift-by-constant.
13468   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13469     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13470                                       CShAmt->getZExtValue(), DAG);
13471
13472   // Change opcode to non-immediate version
13473   switch (Opc) {
13474     default: llvm_unreachable("Unknown target vector shift node");
13475     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13476     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13477     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13478   }
13479
13480   // Need to build a vector containing shift amount
13481   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13482   SDValue ShOps[4];
13483   ShOps[0] = ShAmt;
13484   ShOps[1] = DAG.getConstant(0, MVT::i32);
13485   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13486   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13487
13488   // The return type has to be a 128-bit type with the same element
13489   // type as the input type.
13490   MVT EltVT = VT.getVectorElementType();
13491   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13492
13493   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13494   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13495 }
13496
13497 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13498   SDLoc dl(Op);
13499   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13500   switch (IntNo) {
13501   default: return SDValue();    // Don't custom lower most intrinsics.
13502   // Comparison intrinsics.
13503   case Intrinsic::x86_sse_comieq_ss:
13504   case Intrinsic::x86_sse_comilt_ss:
13505   case Intrinsic::x86_sse_comile_ss:
13506   case Intrinsic::x86_sse_comigt_ss:
13507   case Intrinsic::x86_sse_comige_ss:
13508   case Intrinsic::x86_sse_comineq_ss:
13509   case Intrinsic::x86_sse_ucomieq_ss:
13510   case Intrinsic::x86_sse_ucomilt_ss:
13511   case Intrinsic::x86_sse_ucomile_ss:
13512   case Intrinsic::x86_sse_ucomigt_ss:
13513   case Intrinsic::x86_sse_ucomige_ss:
13514   case Intrinsic::x86_sse_ucomineq_ss:
13515   case Intrinsic::x86_sse2_comieq_sd:
13516   case Intrinsic::x86_sse2_comilt_sd:
13517   case Intrinsic::x86_sse2_comile_sd:
13518   case Intrinsic::x86_sse2_comigt_sd:
13519   case Intrinsic::x86_sse2_comige_sd:
13520   case Intrinsic::x86_sse2_comineq_sd:
13521   case Intrinsic::x86_sse2_ucomieq_sd:
13522   case Intrinsic::x86_sse2_ucomilt_sd:
13523   case Intrinsic::x86_sse2_ucomile_sd:
13524   case Intrinsic::x86_sse2_ucomigt_sd:
13525   case Intrinsic::x86_sse2_ucomige_sd:
13526   case Intrinsic::x86_sse2_ucomineq_sd: {
13527     unsigned Opc;
13528     ISD::CondCode CC;
13529     switch (IntNo) {
13530     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13531     case Intrinsic::x86_sse_comieq_ss:
13532     case Intrinsic::x86_sse2_comieq_sd:
13533       Opc = X86ISD::COMI;
13534       CC = ISD::SETEQ;
13535       break;
13536     case Intrinsic::x86_sse_comilt_ss:
13537     case Intrinsic::x86_sse2_comilt_sd:
13538       Opc = X86ISD::COMI;
13539       CC = ISD::SETLT;
13540       break;
13541     case Intrinsic::x86_sse_comile_ss:
13542     case Intrinsic::x86_sse2_comile_sd:
13543       Opc = X86ISD::COMI;
13544       CC = ISD::SETLE;
13545       break;
13546     case Intrinsic::x86_sse_comigt_ss:
13547     case Intrinsic::x86_sse2_comigt_sd:
13548       Opc = X86ISD::COMI;
13549       CC = ISD::SETGT;
13550       break;
13551     case Intrinsic::x86_sse_comige_ss:
13552     case Intrinsic::x86_sse2_comige_sd:
13553       Opc = X86ISD::COMI;
13554       CC = ISD::SETGE;
13555       break;
13556     case Intrinsic::x86_sse_comineq_ss:
13557     case Intrinsic::x86_sse2_comineq_sd:
13558       Opc = X86ISD::COMI;
13559       CC = ISD::SETNE;
13560       break;
13561     case Intrinsic::x86_sse_ucomieq_ss:
13562     case Intrinsic::x86_sse2_ucomieq_sd:
13563       Opc = X86ISD::UCOMI;
13564       CC = ISD::SETEQ;
13565       break;
13566     case Intrinsic::x86_sse_ucomilt_ss:
13567     case Intrinsic::x86_sse2_ucomilt_sd:
13568       Opc = X86ISD::UCOMI;
13569       CC = ISD::SETLT;
13570       break;
13571     case Intrinsic::x86_sse_ucomile_ss:
13572     case Intrinsic::x86_sse2_ucomile_sd:
13573       Opc = X86ISD::UCOMI;
13574       CC = ISD::SETLE;
13575       break;
13576     case Intrinsic::x86_sse_ucomigt_ss:
13577     case Intrinsic::x86_sse2_ucomigt_sd:
13578       Opc = X86ISD::UCOMI;
13579       CC = ISD::SETGT;
13580       break;
13581     case Intrinsic::x86_sse_ucomige_ss:
13582     case Intrinsic::x86_sse2_ucomige_sd:
13583       Opc = X86ISD::UCOMI;
13584       CC = ISD::SETGE;
13585       break;
13586     case Intrinsic::x86_sse_ucomineq_ss:
13587     case Intrinsic::x86_sse2_ucomineq_sd:
13588       Opc = X86ISD::UCOMI;
13589       CC = ISD::SETNE;
13590       break;
13591     }
13592
13593     SDValue LHS = Op.getOperand(1);
13594     SDValue RHS = Op.getOperand(2);
13595     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13596     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13597     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13598     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13599                                 DAG.getConstant(X86CC, MVT::i8), Cond);
13600     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13601   }
13602
13603   // Arithmetic intrinsics.
13604   case Intrinsic::x86_sse2_pmulu_dq:
13605   case Intrinsic::x86_avx2_pmulu_dq:
13606     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13607                        Op.getOperand(1), Op.getOperand(2));
13608
13609   case Intrinsic::x86_sse41_pmuldq:
13610   case Intrinsic::x86_avx2_pmul_dq:
13611     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13612                        Op.getOperand(1), Op.getOperand(2));
13613
13614   case Intrinsic::x86_sse2_pmulhu_w:
13615   case Intrinsic::x86_avx2_pmulhu_w:
13616     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13617                        Op.getOperand(1), Op.getOperand(2));
13618
13619   case Intrinsic::x86_sse2_pmulh_w:
13620   case Intrinsic::x86_avx2_pmulh_w:
13621     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13622                        Op.getOperand(1), Op.getOperand(2));
13623
13624   // SSE2/AVX2 sub with unsigned saturation intrinsics
13625   case Intrinsic::x86_sse2_psubus_b:
13626   case Intrinsic::x86_sse2_psubus_w:
13627   case Intrinsic::x86_avx2_psubus_b:
13628   case Intrinsic::x86_avx2_psubus_w:
13629     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13630                        Op.getOperand(1), Op.getOperand(2));
13631
13632   // SSE3/AVX horizontal add/sub intrinsics
13633   case Intrinsic::x86_sse3_hadd_ps:
13634   case Intrinsic::x86_sse3_hadd_pd:
13635   case Intrinsic::x86_avx_hadd_ps_256:
13636   case Intrinsic::x86_avx_hadd_pd_256:
13637   case Intrinsic::x86_sse3_hsub_ps:
13638   case Intrinsic::x86_sse3_hsub_pd:
13639   case Intrinsic::x86_avx_hsub_ps_256:
13640   case Intrinsic::x86_avx_hsub_pd_256:
13641   case Intrinsic::x86_ssse3_phadd_w_128:
13642   case Intrinsic::x86_ssse3_phadd_d_128:
13643   case Intrinsic::x86_avx2_phadd_w:
13644   case Intrinsic::x86_avx2_phadd_d:
13645   case Intrinsic::x86_ssse3_phsub_w_128:
13646   case Intrinsic::x86_ssse3_phsub_d_128:
13647   case Intrinsic::x86_avx2_phsub_w:
13648   case Intrinsic::x86_avx2_phsub_d: {
13649     unsigned Opcode;
13650     switch (IntNo) {
13651     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13652     case Intrinsic::x86_sse3_hadd_ps:
13653     case Intrinsic::x86_sse3_hadd_pd:
13654     case Intrinsic::x86_avx_hadd_ps_256:
13655     case Intrinsic::x86_avx_hadd_pd_256:
13656       Opcode = X86ISD::FHADD;
13657       break;
13658     case Intrinsic::x86_sse3_hsub_ps:
13659     case Intrinsic::x86_sse3_hsub_pd:
13660     case Intrinsic::x86_avx_hsub_ps_256:
13661     case Intrinsic::x86_avx_hsub_pd_256:
13662       Opcode = X86ISD::FHSUB;
13663       break;
13664     case Intrinsic::x86_ssse3_phadd_w_128:
13665     case Intrinsic::x86_ssse3_phadd_d_128:
13666     case Intrinsic::x86_avx2_phadd_w:
13667     case Intrinsic::x86_avx2_phadd_d:
13668       Opcode = X86ISD::HADD;
13669       break;
13670     case Intrinsic::x86_ssse3_phsub_w_128:
13671     case Intrinsic::x86_ssse3_phsub_d_128:
13672     case Intrinsic::x86_avx2_phsub_w:
13673     case Intrinsic::x86_avx2_phsub_d:
13674       Opcode = X86ISD::HSUB;
13675       break;
13676     }
13677     return DAG.getNode(Opcode, dl, Op.getValueType(),
13678                        Op.getOperand(1), Op.getOperand(2));
13679   }
13680
13681   // SSE2/SSE41/AVX2 integer max/min intrinsics.
13682   case Intrinsic::x86_sse2_pmaxu_b:
13683   case Intrinsic::x86_sse41_pmaxuw:
13684   case Intrinsic::x86_sse41_pmaxud:
13685   case Intrinsic::x86_avx2_pmaxu_b:
13686   case Intrinsic::x86_avx2_pmaxu_w:
13687   case Intrinsic::x86_avx2_pmaxu_d:
13688   case Intrinsic::x86_sse2_pminu_b:
13689   case Intrinsic::x86_sse41_pminuw:
13690   case Intrinsic::x86_sse41_pminud:
13691   case Intrinsic::x86_avx2_pminu_b:
13692   case Intrinsic::x86_avx2_pminu_w:
13693   case Intrinsic::x86_avx2_pminu_d:
13694   case Intrinsic::x86_sse41_pmaxsb:
13695   case Intrinsic::x86_sse2_pmaxs_w:
13696   case Intrinsic::x86_sse41_pmaxsd:
13697   case Intrinsic::x86_avx2_pmaxs_b:
13698   case Intrinsic::x86_avx2_pmaxs_w:
13699   case Intrinsic::x86_avx2_pmaxs_d:
13700   case Intrinsic::x86_sse41_pminsb:
13701   case Intrinsic::x86_sse2_pmins_w:
13702   case Intrinsic::x86_sse41_pminsd:
13703   case Intrinsic::x86_avx2_pmins_b:
13704   case Intrinsic::x86_avx2_pmins_w:
13705   case Intrinsic::x86_avx2_pmins_d: {
13706     unsigned Opcode;
13707     switch (IntNo) {
13708     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13709     case Intrinsic::x86_sse2_pmaxu_b:
13710     case Intrinsic::x86_sse41_pmaxuw:
13711     case Intrinsic::x86_sse41_pmaxud:
13712     case Intrinsic::x86_avx2_pmaxu_b:
13713     case Intrinsic::x86_avx2_pmaxu_w:
13714     case Intrinsic::x86_avx2_pmaxu_d:
13715       Opcode = X86ISD::UMAX;
13716       break;
13717     case Intrinsic::x86_sse2_pminu_b:
13718     case Intrinsic::x86_sse41_pminuw:
13719     case Intrinsic::x86_sse41_pminud:
13720     case Intrinsic::x86_avx2_pminu_b:
13721     case Intrinsic::x86_avx2_pminu_w:
13722     case Intrinsic::x86_avx2_pminu_d:
13723       Opcode = X86ISD::UMIN;
13724       break;
13725     case Intrinsic::x86_sse41_pmaxsb:
13726     case Intrinsic::x86_sse2_pmaxs_w:
13727     case Intrinsic::x86_sse41_pmaxsd:
13728     case Intrinsic::x86_avx2_pmaxs_b:
13729     case Intrinsic::x86_avx2_pmaxs_w:
13730     case Intrinsic::x86_avx2_pmaxs_d:
13731       Opcode = X86ISD::SMAX;
13732       break;
13733     case Intrinsic::x86_sse41_pminsb:
13734     case Intrinsic::x86_sse2_pmins_w:
13735     case Intrinsic::x86_sse41_pminsd:
13736     case Intrinsic::x86_avx2_pmins_b:
13737     case Intrinsic::x86_avx2_pmins_w:
13738     case Intrinsic::x86_avx2_pmins_d:
13739       Opcode = X86ISD::SMIN;
13740       break;
13741     }
13742     return DAG.getNode(Opcode, dl, Op.getValueType(),
13743                        Op.getOperand(1), Op.getOperand(2));
13744   }
13745
13746   // SSE/SSE2/AVX floating point max/min intrinsics.
13747   case Intrinsic::x86_sse_max_ps:
13748   case Intrinsic::x86_sse2_max_pd:
13749   case Intrinsic::x86_avx_max_ps_256:
13750   case Intrinsic::x86_avx_max_pd_256:
13751   case Intrinsic::x86_sse_min_ps:
13752   case Intrinsic::x86_sse2_min_pd:
13753   case Intrinsic::x86_avx_min_ps_256:
13754   case Intrinsic::x86_avx_min_pd_256: {
13755     unsigned Opcode;
13756     switch (IntNo) {
13757     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13758     case Intrinsic::x86_sse_max_ps:
13759     case Intrinsic::x86_sse2_max_pd:
13760     case Intrinsic::x86_avx_max_ps_256:
13761     case Intrinsic::x86_avx_max_pd_256:
13762       Opcode = X86ISD::FMAX;
13763       break;
13764     case Intrinsic::x86_sse_min_ps:
13765     case Intrinsic::x86_sse2_min_pd:
13766     case Intrinsic::x86_avx_min_ps_256:
13767     case Intrinsic::x86_avx_min_pd_256:
13768       Opcode = X86ISD::FMIN;
13769       break;
13770     }
13771     return DAG.getNode(Opcode, dl, Op.getValueType(),
13772                        Op.getOperand(1), Op.getOperand(2));
13773   }
13774
13775   // AVX2 variable shift intrinsics
13776   case Intrinsic::x86_avx2_psllv_d:
13777   case Intrinsic::x86_avx2_psllv_q:
13778   case Intrinsic::x86_avx2_psllv_d_256:
13779   case Intrinsic::x86_avx2_psllv_q_256:
13780   case Intrinsic::x86_avx2_psrlv_d:
13781   case Intrinsic::x86_avx2_psrlv_q:
13782   case Intrinsic::x86_avx2_psrlv_d_256:
13783   case Intrinsic::x86_avx2_psrlv_q_256:
13784   case Intrinsic::x86_avx2_psrav_d:
13785   case Intrinsic::x86_avx2_psrav_d_256: {
13786     unsigned Opcode;
13787     switch (IntNo) {
13788     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13789     case Intrinsic::x86_avx2_psllv_d:
13790     case Intrinsic::x86_avx2_psllv_q:
13791     case Intrinsic::x86_avx2_psllv_d_256:
13792     case Intrinsic::x86_avx2_psllv_q_256:
13793       Opcode = ISD::SHL;
13794       break;
13795     case Intrinsic::x86_avx2_psrlv_d:
13796     case Intrinsic::x86_avx2_psrlv_q:
13797     case Intrinsic::x86_avx2_psrlv_d_256:
13798     case Intrinsic::x86_avx2_psrlv_q_256:
13799       Opcode = ISD::SRL;
13800       break;
13801     case Intrinsic::x86_avx2_psrav_d:
13802     case Intrinsic::x86_avx2_psrav_d_256:
13803       Opcode = ISD::SRA;
13804       break;
13805     }
13806     return DAG.getNode(Opcode, dl, Op.getValueType(),
13807                        Op.getOperand(1), Op.getOperand(2));
13808   }
13809
13810   case Intrinsic::x86_sse2_packssdw_128:
13811   case Intrinsic::x86_sse2_packsswb_128:
13812   case Intrinsic::x86_avx2_packssdw:
13813   case Intrinsic::x86_avx2_packsswb:
13814     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13815                        Op.getOperand(1), Op.getOperand(2));
13816
13817   case Intrinsic::x86_sse2_packuswb_128:
13818   case Intrinsic::x86_sse41_packusdw:
13819   case Intrinsic::x86_avx2_packuswb:
13820   case Intrinsic::x86_avx2_packusdw:
13821     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13822                        Op.getOperand(1), Op.getOperand(2));
13823
13824   case Intrinsic::x86_ssse3_pshuf_b_128:
13825   case Intrinsic::x86_avx2_pshuf_b:
13826     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13827                        Op.getOperand(1), Op.getOperand(2));
13828
13829   case Intrinsic::x86_sse2_pshuf_d:
13830     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13831                        Op.getOperand(1), Op.getOperand(2));
13832
13833   case Intrinsic::x86_sse2_pshufl_w:
13834     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13835                        Op.getOperand(1), Op.getOperand(2));
13836
13837   case Intrinsic::x86_sse2_pshufh_w:
13838     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13839                        Op.getOperand(1), Op.getOperand(2));
13840
13841   case Intrinsic::x86_ssse3_psign_b_128:
13842   case Intrinsic::x86_ssse3_psign_w_128:
13843   case Intrinsic::x86_ssse3_psign_d_128:
13844   case Intrinsic::x86_avx2_psign_b:
13845   case Intrinsic::x86_avx2_psign_w:
13846   case Intrinsic::x86_avx2_psign_d:
13847     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13848                        Op.getOperand(1), Op.getOperand(2));
13849
13850   case Intrinsic::x86_sse41_insertps:
13851     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13852                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13853
13854   case Intrinsic::x86_avx_vperm2f128_ps_256:
13855   case Intrinsic::x86_avx_vperm2f128_pd_256:
13856   case Intrinsic::x86_avx_vperm2f128_si_256:
13857   case Intrinsic::x86_avx2_vperm2i128:
13858     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13859                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13860
13861   case Intrinsic::x86_avx2_permd:
13862   case Intrinsic::x86_avx2_permps:
13863     // Operands intentionally swapped. Mask is last operand to intrinsic,
13864     // but second operand for node/instruction.
13865     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13866                        Op.getOperand(2), Op.getOperand(1));
13867
13868   case Intrinsic::x86_sse_sqrt_ps:
13869   case Intrinsic::x86_sse2_sqrt_pd:
13870   case Intrinsic::x86_avx_sqrt_ps_256:
13871   case Intrinsic::x86_avx_sqrt_pd_256:
13872     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13873
13874   // ptest and testp intrinsics. The intrinsic these come from are designed to
13875   // return an integer value, not just an instruction so lower it to the ptest
13876   // or testp pattern and a setcc for the result.
13877   case Intrinsic::x86_sse41_ptestz:
13878   case Intrinsic::x86_sse41_ptestc:
13879   case Intrinsic::x86_sse41_ptestnzc:
13880   case Intrinsic::x86_avx_ptestz_256:
13881   case Intrinsic::x86_avx_ptestc_256:
13882   case Intrinsic::x86_avx_ptestnzc_256:
13883   case Intrinsic::x86_avx_vtestz_ps:
13884   case Intrinsic::x86_avx_vtestc_ps:
13885   case Intrinsic::x86_avx_vtestnzc_ps:
13886   case Intrinsic::x86_avx_vtestz_pd:
13887   case Intrinsic::x86_avx_vtestc_pd:
13888   case Intrinsic::x86_avx_vtestnzc_pd:
13889   case Intrinsic::x86_avx_vtestz_ps_256:
13890   case Intrinsic::x86_avx_vtestc_ps_256:
13891   case Intrinsic::x86_avx_vtestnzc_ps_256:
13892   case Intrinsic::x86_avx_vtestz_pd_256:
13893   case Intrinsic::x86_avx_vtestc_pd_256:
13894   case Intrinsic::x86_avx_vtestnzc_pd_256: {
13895     bool IsTestPacked = false;
13896     unsigned X86CC;
13897     switch (IntNo) {
13898     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13899     case Intrinsic::x86_avx_vtestz_ps:
13900     case Intrinsic::x86_avx_vtestz_pd:
13901     case Intrinsic::x86_avx_vtestz_ps_256:
13902     case Intrinsic::x86_avx_vtestz_pd_256:
13903       IsTestPacked = true; // Fallthrough
13904     case Intrinsic::x86_sse41_ptestz:
13905     case Intrinsic::x86_avx_ptestz_256:
13906       // ZF = 1
13907       X86CC = X86::COND_E;
13908       break;
13909     case Intrinsic::x86_avx_vtestc_ps:
13910     case Intrinsic::x86_avx_vtestc_pd:
13911     case Intrinsic::x86_avx_vtestc_ps_256:
13912     case Intrinsic::x86_avx_vtestc_pd_256:
13913       IsTestPacked = true; // Fallthrough
13914     case Intrinsic::x86_sse41_ptestc:
13915     case Intrinsic::x86_avx_ptestc_256:
13916       // CF = 1
13917       X86CC = X86::COND_B;
13918       break;
13919     case Intrinsic::x86_avx_vtestnzc_ps:
13920     case Intrinsic::x86_avx_vtestnzc_pd:
13921     case Intrinsic::x86_avx_vtestnzc_ps_256:
13922     case Intrinsic::x86_avx_vtestnzc_pd_256:
13923       IsTestPacked = true; // Fallthrough
13924     case Intrinsic::x86_sse41_ptestnzc:
13925     case Intrinsic::x86_avx_ptestnzc_256:
13926       // ZF and CF = 0
13927       X86CC = X86::COND_A;
13928       break;
13929     }
13930
13931     SDValue LHS = Op.getOperand(1);
13932     SDValue RHS = Op.getOperand(2);
13933     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13934     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13935     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13936     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13937     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13938   }
13939   case Intrinsic::x86_avx512_kortestz_w:
13940   case Intrinsic::x86_avx512_kortestc_w: {
13941     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13942     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13943     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13944     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13945     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13946     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13947     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13948   }
13949
13950   // SSE/AVX shift intrinsics
13951   case Intrinsic::x86_sse2_psll_w:
13952   case Intrinsic::x86_sse2_psll_d:
13953   case Intrinsic::x86_sse2_psll_q:
13954   case Intrinsic::x86_avx2_psll_w:
13955   case Intrinsic::x86_avx2_psll_d:
13956   case Intrinsic::x86_avx2_psll_q:
13957   case Intrinsic::x86_sse2_psrl_w:
13958   case Intrinsic::x86_sse2_psrl_d:
13959   case Intrinsic::x86_sse2_psrl_q:
13960   case Intrinsic::x86_avx2_psrl_w:
13961   case Intrinsic::x86_avx2_psrl_d:
13962   case Intrinsic::x86_avx2_psrl_q:
13963   case Intrinsic::x86_sse2_psra_w:
13964   case Intrinsic::x86_sse2_psra_d:
13965   case Intrinsic::x86_avx2_psra_w:
13966   case Intrinsic::x86_avx2_psra_d: {
13967     unsigned Opcode;
13968     switch (IntNo) {
13969     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13970     case Intrinsic::x86_sse2_psll_w:
13971     case Intrinsic::x86_sse2_psll_d:
13972     case Intrinsic::x86_sse2_psll_q:
13973     case Intrinsic::x86_avx2_psll_w:
13974     case Intrinsic::x86_avx2_psll_d:
13975     case Intrinsic::x86_avx2_psll_q:
13976       Opcode = X86ISD::VSHL;
13977       break;
13978     case Intrinsic::x86_sse2_psrl_w:
13979     case Intrinsic::x86_sse2_psrl_d:
13980     case Intrinsic::x86_sse2_psrl_q:
13981     case Intrinsic::x86_avx2_psrl_w:
13982     case Intrinsic::x86_avx2_psrl_d:
13983     case Intrinsic::x86_avx2_psrl_q:
13984       Opcode = X86ISD::VSRL;
13985       break;
13986     case Intrinsic::x86_sse2_psra_w:
13987     case Intrinsic::x86_sse2_psra_d:
13988     case Intrinsic::x86_avx2_psra_w:
13989     case Intrinsic::x86_avx2_psra_d:
13990       Opcode = X86ISD::VSRA;
13991       break;
13992     }
13993     return DAG.getNode(Opcode, dl, Op.getValueType(),
13994                        Op.getOperand(1), Op.getOperand(2));
13995   }
13996
13997   // SSE/AVX immediate shift intrinsics
13998   case Intrinsic::x86_sse2_pslli_w:
13999   case Intrinsic::x86_sse2_pslli_d:
14000   case Intrinsic::x86_sse2_pslli_q:
14001   case Intrinsic::x86_avx2_pslli_w:
14002   case Intrinsic::x86_avx2_pslli_d:
14003   case Intrinsic::x86_avx2_pslli_q:
14004   case Intrinsic::x86_sse2_psrli_w:
14005   case Intrinsic::x86_sse2_psrli_d:
14006   case Intrinsic::x86_sse2_psrli_q:
14007   case Intrinsic::x86_avx2_psrli_w:
14008   case Intrinsic::x86_avx2_psrli_d:
14009   case Intrinsic::x86_avx2_psrli_q:
14010   case Intrinsic::x86_sse2_psrai_w:
14011   case Intrinsic::x86_sse2_psrai_d:
14012   case Intrinsic::x86_avx2_psrai_w:
14013   case Intrinsic::x86_avx2_psrai_d: {
14014     unsigned Opcode;
14015     switch (IntNo) {
14016     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14017     case Intrinsic::x86_sse2_pslli_w:
14018     case Intrinsic::x86_sse2_pslli_d:
14019     case Intrinsic::x86_sse2_pslli_q:
14020     case Intrinsic::x86_avx2_pslli_w:
14021     case Intrinsic::x86_avx2_pslli_d:
14022     case Intrinsic::x86_avx2_pslli_q:
14023       Opcode = X86ISD::VSHLI;
14024       break;
14025     case Intrinsic::x86_sse2_psrli_w:
14026     case Intrinsic::x86_sse2_psrli_d:
14027     case Intrinsic::x86_sse2_psrli_q:
14028     case Intrinsic::x86_avx2_psrli_w:
14029     case Intrinsic::x86_avx2_psrli_d:
14030     case Intrinsic::x86_avx2_psrli_q:
14031       Opcode = X86ISD::VSRLI;
14032       break;
14033     case Intrinsic::x86_sse2_psrai_w:
14034     case Intrinsic::x86_sse2_psrai_d:
14035     case Intrinsic::x86_avx2_psrai_w:
14036     case Intrinsic::x86_avx2_psrai_d:
14037       Opcode = X86ISD::VSRAI;
14038       break;
14039     }
14040     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14041                                Op.getOperand(1), Op.getOperand(2), DAG);
14042   }
14043
14044   case Intrinsic::x86_sse42_pcmpistria128:
14045   case Intrinsic::x86_sse42_pcmpestria128:
14046   case Intrinsic::x86_sse42_pcmpistric128:
14047   case Intrinsic::x86_sse42_pcmpestric128:
14048   case Intrinsic::x86_sse42_pcmpistrio128:
14049   case Intrinsic::x86_sse42_pcmpestrio128:
14050   case Intrinsic::x86_sse42_pcmpistris128:
14051   case Intrinsic::x86_sse42_pcmpestris128:
14052   case Intrinsic::x86_sse42_pcmpistriz128:
14053   case Intrinsic::x86_sse42_pcmpestriz128: {
14054     unsigned Opcode;
14055     unsigned X86CC;
14056     switch (IntNo) {
14057     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14058     case Intrinsic::x86_sse42_pcmpistria128:
14059       Opcode = X86ISD::PCMPISTRI;
14060       X86CC = X86::COND_A;
14061       break;
14062     case Intrinsic::x86_sse42_pcmpestria128:
14063       Opcode = X86ISD::PCMPESTRI;
14064       X86CC = X86::COND_A;
14065       break;
14066     case Intrinsic::x86_sse42_pcmpistric128:
14067       Opcode = X86ISD::PCMPISTRI;
14068       X86CC = X86::COND_B;
14069       break;
14070     case Intrinsic::x86_sse42_pcmpestric128:
14071       Opcode = X86ISD::PCMPESTRI;
14072       X86CC = X86::COND_B;
14073       break;
14074     case Intrinsic::x86_sse42_pcmpistrio128:
14075       Opcode = X86ISD::PCMPISTRI;
14076       X86CC = X86::COND_O;
14077       break;
14078     case Intrinsic::x86_sse42_pcmpestrio128:
14079       Opcode = X86ISD::PCMPESTRI;
14080       X86CC = X86::COND_O;
14081       break;
14082     case Intrinsic::x86_sse42_pcmpistris128:
14083       Opcode = X86ISD::PCMPISTRI;
14084       X86CC = X86::COND_S;
14085       break;
14086     case Intrinsic::x86_sse42_pcmpestris128:
14087       Opcode = X86ISD::PCMPESTRI;
14088       X86CC = X86::COND_S;
14089       break;
14090     case Intrinsic::x86_sse42_pcmpistriz128:
14091       Opcode = X86ISD::PCMPISTRI;
14092       X86CC = X86::COND_E;
14093       break;
14094     case Intrinsic::x86_sse42_pcmpestriz128:
14095       Opcode = X86ISD::PCMPESTRI;
14096       X86CC = X86::COND_E;
14097       break;
14098     }
14099     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14100     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14101     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14102     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14103                                 DAG.getConstant(X86CC, MVT::i8),
14104                                 SDValue(PCMP.getNode(), 1));
14105     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14106   }
14107
14108   case Intrinsic::x86_sse42_pcmpistri128:
14109   case Intrinsic::x86_sse42_pcmpestri128: {
14110     unsigned Opcode;
14111     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14112       Opcode = X86ISD::PCMPISTRI;
14113     else
14114       Opcode = X86ISD::PCMPESTRI;
14115
14116     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14117     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14118     return DAG.getNode(Opcode, dl, VTs, NewOps);
14119   }
14120   case Intrinsic::x86_fma_vfmadd_ps:
14121   case Intrinsic::x86_fma_vfmadd_pd:
14122   case Intrinsic::x86_fma_vfmsub_ps:
14123   case Intrinsic::x86_fma_vfmsub_pd:
14124   case Intrinsic::x86_fma_vfnmadd_ps:
14125   case Intrinsic::x86_fma_vfnmadd_pd:
14126   case Intrinsic::x86_fma_vfnmsub_ps:
14127   case Intrinsic::x86_fma_vfnmsub_pd:
14128   case Intrinsic::x86_fma_vfmaddsub_ps:
14129   case Intrinsic::x86_fma_vfmaddsub_pd:
14130   case Intrinsic::x86_fma_vfmsubadd_ps:
14131   case Intrinsic::x86_fma_vfmsubadd_pd:
14132   case Intrinsic::x86_fma_vfmadd_ps_256:
14133   case Intrinsic::x86_fma_vfmadd_pd_256:
14134   case Intrinsic::x86_fma_vfmsub_ps_256:
14135   case Intrinsic::x86_fma_vfmsub_pd_256:
14136   case Intrinsic::x86_fma_vfnmadd_ps_256:
14137   case Intrinsic::x86_fma_vfnmadd_pd_256:
14138   case Intrinsic::x86_fma_vfnmsub_ps_256:
14139   case Intrinsic::x86_fma_vfnmsub_pd_256:
14140   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14141   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14142   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14143   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14144   case Intrinsic::x86_fma_vfmadd_ps_512:
14145   case Intrinsic::x86_fma_vfmadd_pd_512:
14146   case Intrinsic::x86_fma_vfmsub_ps_512:
14147   case Intrinsic::x86_fma_vfmsub_pd_512:
14148   case Intrinsic::x86_fma_vfnmadd_ps_512:
14149   case Intrinsic::x86_fma_vfnmadd_pd_512:
14150   case Intrinsic::x86_fma_vfnmsub_ps_512:
14151   case Intrinsic::x86_fma_vfnmsub_pd_512:
14152   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14153   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14154   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14155   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14156     unsigned Opc;
14157     switch (IntNo) {
14158     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14159     case Intrinsic::x86_fma_vfmadd_ps:
14160     case Intrinsic::x86_fma_vfmadd_pd:
14161     case Intrinsic::x86_fma_vfmadd_ps_256:
14162     case Intrinsic::x86_fma_vfmadd_pd_256:
14163     case Intrinsic::x86_fma_vfmadd_ps_512:
14164     case Intrinsic::x86_fma_vfmadd_pd_512:
14165       Opc = X86ISD::FMADD;
14166       break;
14167     case Intrinsic::x86_fma_vfmsub_ps:
14168     case Intrinsic::x86_fma_vfmsub_pd:
14169     case Intrinsic::x86_fma_vfmsub_ps_256:
14170     case Intrinsic::x86_fma_vfmsub_pd_256:
14171     case Intrinsic::x86_fma_vfmsub_ps_512:
14172     case Intrinsic::x86_fma_vfmsub_pd_512:
14173       Opc = X86ISD::FMSUB;
14174       break;
14175     case Intrinsic::x86_fma_vfnmadd_ps:
14176     case Intrinsic::x86_fma_vfnmadd_pd:
14177     case Intrinsic::x86_fma_vfnmadd_ps_256:
14178     case Intrinsic::x86_fma_vfnmadd_pd_256:
14179     case Intrinsic::x86_fma_vfnmadd_ps_512:
14180     case Intrinsic::x86_fma_vfnmadd_pd_512:
14181       Opc = X86ISD::FNMADD;
14182       break;
14183     case Intrinsic::x86_fma_vfnmsub_ps:
14184     case Intrinsic::x86_fma_vfnmsub_pd:
14185     case Intrinsic::x86_fma_vfnmsub_ps_256:
14186     case Intrinsic::x86_fma_vfnmsub_pd_256:
14187     case Intrinsic::x86_fma_vfnmsub_ps_512:
14188     case Intrinsic::x86_fma_vfnmsub_pd_512:
14189       Opc = X86ISD::FNMSUB;
14190       break;
14191     case Intrinsic::x86_fma_vfmaddsub_ps:
14192     case Intrinsic::x86_fma_vfmaddsub_pd:
14193     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14194     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14195     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14196     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14197       Opc = X86ISD::FMADDSUB;
14198       break;
14199     case Intrinsic::x86_fma_vfmsubadd_ps:
14200     case Intrinsic::x86_fma_vfmsubadd_pd:
14201     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14202     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14203     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14204     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14205       Opc = X86ISD::FMSUBADD;
14206       break;
14207     }
14208
14209     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14210                        Op.getOperand(2), Op.getOperand(3));
14211   }
14212   }
14213 }
14214
14215 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14216                               SDValue Src, SDValue Mask, SDValue Base,
14217                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14218                               const X86Subtarget * Subtarget) {
14219   SDLoc dl(Op);
14220   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14221   assert(C && "Invalid scale type");
14222   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14223   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14224                              Index.getSimpleValueType().getVectorNumElements());
14225   SDValue MaskInReg;
14226   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14227   if (MaskC)
14228     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14229   else
14230     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14231   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14232   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14233   SDValue Segment = DAG.getRegister(0, MVT::i32);
14234   if (Src.getOpcode() == ISD::UNDEF)
14235     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14236   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14237   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14238   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14239   return DAG.getMergeValues(RetOps, dl);
14240 }
14241
14242 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14243                                SDValue Src, SDValue Mask, SDValue Base,
14244                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14245   SDLoc dl(Op);
14246   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14247   assert(C && "Invalid scale type");
14248   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14249   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14250   SDValue Segment = DAG.getRegister(0, MVT::i32);
14251   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14252                              Index.getSimpleValueType().getVectorNumElements());
14253   SDValue MaskInReg;
14254   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14255   if (MaskC)
14256     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14257   else
14258     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14259   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14260   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14261   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14262   return SDValue(Res, 1);
14263 }
14264
14265 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14266                                SDValue Mask, SDValue Base, SDValue Index,
14267                                SDValue ScaleOp, SDValue Chain) {
14268   SDLoc dl(Op);
14269   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14270   assert(C && "Invalid scale type");
14271   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14272   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14273   SDValue Segment = DAG.getRegister(0, MVT::i32);
14274   EVT MaskVT =
14275     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14276   SDValue MaskInReg;
14277   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14278   if (MaskC)
14279     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14280   else
14281     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14282   //SDVTList VTs = DAG.getVTList(MVT::Other);
14283   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14284   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14285   return SDValue(Res, 0);
14286 }
14287
14288 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14289 // read performance monitor counters (x86_rdpmc).
14290 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14291                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14292                               SmallVectorImpl<SDValue> &Results) {
14293   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14294   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14295   SDValue LO, HI;
14296
14297   // The ECX register is used to select the index of the performance counter
14298   // to read.
14299   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14300                                    N->getOperand(2));
14301   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14302
14303   // Reads the content of a 64-bit performance counter and returns it in the
14304   // registers EDX:EAX.
14305   if (Subtarget->is64Bit()) {
14306     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14307     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14308                             LO.getValue(2));
14309   } else {
14310     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14311     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14312                             LO.getValue(2));
14313   }
14314   Chain = HI.getValue(1);
14315
14316   if (Subtarget->is64Bit()) {
14317     // The EAX register is loaded with the low-order 32 bits. The EDX register
14318     // is loaded with the supported high-order bits of the counter.
14319     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14320                               DAG.getConstant(32, MVT::i8));
14321     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14322     Results.push_back(Chain);
14323     return;
14324   }
14325
14326   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14327   SDValue Ops[] = { LO, HI };
14328   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14329   Results.push_back(Pair);
14330   Results.push_back(Chain);
14331 }
14332
14333 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14334 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14335 // also used to custom lower READCYCLECOUNTER nodes.
14336 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14337                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14338                               SmallVectorImpl<SDValue> &Results) {
14339   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14340   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14341   SDValue LO, HI;
14342
14343   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14344   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14345   // and the EAX register is loaded with the low-order 32 bits.
14346   if (Subtarget->is64Bit()) {
14347     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14348     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14349                             LO.getValue(2));
14350   } else {
14351     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14352     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14353                             LO.getValue(2));
14354   }
14355   SDValue Chain = HI.getValue(1);
14356
14357   if (Opcode == X86ISD::RDTSCP_DAG) {
14358     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14359
14360     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14361     // the ECX register. Add 'ecx' explicitly to the chain.
14362     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14363                                      HI.getValue(2));
14364     // Explicitly store the content of ECX at the location passed in input
14365     // to the 'rdtscp' intrinsic.
14366     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14367                          MachinePointerInfo(), false, false, 0);
14368   }
14369
14370   if (Subtarget->is64Bit()) {
14371     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14372     // the EAX register is loaded with the low-order 32 bits.
14373     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14374                               DAG.getConstant(32, MVT::i8));
14375     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14376     Results.push_back(Chain);
14377     return;
14378   }
14379
14380   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14381   SDValue Ops[] = { LO, HI };
14382   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14383   Results.push_back(Pair);
14384   Results.push_back(Chain);
14385 }
14386
14387 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14388                                      SelectionDAG &DAG) {
14389   SmallVector<SDValue, 2> Results;
14390   SDLoc DL(Op);
14391   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14392                           Results);
14393   return DAG.getMergeValues(Results, DL);
14394 }
14395
14396 enum IntrinsicType {
14397   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14398 };
14399
14400 struct IntrinsicData {
14401   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14402     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14403   IntrinsicType Type;
14404   unsigned      Opc0;
14405   unsigned      Opc1;
14406 };
14407
14408 std::map < unsigned, IntrinsicData> IntrMap;
14409 static void InitIntinsicsMap() {
14410   static bool Initialized = false;
14411   if (Initialized) 
14412     return;
14413   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14414                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14415   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14416                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14417   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14418                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14419   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14420                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14421   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14422                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14423   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14424                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14425   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14426                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14427   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14428                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14429   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14430                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14431
14432   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14433                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14434   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14435                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14436   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14437                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14438   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14439                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14440   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14441                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14442   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14443                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14444   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14445                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14446   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14447                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14448    
14449   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14450                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14451                                                         X86::VGATHERPF1QPSm)));
14452   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14453                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14454                                                         X86::VGATHERPF1QPDm)));
14455   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14456                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14457                                                         X86::VGATHERPF1DPDm)));
14458   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14459                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14460                                                         X86::VGATHERPF1DPSm)));
14461   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14462                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14463                                                         X86::VSCATTERPF1QPSm)));
14464   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14465                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14466                                                         X86::VSCATTERPF1QPDm)));
14467   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14468                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14469                                                         X86::VSCATTERPF1DPDm)));
14470   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14471                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14472                                                         X86::VSCATTERPF1DPSm)));
14473   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14474                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14475   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14476                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14477   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14478                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14479   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14480                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14481   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14482                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14483   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14484                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14485   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14486                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14487   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14488                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14489   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14490                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14491   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14492                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
14493   Initialized = true;
14494 }
14495
14496 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14497                                       SelectionDAG &DAG) {
14498   InitIntinsicsMap();
14499   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14500   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14501   if (itr == IntrMap.end())
14502     return SDValue();
14503
14504   SDLoc dl(Op);
14505   IntrinsicData Intr = itr->second;
14506   switch(Intr.Type) {
14507   case RDSEED:
14508   case RDRAND: {
14509     // Emit the node with the right value type.
14510     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14511     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14512
14513     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14514     // Otherwise return the value from Rand, which is always 0, casted to i32.
14515     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14516                       DAG.getConstant(1, Op->getValueType(1)),
14517                       DAG.getConstant(X86::COND_B, MVT::i32),
14518                       SDValue(Result.getNode(), 1) };
14519     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14520                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14521                                   Ops);
14522
14523     // Return { result, isValid, chain }.
14524     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14525                        SDValue(Result.getNode(), 2));
14526   }
14527   case GATHER: {
14528   //gather(v1, mask, index, base, scale);
14529     SDValue Chain = Op.getOperand(0);
14530     SDValue Src   = Op.getOperand(2);
14531     SDValue Base  = Op.getOperand(3);
14532     SDValue Index = Op.getOperand(4);
14533     SDValue Mask  = Op.getOperand(5);
14534     SDValue Scale = Op.getOperand(6);
14535     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14536                           Subtarget);
14537   }
14538   case SCATTER: {
14539   //scatter(base, mask, index, v1, scale);
14540     SDValue Chain = Op.getOperand(0);
14541     SDValue Base  = Op.getOperand(2);
14542     SDValue Mask  = Op.getOperand(3);
14543     SDValue Index = Op.getOperand(4);
14544     SDValue Src   = Op.getOperand(5);
14545     SDValue Scale = Op.getOperand(6);
14546     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14547   }
14548   case PREFETCH: {
14549     SDValue Hint = Op.getOperand(6);
14550     unsigned HintVal;
14551     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14552         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14553       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14554     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14555     SDValue Chain = Op.getOperand(0);
14556     SDValue Mask  = Op.getOperand(2);
14557     SDValue Index = Op.getOperand(3);
14558     SDValue Base  = Op.getOperand(4);
14559     SDValue Scale = Op.getOperand(5);
14560     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14561   }
14562   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14563   case RDTSC: {
14564     SmallVector<SDValue, 2> Results;
14565     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14566     return DAG.getMergeValues(Results, dl);
14567   }
14568   // Read Performance Monitoring Counters.
14569   case RDPMC: {
14570     SmallVector<SDValue, 2> Results;
14571     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14572     return DAG.getMergeValues(Results, dl);
14573   }
14574   // XTEST intrinsics.
14575   case XTEST: {
14576     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14577     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14578     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14579                                 DAG.getConstant(X86::COND_NE, MVT::i8),
14580                                 InTrans);
14581     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14582     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14583                        Ret, SDValue(InTrans.getNode(), 1));
14584   }
14585   }
14586   llvm_unreachable("Unknown Intrinsic Type");
14587 }
14588
14589 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14590                                            SelectionDAG &DAG) const {
14591   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14592   MFI->setReturnAddressIsTaken(true);
14593
14594   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14595     return SDValue();
14596
14597   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14598   SDLoc dl(Op);
14599   EVT PtrVT = getPointerTy();
14600
14601   if (Depth > 0) {
14602     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14603     const X86RegisterInfo *RegInfo =
14604       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14605     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14606     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14607                        DAG.getNode(ISD::ADD, dl, PtrVT,
14608                                    FrameAddr, Offset),
14609                        MachinePointerInfo(), false, false, false, 0);
14610   }
14611
14612   // Just load the return address.
14613   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14614   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14615                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14616 }
14617
14618 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14619   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14620   MFI->setFrameAddressIsTaken(true);
14621
14622   EVT VT = Op.getValueType();
14623   SDLoc dl(Op);  // FIXME probably not meaningful
14624   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14625   const X86RegisterInfo *RegInfo =
14626     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14627   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14628   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14629           (FrameReg == X86::EBP && VT == MVT::i32)) &&
14630          "Invalid Frame Register!");
14631   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14632   while (Depth--)
14633     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14634                             MachinePointerInfo(),
14635                             false, false, false, 0);
14636   return FrameAddr;
14637 }
14638
14639 // FIXME? Maybe this could be a TableGen attribute on some registers and
14640 // this table could be generated automatically from RegInfo.
14641 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14642                                               EVT VT) const {
14643   unsigned Reg = StringSwitch<unsigned>(RegName)
14644                        .Case("esp", X86::ESP)
14645                        .Case("rsp", X86::RSP)
14646                        .Default(0);
14647   if (Reg)
14648     return Reg;
14649   report_fatal_error("Invalid register name global variable");
14650 }
14651
14652 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14653                                                      SelectionDAG &DAG) const {
14654   const X86RegisterInfo *RegInfo =
14655     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14656   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14657 }
14658
14659 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14660   SDValue Chain     = Op.getOperand(0);
14661   SDValue Offset    = Op.getOperand(1);
14662   SDValue Handler   = Op.getOperand(2);
14663   SDLoc dl      (Op);
14664
14665   EVT PtrVT = getPointerTy();
14666   const X86RegisterInfo *RegInfo =
14667     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14668   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14669   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14670           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14671          "Invalid Frame Register!");
14672   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14673   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14674
14675   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14676                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14677   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14678   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14679                        false, false, 0);
14680   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14681
14682   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14683                      DAG.getRegister(StoreAddrReg, PtrVT));
14684 }
14685
14686 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14687                                                SelectionDAG &DAG) const {
14688   SDLoc DL(Op);
14689   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14690                      DAG.getVTList(MVT::i32, MVT::Other),
14691                      Op.getOperand(0), Op.getOperand(1));
14692 }
14693
14694 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14695                                                 SelectionDAG &DAG) const {
14696   SDLoc DL(Op);
14697   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14698                      Op.getOperand(0), Op.getOperand(1));
14699 }
14700
14701 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14702   return Op.getOperand(0);
14703 }
14704
14705 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14706                                                 SelectionDAG &DAG) const {
14707   SDValue Root = Op.getOperand(0);
14708   SDValue Trmp = Op.getOperand(1); // trampoline
14709   SDValue FPtr = Op.getOperand(2); // nested function
14710   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14711   SDLoc dl (Op);
14712
14713   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14714   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14715
14716   if (Subtarget->is64Bit()) {
14717     SDValue OutChains[6];
14718
14719     // Large code-model.
14720     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
14721     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14722
14723     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14724     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14725
14726     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14727
14728     // Load the pointer to the nested function into R11.
14729     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14730     SDValue Addr = Trmp;
14731     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14732                                 Addr, MachinePointerInfo(TrmpAddr),
14733                                 false, false, 0);
14734
14735     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14736                        DAG.getConstant(2, MVT::i64));
14737     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14738                                 MachinePointerInfo(TrmpAddr, 2),
14739                                 false, false, 2);
14740
14741     // Load the 'nest' parameter value into R10.
14742     // R10 is specified in X86CallingConv.td
14743     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14744     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14745                        DAG.getConstant(10, MVT::i64));
14746     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14747                                 Addr, MachinePointerInfo(TrmpAddr, 10),
14748                                 false, false, 0);
14749
14750     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14751                        DAG.getConstant(12, MVT::i64));
14752     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14753                                 MachinePointerInfo(TrmpAddr, 12),
14754                                 false, false, 2);
14755
14756     // Jump to the nested function.
14757     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14758     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14759                        DAG.getConstant(20, MVT::i64));
14760     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14761                                 Addr, MachinePointerInfo(TrmpAddr, 20),
14762                                 false, false, 0);
14763
14764     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14765     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14766                        DAG.getConstant(22, MVT::i64));
14767     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14768                                 MachinePointerInfo(TrmpAddr, 22),
14769                                 false, false, 0);
14770
14771     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14772   } else {
14773     const Function *Func =
14774       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14775     CallingConv::ID CC = Func->getCallingConv();
14776     unsigned NestReg;
14777
14778     switch (CC) {
14779     default:
14780       llvm_unreachable("Unsupported calling convention");
14781     case CallingConv::C:
14782     case CallingConv::X86_StdCall: {
14783       // Pass 'nest' parameter in ECX.
14784       // Must be kept in sync with X86CallingConv.td
14785       NestReg = X86::ECX;
14786
14787       // Check that ECX wasn't needed by an 'inreg' parameter.
14788       FunctionType *FTy = Func->getFunctionType();
14789       const AttributeSet &Attrs = Func->getAttributes();
14790
14791       if (!Attrs.isEmpty() && !Func->isVarArg()) {
14792         unsigned InRegCount = 0;
14793         unsigned Idx = 1;
14794
14795         for (FunctionType::param_iterator I = FTy->param_begin(),
14796              E = FTy->param_end(); I != E; ++I, ++Idx)
14797           if (Attrs.hasAttribute(Idx, Attribute::InReg))
14798             // FIXME: should only count parameters that are lowered to integers.
14799             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14800
14801         if (InRegCount > 2) {
14802           report_fatal_error("Nest register in use - reduce number of inreg"
14803                              " parameters!");
14804         }
14805       }
14806       break;
14807     }
14808     case CallingConv::X86_FastCall:
14809     case CallingConv::X86_ThisCall:
14810     case CallingConv::Fast:
14811       // Pass 'nest' parameter in EAX.
14812       // Must be kept in sync with X86CallingConv.td
14813       NestReg = X86::EAX;
14814       break;
14815     }
14816
14817     SDValue OutChains[4];
14818     SDValue Addr, Disp;
14819
14820     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14821                        DAG.getConstant(10, MVT::i32));
14822     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14823
14824     // This is storing the opcode for MOV32ri.
14825     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14826     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14827     OutChains[0] = DAG.getStore(Root, dl,
14828                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14829                                 Trmp, MachinePointerInfo(TrmpAddr),
14830                                 false, false, 0);
14831
14832     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14833                        DAG.getConstant(1, MVT::i32));
14834     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14835                                 MachinePointerInfo(TrmpAddr, 1),
14836                                 false, false, 1);
14837
14838     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14839     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14840                        DAG.getConstant(5, MVT::i32));
14841     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14842                                 MachinePointerInfo(TrmpAddr, 5),
14843                                 false, false, 1);
14844
14845     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14846                        DAG.getConstant(6, MVT::i32));
14847     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14848                                 MachinePointerInfo(TrmpAddr, 6),
14849                                 false, false, 1);
14850
14851     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14852   }
14853 }
14854
14855 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14856                                             SelectionDAG &DAG) const {
14857   /*
14858    The rounding mode is in bits 11:10 of FPSR, and has the following
14859    settings:
14860      00 Round to nearest
14861      01 Round to -inf
14862      10 Round to +inf
14863      11 Round to 0
14864
14865   FLT_ROUNDS, on the other hand, expects the following:
14866     -1 Undefined
14867      0 Round to 0
14868      1 Round to nearest
14869      2 Round to +inf
14870      3 Round to -inf
14871
14872   To perform the conversion, we do:
14873     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14874   */
14875
14876   MachineFunction &MF = DAG.getMachineFunction();
14877   const TargetMachine &TM = MF.getTarget();
14878   const TargetFrameLowering &TFI = *TM.getFrameLowering();
14879   unsigned StackAlignment = TFI.getStackAlignment();
14880   MVT VT = Op.getSimpleValueType();
14881   SDLoc DL(Op);
14882
14883   // Save FP Control Word to stack slot
14884   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14885   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14886
14887   MachineMemOperand *MMO =
14888    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14889                            MachineMemOperand::MOStore, 2, 2);
14890
14891   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14892   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14893                                           DAG.getVTList(MVT::Other),
14894                                           Ops, MVT::i16, MMO);
14895
14896   // Load FP Control Word from stack slot
14897   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14898                             MachinePointerInfo(), false, false, false, 0);
14899
14900   // Transform as necessary
14901   SDValue CWD1 =
14902     DAG.getNode(ISD::SRL, DL, MVT::i16,
14903                 DAG.getNode(ISD::AND, DL, MVT::i16,
14904                             CWD, DAG.getConstant(0x800, MVT::i16)),
14905                 DAG.getConstant(11, MVT::i8));
14906   SDValue CWD2 =
14907     DAG.getNode(ISD::SRL, DL, MVT::i16,
14908                 DAG.getNode(ISD::AND, DL, MVT::i16,
14909                             CWD, DAG.getConstant(0x400, MVT::i16)),
14910                 DAG.getConstant(9, MVT::i8));
14911
14912   SDValue RetVal =
14913     DAG.getNode(ISD::AND, DL, MVT::i16,
14914                 DAG.getNode(ISD::ADD, DL, MVT::i16,
14915                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14916                             DAG.getConstant(1, MVT::i16)),
14917                 DAG.getConstant(3, MVT::i16));
14918
14919   return DAG.getNode((VT.getSizeInBits() < 16 ?
14920                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14921 }
14922
14923 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14924   MVT VT = Op.getSimpleValueType();
14925   EVT OpVT = VT;
14926   unsigned NumBits = VT.getSizeInBits();
14927   SDLoc dl(Op);
14928
14929   Op = Op.getOperand(0);
14930   if (VT == MVT::i8) {
14931     // Zero extend to i32 since there is not an i8 bsr.
14932     OpVT = MVT::i32;
14933     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14934   }
14935
14936   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14937   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14938   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14939
14940   // If src is zero (i.e. bsr sets ZF), returns NumBits.
14941   SDValue Ops[] = {
14942     Op,
14943     DAG.getConstant(NumBits+NumBits-1, OpVT),
14944     DAG.getConstant(X86::COND_E, MVT::i8),
14945     Op.getValue(1)
14946   };
14947   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14948
14949   // Finally xor with NumBits-1.
14950   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14951
14952   if (VT == MVT::i8)
14953     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14954   return Op;
14955 }
14956
14957 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14958   MVT VT = Op.getSimpleValueType();
14959   EVT OpVT = VT;
14960   unsigned NumBits = VT.getSizeInBits();
14961   SDLoc dl(Op);
14962
14963   Op = Op.getOperand(0);
14964   if (VT == MVT::i8) {
14965     // Zero extend to i32 since there is not an i8 bsr.
14966     OpVT = MVT::i32;
14967     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14968   }
14969
14970   // Issue a bsr (scan bits in reverse).
14971   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14972   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14973
14974   // And xor with NumBits-1.
14975   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14976
14977   if (VT == MVT::i8)
14978     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14979   return Op;
14980 }
14981
14982 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14983   MVT VT = Op.getSimpleValueType();
14984   unsigned NumBits = VT.getSizeInBits();
14985   SDLoc dl(Op);
14986   Op = Op.getOperand(0);
14987
14988   // Issue a bsf (scan bits forward) which also sets EFLAGS.
14989   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14990   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14991
14992   // If src is zero (i.e. bsf sets ZF), returns NumBits.
14993   SDValue Ops[] = {
14994     Op,
14995     DAG.getConstant(NumBits, VT),
14996     DAG.getConstant(X86::COND_E, MVT::i8),
14997     Op.getValue(1)
14998   };
14999   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15000 }
15001
15002 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15003 // ones, and then concatenate the result back.
15004 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15005   MVT VT = Op.getSimpleValueType();
15006
15007   assert(VT.is256BitVector() && VT.isInteger() &&
15008          "Unsupported value type for operation");
15009
15010   unsigned NumElems = VT.getVectorNumElements();
15011   SDLoc dl(Op);
15012
15013   // Extract the LHS vectors
15014   SDValue LHS = Op.getOperand(0);
15015   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15016   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15017
15018   // Extract the RHS vectors
15019   SDValue RHS = Op.getOperand(1);
15020   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15021   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15022
15023   MVT EltVT = VT.getVectorElementType();
15024   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15025
15026   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15027                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15028                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15029 }
15030
15031 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15032   assert(Op.getSimpleValueType().is256BitVector() &&
15033          Op.getSimpleValueType().isInteger() &&
15034          "Only handle AVX 256-bit vector integer operation");
15035   return Lower256IntArith(Op, DAG);
15036 }
15037
15038 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15039   assert(Op.getSimpleValueType().is256BitVector() &&
15040          Op.getSimpleValueType().isInteger() &&
15041          "Only handle AVX 256-bit vector integer operation");
15042   return Lower256IntArith(Op, DAG);
15043 }
15044
15045 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15046                         SelectionDAG &DAG) {
15047   SDLoc dl(Op);
15048   MVT VT = Op.getSimpleValueType();
15049
15050   // Decompose 256-bit ops into smaller 128-bit ops.
15051   if (VT.is256BitVector() && !Subtarget->hasInt256())
15052     return Lower256IntArith(Op, DAG);
15053
15054   SDValue A = Op.getOperand(0);
15055   SDValue B = Op.getOperand(1);
15056
15057   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15058   if (VT == MVT::v4i32) {
15059     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15060            "Should not custom lower when pmuldq is available!");
15061
15062     // Extract the odd parts.
15063     static const int UnpackMask[] = { 1, -1, 3, -1 };
15064     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15065     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15066
15067     // Multiply the even parts.
15068     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15069     // Now multiply odd parts.
15070     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15071
15072     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15073     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15074
15075     // Merge the two vectors back together with a shuffle. This expands into 2
15076     // shuffles.
15077     static const int ShufMask[] = { 0, 4, 2, 6 };
15078     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15079   }
15080
15081   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15082          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15083
15084   //  Ahi = psrlqi(a, 32);
15085   //  Bhi = psrlqi(b, 32);
15086   //
15087   //  AloBlo = pmuludq(a, b);
15088   //  AloBhi = pmuludq(a, Bhi);
15089   //  AhiBlo = pmuludq(Ahi, b);
15090
15091   //  AloBhi = psllqi(AloBhi, 32);
15092   //  AhiBlo = psllqi(AhiBlo, 32);
15093   //  return AloBlo + AloBhi + AhiBlo;
15094
15095   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15096   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15097
15098   // Bit cast to 32-bit vectors for MULUDQ
15099   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15100                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15101   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15102   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15103   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15104   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15105
15106   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15107   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15108   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15109
15110   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15111   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15112
15113   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15114   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15115 }
15116
15117 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15118   assert(Subtarget->isTargetWin64() && "Unexpected target");
15119   EVT VT = Op.getValueType();
15120   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15121          "Unexpected return type for lowering");
15122
15123   RTLIB::Libcall LC;
15124   bool isSigned;
15125   switch (Op->getOpcode()) {
15126   default: llvm_unreachable("Unexpected request for libcall!");
15127   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15128   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15129   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15130   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15131   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15132   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15133   }
15134
15135   SDLoc dl(Op);
15136   SDValue InChain = DAG.getEntryNode();
15137
15138   TargetLowering::ArgListTy Args;
15139   TargetLowering::ArgListEntry Entry;
15140   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15141     EVT ArgVT = Op->getOperand(i).getValueType();
15142     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15143            "Unexpected argument type for lowering");
15144     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15145     Entry.Node = StackPtr;
15146     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15147                            false, false, 16);
15148     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15149     Entry.Ty = PointerType::get(ArgTy,0);
15150     Entry.isSExt = false;
15151     Entry.isZExt = false;
15152     Args.push_back(Entry);
15153   }
15154
15155   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15156                                          getPointerTy());
15157
15158   TargetLowering::CallLoweringInfo CLI(DAG);
15159   CLI.setDebugLoc(dl).setChain(InChain)
15160     .setCallee(getLibcallCallingConv(LC),
15161                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15162                Callee, std::move(Args), 0)
15163     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15164
15165   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15166   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15167 }
15168
15169 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15170                              SelectionDAG &DAG) {
15171   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15172   EVT VT = Op0.getValueType();
15173   SDLoc dl(Op);
15174
15175   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15176          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15177
15178   // PMULxD operations multiply each even value (starting at 0) of LHS with
15179   // the related value of RHS and produce a widen result.
15180   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15181   // => <2 x i64> <ae|cg>
15182   //
15183   // In other word, to have all the results, we need to perform two PMULxD:
15184   // 1. one with the even values.
15185   // 2. one with the odd values.
15186   // To achieve #2, with need to place the odd values at an even position.
15187   //
15188   // Place the odd value at an even position (basically, shift all values 1
15189   // step to the left):
15190   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15191   // <a|b|c|d> => <b|undef|d|undef>
15192   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15193   // <e|f|g|h> => <f|undef|h|undef>
15194   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15195
15196   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15197   // ints.
15198   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15199   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15200   unsigned Opcode =
15201       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15202   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15203   // => <2 x i64> <ae|cg>
15204   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15205                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15206   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15207   // => <2 x i64> <bf|dh>
15208   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15209                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15210
15211   // Shuffle it back into the right order.
15212   // The internal representation is big endian.
15213   // In other words, a i64 bitcasted to 2 x i32 has its high part at index 0
15214   // and its low part at index 1.
15215   // Moreover, we have: Mul1 = <ae|cg> ; Mul2 = <bf|dh>
15216   // Vector index                0 1   ;          2 3
15217   // We want      <ae|bf|cg|dh>
15218   // Vector index   0  2  1  3
15219   // Since each element is seen as 2 x i32, we get:
15220   // high_mask[i] = 2 x vector_index[i]
15221   // low_mask[i] = 2 x vector_index[i] + 1
15222   // where vector_index = {0, Size/2, 1, Size/2 + 1, ...,
15223   //                       Size/2 - 1, Size/2 + Size/2 - 1}
15224   // where Size is the number of element of the final vector.
15225   SDValue Highs, Lows;
15226   if (VT == MVT::v8i32) {
15227     const int HighMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15228     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15229     const int LowMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15230     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15231   } else {
15232     const int HighMask[] = {0, 4, 2, 6};
15233     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15234     const int LowMask[] = {1, 5, 3, 7};
15235     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15236   }
15237
15238   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15239   // unsigned multiply.
15240   if (IsSigned && !Subtarget->hasSSE41()) {
15241     SDValue ShAmt =
15242         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15243     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15244                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15245     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15246                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15247
15248     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15249     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15250   }
15251
15252   // The low part of a MUL_LOHI is supposed to be the first value and the
15253   // high part the second value.
15254   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Lows, Highs);
15255 }
15256
15257 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15258                                          const X86Subtarget *Subtarget) {
15259   MVT VT = Op.getSimpleValueType();
15260   SDLoc dl(Op);
15261   SDValue R = Op.getOperand(0);
15262   SDValue Amt = Op.getOperand(1);
15263
15264   // Optimize shl/srl/sra with constant shift amount.
15265   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15266     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15267       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15268
15269       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15270           (Subtarget->hasInt256() &&
15271            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15272           (Subtarget->hasAVX512() &&
15273            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15274         if (Op.getOpcode() == ISD::SHL)
15275           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15276                                             DAG);
15277         if (Op.getOpcode() == ISD::SRL)
15278           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15279                                             DAG);
15280         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15281           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15282                                             DAG);
15283       }
15284
15285       if (VT == MVT::v16i8) {
15286         if (Op.getOpcode() == ISD::SHL) {
15287           // Make a large shift.
15288           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15289                                                    MVT::v8i16, R, ShiftAmt,
15290                                                    DAG);
15291           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15292           // Zero out the rightmost bits.
15293           SmallVector<SDValue, 16> V(16,
15294                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15295                                                      MVT::i8));
15296           return DAG.getNode(ISD::AND, dl, VT, SHL,
15297                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15298         }
15299         if (Op.getOpcode() == ISD::SRL) {
15300           // Make a large shift.
15301           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15302                                                    MVT::v8i16, R, ShiftAmt,
15303                                                    DAG);
15304           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15305           // Zero out the leftmost bits.
15306           SmallVector<SDValue, 16> V(16,
15307                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15308                                                      MVT::i8));
15309           return DAG.getNode(ISD::AND, dl, VT, SRL,
15310                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15311         }
15312         if (Op.getOpcode() == ISD::SRA) {
15313           if (ShiftAmt == 7) {
15314             // R s>> 7  ===  R s< 0
15315             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15316             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15317           }
15318
15319           // R s>> a === ((R u>> a) ^ m) - m
15320           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15321           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15322                                                          MVT::i8));
15323           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15324           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15325           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15326           return Res;
15327         }
15328         llvm_unreachable("Unknown shift opcode.");
15329       }
15330
15331       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15332         if (Op.getOpcode() == ISD::SHL) {
15333           // Make a large shift.
15334           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15335                                                    MVT::v16i16, R, ShiftAmt,
15336                                                    DAG);
15337           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15338           // Zero out the rightmost bits.
15339           SmallVector<SDValue, 32> V(32,
15340                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15341                                                      MVT::i8));
15342           return DAG.getNode(ISD::AND, dl, VT, SHL,
15343                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15344         }
15345         if (Op.getOpcode() == ISD::SRL) {
15346           // Make a large shift.
15347           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15348                                                    MVT::v16i16, R, ShiftAmt,
15349                                                    DAG);
15350           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15351           // Zero out the leftmost bits.
15352           SmallVector<SDValue, 32> V(32,
15353                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15354                                                      MVT::i8));
15355           return DAG.getNode(ISD::AND, dl, VT, SRL,
15356                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15357         }
15358         if (Op.getOpcode() == ISD::SRA) {
15359           if (ShiftAmt == 7) {
15360             // R s>> 7  ===  R s< 0
15361             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15362             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15363           }
15364
15365           // R s>> a === ((R u>> a) ^ m) - m
15366           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15367           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15368                                                          MVT::i8));
15369           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15370           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15371           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15372           return Res;
15373         }
15374         llvm_unreachable("Unknown shift opcode.");
15375       }
15376     }
15377   }
15378
15379   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15380   if (!Subtarget->is64Bit() &&
15381       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15382       Amt.getOpcode() == ISD::BITCAST &&
15383       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15384     Amt = Amt.getOperand(0);
15385     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15386                      VT.getVectorNumElements();
15387     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15388     uint64_t ShiftAmt = 0;
15389     for (unsigned i = 0; i != Ratio; ++i) {
15390       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15391       if (!C)
15392         return SDValue();
15393       // 6 == Log2(64)
15394       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15395     }
15396     // Check remaining shift amounts.
15397     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15398       uint64_t ShAmt = 0;
15399       for (unsigned j = 0; j != Ratio; ++j) {
15400         ConstantSDNode *C =
15401           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15402         if (!C)
15403           return SDValue();
15404         // 6 == Log2(64)
15405         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15406       }
15407       if (ShAmt != ShiftAmt)
15408         return SDValue();
15409     }
15410     switch (Op.getOpcode()) {
15411     default:
15412       llvm_unreachable("Unknown shift opcode!");
15413     case ISD::SHL:
15414       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15415                                         DAG);
15416     case ISD::SRL:
15417       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15418                                         DAG);
15419     case ISD::SRA:
15420       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15421                                         DAG);
15422     }
15423   }
15424
15425   return SDValue();
15426 }
15427
15428 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15429                                         const X86Subtarget* Subtarget) {
15430   MVT VT = Op.getSimpleValueType();
15431   SDLoc dl(Op);
15432   SDValue R = Op.getOperand(0);
15433   SDValue Amt = Op.getOperand(1);
15434
15435   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15436       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15437       (Subtarget->hasInt256() &&
15438        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15439         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15440        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15441     SDValue BaseShAmt;
15442     EVT EltVT = VT.getVectorElementType();
15443
15444     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15445       unsigned NumElts = VT.getVectorNumElements();
15446       unsigned i, j;
15447       for (i = 0; i != NumElts; ++i) {
15448         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15449           continue;
15450         break;
15451       }
15452       for (j = i; j != NumElts; ++j) {
15453         SDValue Arg = Amt.getOperand(j);
15454         if (Arg.getOpcode() == ISD::UNDEF) continue;
15455         if (Arg != Amt.getOperand(i))
15456           break;
15457       }
15458       if (i != NumElts && j == NumElts)
15459         BaseShAmt = Amt.getOperand(i);
15460     } else {
15461       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15462         Amt = Amt.getOperand(0);
15463       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15464                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15465         SDValue InVec = Amt.getOperand(0);
15466         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15467           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15468           unsigned i = 0;
15469           for (; i != NumElts; ++i) {
15470             SDValue Arg = InVec.getOperand(i);
15471             if (Arg.getOpcode() == ISD::UNDEF) continue;
15472             BaseShAmt = Arg;
15473             break;
15474           }
15475         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15476            if (ConstantSDNode *C =
15477                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15478              unsigned SplatIdx =
15479                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15480              if (C->getZExtValue() == SplatIdx)
15481                BaseShAmt = InVec.getOperand(1);
15482            }
15483         }
15484         if (!BaseShAmt.getNode())
15485           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15486                                   DAG.getIntPtrConstant(0));
15487       }
15488     }
15489
15490     if (BaseShAmt.getNode()) {
15491       if (EltVT.bitsGT(MVT::i32))
15492         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15493       else if (EltVT.bitsLT(MVT::i32))
15494         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15495
15496       switch (Op.getOpcode()) {
15497       default:
15498         llvm_unreachable("Unknown shift opcode!");
15499       case ISD::SHL:
15500         switch (VT.SimpleTy) {
15501         default: return SDValue();
15502         case MVT::v2i64:
15503         case MVT::v4i32:
15504         case MVT::v8i16:
15505         case MVT::v4i64:
15506         case MVT::v8i32:
15507         case MVT::v16i16:
15508         case MVT::v16i32:
15509         case MVT::v8i64:
15510           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15511         }
15512       case ISD::SRA:
15513         switch (VT.SimpleTy) {
15514         default: return SDValue();
15515         case MVT::v4i32:
15516         case MVT::v8i16:
15517         case MVT::v8i32:
15518         case MVT::v16i16:
15519         case MVT::v16i32:
15520         case MVT::v8i64:
15521           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15522         }
15523       case ISD::SRL:
15524         switch (VT.SimpleTy) {
15525         default: return SDValue();
15526         case MVT::v2i64:
15527         case MVT::v4i32:
15528         case MVT::v8i16:
15529         case MVT::v4i64:
15530         case MVT::v8i32:
15531         case MVT::v16i16:
15532         case MVT::v16i32:
15533         case MVT::v8i64:
15534           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15535         }
15536       }
15537     }
15538   }
15539
15540   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15541   if (!Subtarget->is64Bit() &&
15542       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15543       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15544       Amt.getOpcode() == ISD::BITCAST &&
15545       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15546     Amt = Amt.getOperand(0);
15547     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15548                      VT.getVectorNumElements();
15549     std::vector<SDValue> Vals(Ratio);
15550     for (unsigned i = 0; i != Ratio; ++i)
15551       Vals[i] = Amt.getOperand(i);
15552     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15553       for (unsigned j = 0; j != Ratio; ++j)
15554         if (Vals[j] != Amt.getOperand(i + j))
15555           return SDValue();
15556     }
15557     switch (Op.getOpcode()) {
15558     default:
15559       llvm_unreachable("Unknown shift opcode!");
15560     case ISD::SHL:
15561       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15562     case ISD::SRL:
15563       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15564     case ISD::SRA:
15565       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15566     }
15567   }
15568
15569   return SDValue();
15570 }
15571
15572 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15573                           SelectionDAG &DAG) {
15574   MVT VT = Op.getSimpleValueType();
15575   SDLoc dl(Op);
15576   SDValue R = Op.getOperand(0);
15577   SDValue Amt = Op.getOperand(1);
15578   SDValue V;
15579
15580   assert(VT.isVector() && "Custom lowering only for vector shifts!");
15581   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15582
15583   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15584   if (V.getNode())
15585     return V;
15586
15587   V = LowerScalarVariableShift(Op, DAG, Subtarget);
15588   if (V.getNode())
15589       return V;
15590
15591   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15592     return Op;
15593   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15594   if (Subtarget->hasInt256()) {
15595     if (Op.getOpcode() == ISD::SRL &&
15596         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15597          VT == MVT::v4i64 || VT == MVT::v8i32))
15598       return Op;
15599     if (Op.getOpcode() == ISD::SHL &&
15600         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15601          VT == MVT::v4i64 || VT == MVT::v8i32))
15602       return Op;
15603     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15604       return Op;
15605   }
15606
15607   // If possible, lower this packed shift into a vector multiply instead of
15608   // expanding it into a sequence of scalar shifts.
15609   // Do this only if the vector shift count is a constant build_vector.
15610   if (Op.getOpcode() == ISD::SHL && 
15611       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15612        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15613       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15614     SmallVector<SDValue, 8> Elts;
15615     EVT SVT = VT.getScalarType();
15616     unsigned SVTBits = SVT.getSizeInBits();
15617     const APInt &One = APInt(SVTBits, 1);
15618     unsigned NumElems = VT.getVectorNumElements();
15619
15620     for (unsigned i=0; i !=NumElems; ++i) {
15621       SDValue Op = Amt->getOperand(i);
15622       if (Op->getOpcode() == ISD::UNDEF) {
15623         Elts.push_back(Op);
15624         continue;
15625       }
15626
15627       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15628       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15629       uint64_t ShAmt = C.getZExtValue();
15630       if (ShAmt >= SVTBits) {
15631         Elts.push_back(DAG.getUNDEF(SVT));
15632         continue;
15633       }
15634       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15635     }
15636     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15637     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15638   }
15639
15640   // Lower SHL with variable shift amount.
15641   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15642     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15643
15644     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15645     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15646     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15647     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15648   }
15649
15650   // If possible, lower this shift as a sequence of two shifts by
15651   // constant plus a MOVSS/MOVSD instead of scalarizing it.
15652   // Example:
15653   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15654   //
15655   // Could be rewritten as:
15656   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15657   //
15658   // The advantage is that the two shifts from the example would be
15659   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15660   // the vector shift into four scalar shifts plus four pairs of vector
15661   // insert/extract.
15662   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15663       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15664     unsigned TargetOpcode = X86ISD::MOVSS;
15665     bool CanBeSimplified;
15666     // The splat value for the first packed shift (the 'X' from the example).
15667     SDValue Amt1 = Amt->getOperand(0);
15668     // The splat value for the second packed shift (the 'Y' from the example).
15669     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15670                                         Amt->getOperand(2);
15671
15672     // See if it is possible to replace this node with a sequence of
15673     // two shifts followed by a MOVSS/MOVSD
15674     if (VT == MVT::v4i32) {
15675       // Check if it is legal to use a MOVSS.
15676       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15677                         Amt2 == Amt->getOperand(3);
15678       if (!CanBeSimplified) {
15679         // Otherwise, check if we can still simplify this node using a MOVSD.
15680         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15681                           Amt->getOperand(2) == Amt->getOperand(3);
15682         TargetOpcode = X86ISD::MOVSD;
15683         Amt2 = Amt->getOperand(2);
15684       }
15685     } else {
15686       // Do similar checks for the case where the machine value type
15687       // is MVT::v8i16.
15688       CanBeSimplified = Amt1 == Amt->getOperand(1);
15689       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15690         CanBeSimplified = Amt2 == Amt->getOperand(i);
15691
15692       if (!CanBeSimplified) {
15693         TargetOpcode = X86ISD::MOVSD;
15694         CanBeSimplified = true;
15695         Amt2 = Amt->getOperand(4);
15696         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15697           CanBeSimplified = Amt1 == Amt->getOperand(i);
15698         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15699           CanBeSimplified = Amt2 == Amt->getOperand(j);
15700       }
15701     }
15702     
15703     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15704         isa<ConstantSDNode>(Amt2)) {
15705       // Replace this node with two shifts followed by a MOVSS/MOVSD.
15706       EVT CastVT = MVT::v4i32;
15707       SDValue Splat1 = 
15708         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15709       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15710       SDValue Splat2 = 
15711         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15712       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15713       if (TargetOpcode == X86ISD::MOVSD)
15714         CastVT = MVT::v2i64;
15715       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15716       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15717       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15718                                             BitCast1, DAG);
15719       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15720     }
15721   }
15722
15723   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15724     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15725
15726     // a = a << 5;
15727     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15728     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15729
15730     // Turn 'a' into a mask suitable for VSELECT
15731     SDValue VSelM = DAG.getConstant(0x80, VT);
15732     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15733     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15734
15735     SDValue CM1 = DAG.getConstant(0x0f, VT);
15736     SDValue CM2 = DAG.getConstant(0x3f, VT);
15737
15738     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15739     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15740     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15741     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15742     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15743
15744     // a += a
15745     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15746     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15747     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15748
15749     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15750     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15751     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15752     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15753     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15754
15755     // a += a
15756     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15757     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15758     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15759
15760     // return VSELECT(r, r+r, a);
15761     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15762                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15763     return R;
15764   }
15765
15766   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15767   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15768   // solution better.
15769   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15770     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15771     unsigned ExtOpc =
15772         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15773     R = DAG.getNode(ExtOpc, dl, NewVT, R);
15774     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15775     return DAG.getNode(ISD::TRUNCATE, dl, VT,
15776                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15777     }
15778
15779   // Decompose 256-bit shifts into smaller 128-bit shifts.
15780   if (VT.is256BitVector()) {
15781     unsigned NumElems = VT.getVectorNumElements();
15782     MVT EltVT = VT.getVectorElementType();
15783     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15784
15785     // Extract the two vectors
15786     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15787     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15788
15789     // Recreate the shift amount vectors
15790     SDValue Amt1, Amt2;
15791     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15792       // Constant shift amount
15793       SmallVector<SDValue, 4> Amt1Csts;
15794       SmallVector<SDValue, 4> Amt2Csts;
15795       for (unsigned i = 0; i != NumElems/2; ++i)
15796         Amt1Csts.push_back(Amt->getOperand(i));
15797       for (unsigned i = NumElems/2; i != NumElems; ++i)
15798         Amt2Csts.push_back(Amt->getOperand(i));
15799
15800       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15801       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15802     } else {
15803       // Variable shift amount
15804       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15805       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15806     }
15807
15808     // Issue new vector shifts for the smaller types
15809     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15810     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15811
15812     // Concatenate the result back
15813     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15814   }
15815
15816   return SDValue();
15817 }
15818
15819 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15820   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15821   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15822   // looks for this combo and may remove the "setcc" instruction if the "setcc"
15823   // has only one use.
15824   SDNode *N = Op.getNode();
15825   SDValue LHS = N->getOperand(0);
15826   SDValue RHS = N->getOperand(1);
15827   unsigned BaseOp = 0;
15828   unsigned Cond = 0;
15829   SDLoc DL(Op);
15830   switch (Op.getOpcode()) {
15831   default: llvm_unreachable("Unknown ovf instruction!");
15832   case ISD::SADDO:
15833     // A subtract of one will be selected as a INC. Note that INC doesn't
15834     // set CF, so we can't do this for UADDO.
15835     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15836       if (C->isOne()) {
15837         BaseOp = X86ISD::INC;
15838         Cond = X86::COND_O;
15839         break;
15840       }
15841     BaseOp = X86ISD::ADD;
15842     Cond = X86::COND_O;
15843     break;
15844   case ISD::UADDO:
15845     BaseOp = X86ISD::ADD;
15846     Cond = X86::COND_B;
15847     break;
15848   case ISD::SSUBO:
15849     // A subtract of one will be selected as a DEC. Note that DEC doesn't
15850     // set CF, so we can't do this for USUBO.
15851     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15852       if (C->isOne()) {
15853         BaseOp = X86ISD::DEC;
15854         Cond = X86::COND_O;
15855         break;
15856       }
15857     BaseOp = X86ISD::SUB;
15858     Cond = X86::COND_O;
15859     break;
15860   case ISD::USUBO:
15861     BaseOp = X86ISD::SUB;
15862     Cond = X86::COND_B;
15863     break;
15864   case ISD::SMULO:
15865     BaseOp = X86ISD::SMUL;
15866     Cond = X86::COND_O;
15867     break;
15868   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15869     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15870                                  MVT::i32);
15871     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15872
15873     SDValue SetCC =
15874       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15875                   DAG.getConstant(X86::COND_O, MVT::i32),
15876                   SDValue(Sum.getNode(), 2));
15877
15878     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15879   }
15880   }
15881
15882   // Also sets EFLAGS.
15883   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15884   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15885
15886   SDValue SetCC =
15887     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15888                 DAG.getConstant(Cond, MVT::i32),
15889                 SDValue(Sum.getNode(), 1));
15890
15891   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15892 }
15893
15894 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15895                                                   SelectionDAG &DAG) const {
15896   SDLoc dl(Op);
15897   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15898   MVT VT = Op.getSimpleValueType();
15899
15900   if (!Subtarget->hasSSE2() || !VT.isVector())
15901     return SDValue();
15902
15903   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15904                       ExtraVT.getScalarType().getSizeInBits();
15905
15906   switch (VT.SimpleTy) {
15907     default: return SDValue();
15908     case MVT::v8i32:
15909     case MVT::v16i16:
15910       if (!Subtarget->hasFp256())
15911         return SDValue();
15912       if (!Subtarget->hasInt256()) {
15913         // needs to be split
15914         unsigned NumElems = VT.getVectorNumElements();
15915
15916         // Extract the LHS vectors
15917         SDValue LHS = Op.getOperand(0);
15918         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15919         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15920
15921         MVT EltVT = VT.getVectorElementType();
15922         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15923
15924         EVT ExtraEltVT = ExtraVT.getVectorElementType();
15925         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15926         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15927                                    ExtraNumElems/2);
15928         SDValue Extra = DAG.getValueType(ExtraVT);
15929
15930         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15931         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15932
15933         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15934       }
15935       // fall through
15936     case MVT::v4i32:
15937     case MVT::v8i16: {
15938       SDValue Op0 = Op.getOperand(0);
15939       SDValue Op00 = Op0.getOperand(0);
15940       SDValue Tmp1;
15941       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15942       if (Op0.getOpcode() == ISD::BITCAST &&
15943           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15944         // (sext (vzext x)) -> (vsext x)
15945         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15946         if (Tmp1.getNode()) {
15947           EVT ExtraEltVT = ExtraVT.getVectorElementType();
15948           // This folding is only valid when the in-reg type is a vector of i8,
15949           // i16, or i32.
15950           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15951               ExtraEltVT == MVT::i32) {
15952             SDValue Tmp1Op0 = Tmp1.getOperand(0);
15953             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15954                    "This optimization is invalid without a VZEXT.");
15955             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15956           }
15957           Op0 = Tmp1;
15958         }
15959       }
15960
15961       // If the above didn't work, then just use Shift-Left + Shift-Right.
15962       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15963                                         DAG);
15964       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15965                                         DAG);
15966     }
15967   }
15968 }
15969
15970 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15971                                  SelectionDAG &DAG) {
15972   SDLoc dl(Op);
15973   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15974     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15975   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15976     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15977
15978   // The only fence that needs an instruction is a sequentially-consistent
15979   // cross-thread fence.
15980   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15981     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15982     // no-sse2). There isn't any reason to disable it if the target processor
15983     // supports it.
15984     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15985       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15986
15987     SDValue Chain = Op.getOperand(0);
15988     SDValue Zero = DAG.getConstant(0, MVT::i32);
15989     SDValue Ops[] = {
15990       DAG.getRegister(X86::ESP, MVT::i32), // Base
15991       DAG.getTargetConstant(1, MVT::i8),   // Scale
15992       DAG.getRegister(0, MVT::i32),        // Index
15993       DAG.getTargetConstant(0, MVT::i32),  // Disp
15994       DAG.getRegister(0, MVT::i32),        // Segment.
15995       Zero,
15996       Chain
15997     };
15998     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15999     return SDValue(Res, 0);
16000   }
16001
16002   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16003   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16004 }
16005
16006 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16007                              SelectionDAG &DAG) {
16008   MVT T = Op.getSimpleValueType();
16009   SDLoc DL(Op);
16010   unsigned Reg = 0;
16011   unsigned size = 0;
16012   switch(T.SimpleTy) {
16013   default: llvm_unreachable("Invalid value type!");
16014   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16015   case MVT::i16: Reg = X86::AX;  size = 2; break;
16016   case MVT::i32: Reg = X86::EAX; size = 4; break;
16017   case MVT::i64:
16018     assert(Subtarget->is64Bit() && "Node not type legal!");
16019     Reg = X86::RAX; size = 8;
16020     break;
16021   }
16022   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16023                                   Op.getOperand(2), SDValue());
16024   SDValue Ops[] = { cpIn.getValue(0),
16025                     Op.getOperand(1),
16026                     Op.getOperand(3),
16027                     DAG.getTargetConstant(size, MVT::i8),
16028                     cpIn.getValue(1) };
16029   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16030   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16031   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16032                                            Ops, T, MMO);
16033
16034   SDValue cpOut =
16035     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16036   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16037                                       MVT::i32, cpOut.getValue(2));
16038   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16039                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16040
16041   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16042   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16043   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16044   return SDValue();
16045 }
16046
16047 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16048                             SelectionDAG &DAG) {
16049   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16050   MVT DstVT = Op.getSimpleValueType();
16051
16052   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16053     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16054     if (DstVT != MVT::f64)
16055       // This conversion needs to be expanded.
16056       return SDValue();
16057
16058     SDValue InVec = Op->getOperand(0);
16059     SDLoc dl(Op);
16060     unsigned NumElts = SrcVT.getVectorNumElements();
16061     EVT SVT = SrcVT.getVectorElementType();
16062
16063     // Widen the vector in input in the case of MVT::v2i32.
16064     // Example: from MVT::v2i32 to MVT::v4i32.
16065     SmallVector<SDValue, 16> Elts;
16066     for (unsigned i = 0, e = NumElts; i != e; ++i)
16067       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16068                                  DAG.getIntPtrConstant(i)));
16069
16070     // Explicitly mark the extra elements as Undef.
16071     SDValue Undef = DAG.getUNDEF(SVT);
16072     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16073       Elts.push_back(Undef);
16074
16075     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16076     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16077     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16078     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16079                        DAG.getIntPtrConstant(0));
16080   }
16081
16082   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16083          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16084   assert((DstVT == MVT::i64 ||
16085           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16086          "Unexpected custom BITCAST");
16087   // i64 <=> MMX conversions are Legal.
16088   if (SrcVT==MVT::i64 && DstVT.isVector())
16089     return Op;
16090   if (DstVT==MVT::i64 && SrcVT.isVector())
16091     return Op;
16092   // MMX <=> MMX conversions are Legal.
16093   if (SrcVT.isVector() && DstVT.isVector())
16094     return Op;
16095   // All other conversions need to be expanded.
16096   return SDValue();
16097 }
16098
16099 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16100   SDNode *Node = Op.getNode();
16101   SDLoc dl(Node);
16102   EVT T = Node->getValueType(0);
16103   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16104                               DAG.getConstant(0, T), Node->getOperand(2));
16105   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16106                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16107                        Node->getOperand(0),
16108                        Node->getOperand(1), negOp,
16109                        cast<AtomicSDNode>(Node)->getMemOperand(),
16110                        cast<AtomicSDNode>(Node)->getOrdering(),
16111                        cast<AtomicSDNode>(Node)->getSynchScope());
16112 }
16113
16114 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16115   SDNode *Node = Op.getNode();
16116   SDLoc dl(Node);
16117   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16118
16119   // Convert seq_cst store -> xchg
16120   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16121   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16122   //        (The only way to get a 16-byte store is cmpxchg16b)
16123   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16124   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16125       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16126     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16127                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16128                                  Node->getOperand(0),
16129                                  Node->getOperand(1), Node->getOperand(2),
16130                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16131                                  cast<AtomicSDNode>(Node)->getOrdering(),
16132                                  cast<AtomicSDNode>(Node)->getSynchScope());
16133     return Swap.getValue(1);
16134   }
16135   // Other atomic stores have a simple pattern.
16136   return Op;
16137 }
16138
16139 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16140   EVT VT = Op.getNode()->getSimpleValueType(0);
16141
16142   // Let legalize expand this if it isn't a legal type yet.
16143   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16144     return SDValue();
16145
16146   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16147
16148   unsigned Opc;
16149   bool ExtraOp = false;
16150   switch (Op.getOpcode()) {
16151   default: llvm_unreachable("Invalid code");
16152   case ISD::ADDC: Opc = X86ISD::ADD; break;
16153   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16154   case ISD::SUBC: Opc = X86ISD::SUB; break;
16155   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16156   }
16157
16158   if (!ExtraOp)
16159     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16160                        Op.getOperand(1));
16161   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16162                      Op.getOperand(1), Op.getOperand(2));
16163 }
16164
16165 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16166                             SelectionDAG &DAG) {
16167   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16168
16169   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16170   // which returns the values as { float, float } (in XMM0) or
16171   // { double, double } (which is returned in XMM0, XMM1).
16172   SDLoc dl(Op);
16173   SDValue Arg = Op.getOperand(0);
16174   EVT ArgVT = Arg.getValueType();
16175   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16176
16177   TargetLowering::ArgListTy Args;
16178   TargetLowering::ArgListEntry Entry;
16179
16180   Entry.Node = Arg;
16181   Entry.Ty = ArgTy;
16182   Entry.isSExt = false;
16183   Entry.isZExt = false;
16184   Args.push_back(Entry);
16185
16186   bool isF64 = ArgVT == MVT::f64;
16187   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16188   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16189   // the results are returned via SRet in memory.
16190   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16191   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16192   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16193
16194   Type *RetTy = isF64
16195     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16196     : (Type*)VectorType::get(ArgTy, 4);
16197
16198   TargetLowering::CallLoweringInfo CLI(DAG);
16199   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16200     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16201
16202   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16203
16204   if (isF64)
16205     // Returned in xmm0 and xmm1.
16206     return CallResult.first;
16207
16208   // Returned in bits 0:31 and 32:64 xmm0.
16209   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16210                                CallResult.first, DAG.getIntPtrConstant(0));
16211   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16212                                CallResult.first, DAG.getIntPtrConstant(1));
16213   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16214   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16215 }
16216
16217 /// LowerOperation - Provide custom lowering hooks for some operations.
16218 ///
16219 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16220   switch (Op.getOpcode()) {
16221   default: llvm_unreachable("Should not custom lower this!");
16222   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16223   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16224   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16225     return LowerCMP_SWAP(Op, Subtarget, DAG);
16226   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16227   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16228   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16229   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16230   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16231   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16232   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16233   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16234   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16235   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16236   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16237   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16238   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16239   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16240   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16241   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16242   case ISD::SHL_PARTS:
16243   case ISD::SRA_PARTS:
16244   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16245   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16246   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16247   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16248   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16249   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16250   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16251   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16252   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16253   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16254   case ISD::FABS:               return LowerFABS(Op, DAG);
16255   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16256   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16257   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16258   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16259   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16260   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16261   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16262   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16263   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16264   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16265   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16266   case ISD::INTRINSIC_VOID:
16267   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16268   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16269   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16270   case ISD::FRAME_TO_ARGS_OFFSET:
16271                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16272   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16273   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16274   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16275   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16276   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16277   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16278   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16279   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16280   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16281   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16282   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16283   case ISD::UMUL_LOHI:
16284   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16285   case ISD::SRA:
16286   case ISD::SRL:
16287   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16288   case ISD::SADDO:
16289   case ISD::UADDO:
16290   case ISD::SSUBO:
16291   case ISD::USUBO:
16292   case ISD::SMULO:
16293   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16294   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16295   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16296   case ISD::ADDC:
16297   case ISD::ADDE:
16298   case ISD::SUBC:
16299   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16300   case ISD::ADD:                return LowerADD(Op, DAG);
16301   case ISD::SUB:                return LowerSUB(Op, DAG);
16302   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16303   }
16304 }
16305
16306 static void ReplaceATOMIC_LOAD(SDNode *Node,
16307                                SmallVectorImpl<SDValue> &Results,
16308                                SelectionDAG &DAG) {
16309   SDLoc dl(Node);
16310   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16311
16312   // Convert wide load -> cmpxchg8b/cmpxchg16b
16313   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16314   //        (The only way to get a 16-byte load is cmpxchg16b)
16315   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16316   SDValue Zero = DAG.getConstant(0, VT);
16317   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16318   SDValue Swap =
16319       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16320                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16321                            cast<AtomicSDNode>(Node)->getMemOperand(),
16322                            cast<AtomicSDNode>(Node)->getOrdering(),
16323                            cast<AtomicSDNode>(Node)->getOrdering(),
16324                            cast<AtomicSDNode>(Node)->getSynchScope());
16325   Results.push_back(Swap.getValue(0));
16326   Results.push_back(Swap.getValue(2));
16327 }
16328
16329 /// ReplaceNodeResults - Replace a node with an illegal result type
16330 /// with a new node built out of custom code.
16331 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16332                                            SmallVectorImpl<SDValue>&Results,
16333                                            SelectionDAG &DAG) const {
16334   SDLoc dl(N);
16335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16336   switch (N->getOpcode()) {
16337   default:
16338     llvm_unreachable("Do not know how to custom type legalize this operation!");
16339   case ISD::SIGN_EXTEND_INREG:
16340   case ISD::ADDC:
16341   case ISD::ADDE:
16342   case ISD::SUBC:
16343   case ISD::SUBE:
16344     // We don't want to expand or promote these.
16345     return;
16346   case ISD::SDIV:
16347   case ISD::UDIV:
16348   case ISD::SREM:
16349   case ISD::UREM:
16350   case ISD::SDIVREM:
16351   case ISD::UDIVREM: {
16352     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16353     Results.push_back(V);
16354     return;
16355   }
16356   case ISD::FP_TO_SINT:
16357   case ISD::FP_TO_UINT: {
16358     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16359
16360     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16361       return;
16362
16363     std::pair<SDValue,SDValue> Vals =
16364         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16365     SDValue FIST = Vals.first, StackSlot = Vals.second;
16366     if (FIST.getNode()) {
16367       EVT VT = N->getValueType(0);
16368       // Return a load from the stack slot.
16369       if (StackSlot.getNode())
16370         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16371                                       MachinePointerInfo(),
16372                                       false, false, false, 0));
16373       else
16374         Results.push_back(FIST);
16375     }
16376     return;
16377   }
16378   case ISD::UINT_TO_FP: {
16379     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16380     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16381         N->getValueType(0) != MVT::v2f32)
16382       return;
16383     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16384                                  N->getOperand(0));
16385     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16386                                      MVT::f64);
16387     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16388     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16389                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16390     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16391     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16392     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16393     return;
16394   }
16395   case ISD::FP_ROUND: {
16396     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16397         return;
16398     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16399     Results.push_back(V);
16400     return;
16401   }
16402   case ISD::INTRINSIC_W_CHAIN: {
16403     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16404     switch (IntNo) {
16405     default : llvm_unreachable("Do not know how to custom type "
16406                                "legalize this intrinsic operation!");
16407     case Intrinsic::x86_rdtsc:
16408       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16409                                      Results);
16410     case Intrinsic::x86_rdtscp:
16411       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16412                                      Results);
16413     case Intrinsic::x86_rdpmc:
16414       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16415     }
16416   }
16417   case ISD::READCYCLECOUNTER: {
16418     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16419                                    Results);
16420   }
16421   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16422     EVT T = N->getValueType(0);
16423     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16424     bool Regs64bit = T == MVT::i128;
16425     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16426     SDValue cpInL, cpInH;
16427     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16428                         DAG.getConstant(0, HalfT));
16429     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16430                         DAG.getConstant(1, HalfT));
16431     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16432                              Regs64bit ? X86::RAX : X86::EAX,
16433                              cpInL, SDValue());
16434     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16435                              Regs64bit ? X86::RDX : X86::EDX,
16436                              cpInH, cpInL.getValue(1));
16437     SDValue swapInL, swapInH;
16438     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16439                           DAG.getConstant(0, HalfT));
16440     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16441                           DAG.getConstant(1, HalfT));
16442     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16443                                Regs64bit ? X86::RBX : X86::EBX,
16444                                swapInL, cpInH.getValue(1));
16445     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16446                                Regs64bit ? X86::RCX : X86::ECX,
16447                                swapInH, swapInL.getValue(1));
16448     SDValue Ops[] = { swapInH.getValue(0),
16449                       N->getOperand(1),
16450                       swapInH.getValue(1) };
16451     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16452     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16453     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16454                                   X86ISD::LCMPXCHG8_DAG;
16455     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16456     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16457                                         Regs64bit ? X86::RAX : X86::EAX,
16458                                         HalfT, Result.getValue(1));
16459     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16460                                         Regs64bit ? X86::RDX : X86::EDX,
16461                                         HalfT, cpOutL.getValue(2));
16462     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16463
16464     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16465                                         MVT::i32, cpOutH.getValue(2));
16466     SDValue Success =
16467         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16468                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16469     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16470
16471     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16472     Results.push_back(Success);
16473     Results.push_back(EFLAGS.getValue(1));
16474     return;
16475   }
16476   case ISD::ATOMIC_SWAP:
16477   case ISD::ATOMIC_LOAD_ADD:
16478   case ISD::ATOMIC_LOAD_SUB:
16479   case ISD::ATOMIC_LOAD_AND:
16480   case ISD::ATOMIC_LOAD_OR:
16481   case ISD::ATOMIC_LOAD_XOR:
16482   case ISD::ATOMIC_LOAD_NAND:
16483   case ISD::ATOMIC_LOAD_MIN:
16484   case ISD::ATOMIC_LOAD_MAX:
16485   case ISD::ATOMIC_LOAD_UMIN:
16486   case ISD::ATOMIC_LOAD_UMAX:
16487     // Delegate to generic TypeLegalization. Situations we can really handle
16488     // should have already been dealt with by X86AtomicExpand.cpp.
16489     break;
16490   case ISD::ATOMIC_LOAD: {
16491     ReplaceATOMIC_LOAD(N, Results, DAG);
16492     return;
16493   }
16494   case ISD::BITCAST: {
16495     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16496     EVT DstVT = N->getValueType(0);
16497     EVT SrcVT = N->getOperand(0)->getValueType(0);
16498
16499     if (SrcVT != MVT::f64 ||
16500         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16501       return;
16502
16503     unsigned NumElts = DstVT.getVectorNumElements();
16504     EVT SVT = DstVT.getVectorElementType();
16505     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16506     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16507                                    MVT::v2f64, N->getOperand(0));
16508     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16509
16510     if (ExperimentalVectorWideningLegalization) {
16511       // If we are legalizing vectors by widening, we already have the desired
16512       // legal vector type, just return it.
16513       Results.push_back(ToVecInt);
16514       return;
16515     }
16516
16517     SmallVector<SDValue, 8> Elts;
16518     for (unsigned i = 0, e = NumElts; i != e; ++i)
16519       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16520                                    ToVecInt, DAG.getIntPtrConstant(i)));
16521
16522     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16523   }
16524   }
16525 }
16526
16527 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16528   switch (Opcode) {
16529   default: return nullptr;
16530   case X86ISD::BSF:                return "X86ISD::BSF";
16531   case X86ISD::BSR:                return "X86ISD::BSR";
16532   case X86ISD::SHLD:               return "X86ISD::SHLD";
16533   case X86ISD::SHRD:               return "X86ISD::SHRD";
16534   case X86ISD::FAND:               return "X86ISD::FAND";
16535   case X86ISD::FANDN:              return "X86ISD::FANDN";
16536   case X86ISD::FOR:                return "X86ISD::FOR";
16537   case X86ISD::FXOR:               return "X86ISD::FXOR";
16538   case X86ISD::FSRL:               return "X86ISD::FSRL";
16539   case X86ISD::FILD:               return "X86ISD::FILD";
16540   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16541   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16542   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16543   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16544   case X86ISD::FLD:                return "X86ISD::FLD";
16545   case X86ISD::FST:                return "X86ISD::FST";
16546   case X86ISD::CALL:               return "X86ISD::CALL";
16547   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16548   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16549   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
16550   case X86ISD::BT:                 return "X86ISD::BT";
16551   case X86ISD::CMP:                return "X86ISD::CMP";
16552   case X86ISD::COMI:               return "X86ISD::COMI";
16553   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16554   case X86ISD::CMPM:               return "X86ISD::CMPM";
16555   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16556   case X86ISD::SETCC:              return "X86ISD::SETCC";
16557   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16558   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16559   case X86ISD::CMOV:               return "X86ISD::CMOV";
16560   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16561   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16562   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
16563   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
16564   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
16565   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
16566   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
16567   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
16568   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
16569   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
16570   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
16571   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
16572   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
16573   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
16574   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
16575   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
16576   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
16577   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
16578   case X86ISD::HADD:               return "X86ISD::HADD";
16579   case X86ISD::HSUB:               return "X86ISD::HSUB";
16580   case X86ISD::FHADD:              return "X86ISD::FHADD";
16581   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
16582   case X86ISD::UMAX:               return "X86ISD::UMAX";
16583   case X86ISD::UMIN:               return "X86ISD::UMIN";
16584   case X86ISD::SMAX:               return "X86ISD::SMAX";
16585   case X86ISD::SMIN:               return "X86ISD::SMIN";
16586   case X86ISD::FMAX:               return "X86ISD::FMAX";
16587   case X86ISD::FMIN:               return "X86ISD::FMIN";
16588   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
16589   case X86ISD::FMINC:              return "X86ISD::FMINC";
16590   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
16591   case X86ISD::FRCP:               return "X86ISD::FRCP";
16592   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
16593   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
16594   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
16595   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
16596   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
16597   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
16598   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
16599   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
16600   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
16601   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
16602   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
16603   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
16604   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
16605   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
16606   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
16607   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
16608   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
16609   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
16610   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
16611   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
16612   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
16613   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
16614   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
16615   case X86ISD::VSHL:               return "X86ISD::VSHL";
16616   case X86ISD::VSRL:               return "X86ISD::VSRL";
16617   case X86ISD::VSRA:               return "X86ISD::VSRA";
16618   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
16619   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
16620   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
16621   case X86ISD::CMPP:               return "X86ISD::CMPP";
16622   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
16623   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
16624   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
16625   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
16626   case X86ISD::ADD:                return "X86ISD::ADD";
16627   case X86ISD::SUB:                return "X86ISD::SUB";
16628   case X86ISD::ADC:                return "X86ISD::ADC";
16629   case X86ISD::SBB:                return "X86ISD::SBB";
16630   case X86ISD::SMUL:               return "X86ISD::SMUL";
16631   case X86ISD::UMUL:               return "X86ISD::UMUL";
16632   case X86ISD::INC:                return "X86ISD::INC";
16633   case X86ISD::DEC:                return "X86ISD::DEC";
16634   case X86ISD::OR:                 return "X86ISD::OR";
16635   case X86ISD::XOR:                return "X86ISD::XOR";
16636   case X86ISD::AND:                return "X86ISD::AND";
16637   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
16638   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
16639   case X86ISD::PTEST:              return "X86ISD::PTEST";
16640   case X86ISD::TESTP:              return "X86ISD::TESTP";
16641   case X86ISD::TESTM:              return "X86ISD::TESTM";
16642   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
16643   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
16644   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
16645   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
16646   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
16647   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
16648   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
16649   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
16650   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
16651   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
16652   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
16653   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
16654   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
16655   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
16656   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
16657   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
16658   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
16659   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
16660   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
16661   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
16662   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
16663   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
16664   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
16665   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
16666   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
16667   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
16668   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
16669   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
16670   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
16671   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
16672   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
16673   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
16674   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16675   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
16676   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
16677   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
16678   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
16679   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
16680   case X86ISD::SAHF:               return "X86ISD::SAHF";
16681   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
16682   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
16683   case X86ISD::FMADD:              return "X86ISD::FMADD";
16684   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
16685   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
16686   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
16687   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
16688   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
16689   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
16690   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
16691   case X86ISD::XTEST:              return "X86ISD::XTEST";
16692   }
16693 }
16694
16695 // isLegalAddressingMode - Return true if the addressing mode represented
16696 // by AM is legal for this target, for a load/store of the specified type.
16697 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16698                                               Type *Ty) const {
16699   // X86 supports extremely general addressing modes.
16700   CodeModel::Model M = getTargetMachine().getCodeModel();
16701   Reloc::Model R = getTargetMachine().getRelocationModel();
16702
16703   // X86 allows a sign-extended 32-bit immediate field as a displacement.
16704   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16705     return false;
16706
16707   if (AM.BaseGV) {
16708     unsigned GVFlags =
16709       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16710
16711     // If a reference to this global requires an extra load, we can't fold it.
16712     if (isGlobalStubReference(GVFlags))
16713       return false;
16714
16715     // If BaseGV requires a register for the PIC base, we cannot also have a
16716     // BaseReg specified.
16717     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16718       return false;
16719
16720     // If lower 4G is not available, then we must use rip-relative addressing.
16721     if ((M != CodeModel::Small || R != Reloc::Static) &&
16722         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16723       return false;
16724   }
16725
16726   switch (AM.Scale) {
16727   case 0:
16728   case 1:
16729   case 2:
16730   case 4:
16731   case 8:
16732     // These scales always work.
16733     break;
16734   case 3:
16735   case 5:
16736   case 9:
16737     // These scales are formed with basereg+scalereg.  Only accept if there is
16738     // no basereg yet.
16739     if (AM.HasBaseReg)
16740       return false;
16741     break;
16742   default:  // Other stuff never works.
16743     return false;
16744   }
16745
16746   return true;
16747 }
16748
16749 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16750   unsigned Bits = Ty->getScalarSizeInBits();
16751
16752   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16753   // particularly cheaper than those without.
16754   if (Bits == 8)
16755     return false;
16756
16757   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16758   // variable shifts just as cheap as scalar ones.
16759   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16760     return false;
16761
16762   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16763   // fully general vector.
16764   return true;
16765 }
16766
16767 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16768   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16769     return false;
16770   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16771   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16772   return NumBits1 > NumBits2;
16773 }
16774
16775 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16776   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16777     return false;
16778
16779   if (!isTypeLegal(EVT::getEVT(Ty1)))
16780     return false;
16781
16782   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16783
16784   // Assuming the caller doesn't have a zeroext or signext return parameter,
16785   // truncation all the way down to i1 is valid.
16786   return true;
16787 }
16788
16789 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16790   return isInt<32>(Imm);
16791 }
16792
16793 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16794   // Can also use sub to handle negated immediates.
16795   return isInt<32>(Imm);
16796 }
16797
16798 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16799   if (!VT1.isInteger() || !VT2.isInteger())
16800     return false;
16801   unsigned NumBits1 = VT1.getSizeInBits();
16802   unsigned NumBits2 = VT2.getSizeInBits();
16803   return NumBits1 > NumBits2;
16804 }
16805
16806 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16807   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16808   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16809 }
16810
16811 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16812   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16813   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16814 }
16815
16816 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16817   EVT VT1 = Val.getValueType();
16818   if (isZExtFree(VT1, VT2))
16819     return true;
16820
16821   if (Val.getOpcode() != ISD::LOAD)
16822     return false;
16823
16824   if (!VT1.isSimple() || !VT1.isInteger() ||
16825       !VT2.isSimple() || !VT2.isInteger())
16826     return false;
16827
16828   switch (VT1.getSimpleVT().SimpleTy) {
16829   default: break;
16830   case MVT::i8:
16831   case MVT::i16:
16832   case MVT::i32:
16833     // X86 has 8, 16, and 32-bit zero-extending loads.
16834     return true;
16835   }
16836
16837   return false;
16838 }
16839
16840 bool
16841 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16842   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16843     return false;
16844
16845   VT = VT.getScalarType();
16846
16847   if (!VT.isSimple())
16848     return false;
16849
16850   switch (VT.getSimpleVT().SimpleTy) {
16851   case MVT::f32:
16852   case MVT::f64:
16853     return true;
16854   default:
16855     break;
16856   }
16857
16858   return false;
16859 }
16860
16861 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16862   // i16 instructions are longer (0x66 prefix) and potentially slower.
16863   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16864 }
16865
16866 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16867 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16868 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16869 /// are assumed to be legal.
16870 bool
16871 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16872                                       EVT VT) const {
16873   if (!VT.isSimple())
16874     return false;
16875
16876   MVT SVT = VT.getSimpleVT();
16877
16878   // Very little shuffling can be done for 64-bit vectors right now.
16879   if (VT.getSizeInBits() == 64)
16880     return false;
16881
16882   // If this is a single-input shuffle with no 128 bit lane crossings we can
16883   // lower it into pshufb.
16884   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16885       (SVT.is256BitVector() && Subtarget->hasInt256())) {
16886     bool isLegal = true;
16887     for (unsigned I = 0, E = M.size(); I != E; ++I) {
16888       if (M[I] >= (int)SVT.getVectorNumElements() ||
16889           ShuffleCrosses128bitLane(SVT, I, M[I])) {
16890         isLegal = false;
16891         break;
16892       }
16893     }
16894     if (isLegal)
16895       return true;
16896   }
16897
16898   // FIXME: blends, shifts.
16899   return (SVT.getVectorNumElements() == 2 ||
16900           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16901           isMOVLMask(M, SVT) ||
16902           isMOVHLPSMask(M, SVT) ||
16903           isSHUFPMask(M, SVT) ||
16904           isPSHUFDMask(M, SVT) ||
16905           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16906           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16907           isPALIGNRMask(M, SVT, Subtarget) ||
16908           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16909           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16910           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16911           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16912           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16913 }
16914
16915 bool
16916 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16917                                           EVT VT) const {
16918   if (!VT.isSimple())
16919     return false;
16920
16921   MVT SVT = VT.getSimpleVT();
16922   unsigned NumElts = SVT.getVectorNumElements();
16923   // FIXME: This collection of masks seems suspect.
16924   if (NumElts == 2)
16925     return true;
16926   if (NumElts == 4 && SVT.is128BitVector()) {
16927     return (isMOVLMask(Mask, SVT)  ||
16928             isCommutedMOVLMask(Mask, SVT, true) ||
16929             isSHUFPMask(Mask, SVT) ||
16930             isSHUFPMask(Mask, SVT, /* Commuted */ true));
16931   }
16932   return false;
16933 }
16934
16935 //===----------------------------------------------------------------------===//
16936 //                           X86 Scheduler Hooks
16937 //===----------------------------------------------------------------------===//
16938
16939 /// Utility function to emit xbegin specifying the start of an RTM region.
16940 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16941                                      const TargetInstrInfo *TII) {
16942   DebugLoc DL = MI->getDebugLoc();
16943
16944   const BasicBlock *BB = MBB->getBasicBlock();
16945   MachineFunction::iterator I = MBB;
16946   ++I;
16947
16948   // For the v = xbegin(), we generate
16949   //
16950   // thisMBB:
16951   //  xbegin sinkMBB
16952   //
16953   // mainMBB:
16954   //  eax = -1
16955   //
16956   // sinkMBB:
16957   //  v = eax
16958
16959   MachineBasicBlock *thisMBB = MBB;
16960   MachineFunction *MF = MBB->getParent();
16961   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16962   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16963   MF->insert(I, mainMBB);
16964   MF->insert(I, sinkMBB);
16965
16966   // Transfer the remainder of BB and its successor edges to sinkMBB.
16967   sinkMBB->splice(sinkMBB->begin(), MBB,
16968                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16969   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16970
16971   // thisMBB:
16972   //  xbegin sinkMBB
16973   //  # fallthrough to mainMBB
16974   //  # abortion to sinkMBB
16975   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16976   thisMBB->addSuccessor(mainMBB);
16977   thisMBB->addSuccessor(sinkMBB);
16978
16979   // mainMBB:
16980   //  EAX = -1
16981   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16982   mainMBB->addSuccessor(sinkMBB);
16983
16984   // sinkMBB:
16985   // EAX is live into the sinkMBB
16986   sinkMBB->addLiveIn(X86::EAX);
16987   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16988           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16989     .addReg(X86::EAX);
16990
16991   MI->eraseFromParent();
16992   return sinkMBB;
16993 }
16994
16995 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16996 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16997 // in the .td file.
16998 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16999                                        const TargetInstrInfo *TII) {
17000   unsigned Opc;
17001   switch (MI->getOpcode()) {
17002   default: llvm_unreachable("illegal opcode!");
17003   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17004   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17005   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17006   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17007   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17008   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17009   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17010   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17011   }
17012
17013   DebugLoc dl = MI->getDebugLoc();
17014   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17015
17016   unsigned NumArgs = MI->getNumOperands();
17017   for (unsigned i = 1; i < NumArgs; ++i) {
17018     MachineOperand &Op = MI->getOperand(i);
17019     if (!(Op.isReg() && Op.isImplicit()))
17020       MIB.addOperand(Op);
17021   }
17022   if (MI->hasOneMemOperand())
17023     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17024
17025   BuildMI(*BB, MI, dl,
17026     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17027     .addReg(X86::XMM0);
17028
17029   MI->eraseFromParent();
17030   return BB;
17031 }
17032
17033 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17034 // defs in an instruction pattern
17035 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17036                                        const TargetInstrInfo *TII) {
17037   unsigned Opc;
17038   switch (MI->getOpcode()) {
17039   default: llvm_unreachable("illegal opcode!");
17040   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17041   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17042   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17043   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17044   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17045   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17046   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17047   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17048   }
17049
17050   DebugLoc dl = MI->getDebugLoc();
17051   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17052
17053   unsigned NumArgs = MI->getNumOperands(); // remove the results
17054   for (unsigned i = 1; i < NumArgs; ++i) {
17055     MachineOperand &Op = MI->getOperand(i);
17056     if (!(Op.isReg() && Op.isImplicit()))
17057       MIB.addOperand(Op);
17058   }
17059   if (MI->hasOneMemOperand())
17060     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17061
17062   BuildMI(*BB, MI, dl,
17063     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17064     .addReg(X86::ECX);
17065
17066   MI->eraseFromParent();
17067   return BB;
17068 }
17069
17070 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17071                                        const TargetInstrInfo *TII,
17072                                        const X86Subtarget* Subtarget) {
17073   DebugLoc dl = MI->getDebugLoc();
17074
17075   // Address into RAX/EAX, other two args into ECX, EDX.
17076   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17077   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17078   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17079   for (int i = 0; i < X86::AddrNumOperands; ++i)
17080     MIB.addOperand(MI->getOperand(i));
17081
17082   unsigned ValOps = X86::AddrNumOperands;
17083   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17084     .addReg(MI->getOperand(ValOps).getReg());
17085   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17086     .addReg(MI->getOperand(ValOps+1).getReg());
17087
17088   // The instruction doesn't actually take any operands though.
17089   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17090
17091   MI->eraseFromParent(); // The pseudo is gone now.
17092   return BB;
17093 }
17094
17095 MachineBasicBlock *
17096 X86TargetLowering::EmitVAARG64WithCustomInserter(
17097                    MachineInstr *MI,
17098                    MachineBasicBlock *MBB) const {
17099   // Emit va_arg instruction on X86-64.
17100
17101   // Operands to this pseudo-instruction:
17102   // 0  ) Output        : destination address (reg)
17103   // 1-5) Input         : va_list address (addr, i64mem)
17104   // 6  ) ArgSize       : Size (in bytes) of vararg type
17105   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17106   // 8  ) Align         : Alignment of type
17107   // 9  ) EFLAGS (implicit-def)
17108
17109   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17110   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17111
17112   unsigned DestReg = MI->getOperand(0).getReg();
17113   MachineOperand &Base = MI->getOperand(1);
17114   MachineOperand &Scale = MI->getOperand(2);
17115   MachineOperand &Index = MI->getOperand(3);
17116   MachineOperand &Disp = MI->getOperand(4);
17117   MachineOperand &Segment = MI->getOperand(5);
17118   unsigned ArgSize = MI->getOperand(6).getImm();
17119   unsigned ArgMode = MI->getOperand(7).getImm();
17120   unsigned Align = MI->getOperand(8).getImm();
17121
17122   // Memory Reference
17123   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17124   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17125   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17126
17127   // Machine Information
17128   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17129   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17130   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17131   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17132   DebugLoc DL = MI->getDebugLoc();
17133
17134   // struct va_list {
17135   //   i32   gp_offset
17136   //   i32   fp_offset
17137   //   i64   overflow_area (address)
17138   //   i64   reg_save_area (address)
17139   // }
17140   // sizeof(va_list) = 24
17141   // alignment(va_list) = 8
17142
17143   unsigned TotalNumIntRegs = 6;
17144   unsigned TotalNumXMMRegs = 8;
17145   bool UseGPOffset = (ArgMode == 1);
17146   bool UseFPOffset = (ArgMode == 2);
17147   unsigned MaxOffset = TotalNumIntRegs * 8 +
17148                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17149
17150   /* Align ArgSize to a multiple of 8 */
17151   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17152   bool NeedsAlign = (Align > 8);
17153
17154   MachineBasicBlock *thisMBB = MBB;
17155   MachineBasicBlock *overflowMBB;
17156   MachineBasicBlock *offsetMBB;
17157   MachineBasicBlock *endMBB;
17158
17159   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17160   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17161   unsigned OffsetReg = 0;
17162
17163   if (!UseGPOffset && !UseFPOffset) {
17164     // If we only pull from the overflow region, we don't create a branch.
17165     // We don't need to alter control flow.
17166     OffsetDestReg = 0; // unused
17167     OverflowDestReg = DestReg;
17168
17169     offsetMBB = nullptr;
17170     overflowMBB = thisMBB;
17171     endMBB = thisMBB;
17172   } else {
17173     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17174     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17175     // If not, pull from overflow_area. (branch to overflowMBB)
17176     //
17177     //       thisMBB
17178     //         |     .
17179     //         |        .
17180     //     offsetMBB   overflowMBB
17181     //         |        .
17182     //         |     .
17183     //        endMBB
17184
17185     // Registers for the PHI in endMBB
17186     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17187     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17188
17189     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17190     MachineFunction *MF = MBB->getParent();
17191     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17192     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17193     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17194
17195     MachineFunction::iterator MBBIter = MBB;
17196     ++MBBIter;
17197
17198     // Insert the new basic blocks
17199     MF->insert(MBBIter, offsetMBB);
17200     MF->insert(MBBIter, overflowMBB);
17201     MF->insert(MBBIter, endMBB);
17202
17203     // Transfer the remainder of MBB and its successor edges to endMBB.
17204     endMBB->splice(endMBB->begin(), thisMBB,
17205                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17206     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17207
17208     // Make offsetMBB and overflowMBB successors of thisMBB
17209     thisMBB->addSuccessor(offsetMBB);
17210     thisMBB->addSuccessor(overflowMBB);
17211
17212     // endMBB is a successor of both offsetMBB and overflowMBB
17213     offsetMBB->addSuccessor(endMBB);
17214     overflowMBB->addSuccessor(endMBB);
17215
17216     // Load the offset value into a register
17217     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17218     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17219       .addOperand(Base)
17220       .addOperand(Scale)
17221       .addOperand(Index)
17222       .addDisp(Disp, UseFPOffset ? 4 : 0)
17223       .addOperand(Segment)
17224       .setMemRefs(MMOBegin, MMOEnd);
17225
17226     // Check if there is enough room left to pull this argument.
17227     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17228       .addReg(OffsetReg)
17229       .addImm(MaxOffset + 8 - ArgSizeA8);
17230
17231     // Branch to "overflowMBB" if offset >= max
17232     // Fall through to "offsetMBB" otherwise
17233     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17234       .addMBB(overflowMBB);
17235   }
17236
17237   // In offsetMBB, emit code to use the reg_save_area.
17238   if (offsetMBB) {
17239     assert(OffsetReg != 0);
17240
17241     // Read the reg_save_area address.
17242     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17243     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17244       .addOperand(Base)
17245       .addOperand(Scale)
17246       .addOperand(Index)
17247       .addDisp(Disp, 16)
17248       .addOperand(Segment)
17249       .setMemRefs(MMOBegin, MMOEnd);
17250
17251     // Zero-extend the offset
17252     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17253       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17254         .addImm(0)
17255         .addReg(OffsetReg)
17256         .addImm(X86::sub_32bit);
17257
17258     // Add the offset to the reg_save_area to get the final address.
17259     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17260       .addReg(OffsetReg64)
17261       .addReg(RegSaveReg);
17262
17263     // Compute the offset for the next argument
17264     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17265     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17266       .addReg(OffsetReg)
17267       .addImm(UseFPOffset ? 16 : 8);
17268
17269     // Store it back into the va_list.
17270     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17271       .addOperand(Base)
17272       .addOperand(Scale)
17273       .addOperand(Index)
17274       .addDisp(Disp, UseFPOffset ? 4 : 0)
17275       .addOperand(Segment)
17276       .addReg(NextOffsetReg)
17277       .setMemRefs(MMOBegin, MMOEnd);
17278
17279     // Jump to endMBB
17280     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17281       .addMBB(endMBB);
17282   }
17283
17284   //
17285   // Emit code to use overflow area
17286   //
17287
17288   // Load the overflow_area address into a register.
17289   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17290   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17291     .addOperand(Base)
17292     .addOperand(Scale)
17293     .addOperand(Index)
17294     .addDisp(Disp, 8)
17295     .addOperand(Segment)
17296     .setMemRefs(MMOBegin, MMOEnd);
17297
17298   // If we need to align it, do so. Otherwise, just copy the address
17299   // to OverflowDestReg.
17300   if (NeedsAlign) {
17301     // Align the overflow address
17302     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17303     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17304
17305     // aligned_addr = (addr + (align-1)) & ~(align-1)
17306     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17307       .addReg(OverflowAddrReg)
17308       .addImm(Align-1);
17309
17310     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17311       .addReg(TmpReg)
17312       .addImm(~(uint64_t)(Align-1));
17313   } else {
17314     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17315       .addReg(OverflowAddrReg);
17316   }
17317
17318   // Compute the next overflow address after this argument.
17319   // (the overflow address should be kept 8-byte aligned)
17320   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17321   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17322     .addReg(OverflowDestReg)
17323     .addImm(ArgSizeA8);
17324
17325   // Store the new overflow address.
17326   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17327     .addOperand(Base)
17328     .addOperand(Scale)
17329     .addOperand(Index)
17330     .addDisp(Disp, 8)
17331     .addOperand(Segment)
17332     .addReg(NextAddrReg)
17333     .setMemRefs(MMOBegin, MMOEnd);
17334
17335   // If we branched, emit the PHI to the front of endMBB.
17336   if (offsetMBB) {
17337     BuildMI(*endMBB, endMBB->begin(), DL,
17338             TII->get(X86::PHI), DestReg)
17339       .addReg(OffsetDestReg).addMBB(offsetMBB)
17340       .addReg(OverflowDestReg).addMBB(overflowMBB);
17341   }
17342
17343   // Erase the pseudo instruction
17344   MI->eraseFromParent();
17345
17346   return endMBB;
17347 }
17348
17349 MachineBasicBlock *
17350 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17351                                                  MachineInstr *MI,
17352                                                  MachineBasicBlock *MBB) const {
17353   // Emit code to save XMM registers to the stack. The ABI says that the
17354   // number of registers to save is given in %al, so it's theoretically
17355   // possible to do an indirect jump trick to avoid saving all of them,
17356   // however this code takes a simpler approach and just executes all
17357   // of the stores if %al is non-zero. It's less code, and it's probably
17358   // easier on the hardware branch predictor, and stores aren't all that
17359   // expensive anyway.
17360
17361   // Create the new basic blocks. One block contains all the XMM stores,
17362   // and one block is the final destination regardless of whether any
17363   // stores were performed.
17364   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17365   MachineFunction *F = MBB->getParent();
17366   MachineFunction::iterator MBBIter = MBB;
17367   ++MBBIter;
17368   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17369   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17370   F->insert(MBBIter, XMMSaveMBB);
17371   F->insert(MBBIter, EndMBB);
17372
17373   // Transfer the remainder of MBB and its successor edges to EndMBB.
17374   EndMBB->splice(EndMBB->begin(), MBB,
17375                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17376   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17377
17378   // The original block will now fall through to the XMM save block.
17379   MBB->addSuccessor(XMMSaveMBB);
17380   // The XMMSaveMBB will fall through to the end block.
17381   XMMSaveMBB->addSuccessor(EndMBB);
17382
17383   // Now add the instructions.
17384   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17385   DebugLoc DL = MI->getDebugLoc();
17386
17387   unsigned CountReg = MI->getOperand(0).getReg();
17388   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17389   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17390
17391   if (!Subtarget->isTargetWin64()) {
17392     // If %al is 0, branch around the XMM save block.
17393     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17394     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17395     MBB->addSuccessor(EndMBB);
17396   }
17397
17398   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17399   // that was just emitted, but clearly shouldn't be "saved".
17400   assert((MI->getNumOperands() <= 3 ||
17401           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17402           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17403          && "Expected last argument to be EFLAGS");
17404   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17405   // In the XMM save block, save all the XMM argument registers.
17406   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17407     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17408     MachineMemOperand *MMO =
17409       F->getMachineMemOperand(
17410           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17411         MachineMemOperand::MOStore,
17412         /*Size=*/16, /*Align=*/16);
17413     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17414       .addFrameIndex(RegSaveFrameIndex)
17415       .addImm(/*Scale=*/1)
17416       .addReg(/*IndexReg=*/0)
17417       .addImm(/*Disp=*/Offset)
17418       .addReg(/*Segment=*/0)
17419       .addReg(MI->getOperand(i).getReg())
17420       .addMemOperand(MMO);
17421   }
17422
17423   MI->eraseFromParent();   // The pseudo instruction is gone now.
17424
17425   return EndMBB;
17426 }
17427
17428 // The EFLAGS operand of SelectItr might be missing a kill marker
17429 // because there were multiple uses of EFLAGS, and ISel didn't know
17430 // which to mark. Figure out whether SelectItr should have had a
17431 // kill marker, and set it if it should. Returns the correct kill
17432 // marker value.
17433 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17434                                      MachineBasicBlock* BB,
17435                                      const TargetRegisterInfo* TRI) {
17436   // Scan forward through BB for a use/def of EFLAGS.
17437   MachineBasicBlock::iterator miI(std::next(SelectItr));
17438   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17439     const MachineInstr& mi = *miI;
17440     if (mi.readsRegister(X86::EFLAGS))
17441       return false;
17442     if (mi.definesRegister(X86::EFLAGS))
17443       break; // Should have kill-flag - update below.
17444   }
17445
17446   // If we hit the end of the block, check whether EFLAGS is live into a
17447   // successor.
17448   if (miI == BB->end()) {
17449     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17450                                           sEnd = BB->succ_end();
17451          sItr != sEnd; ++sItr) {
17452       MachineBasicBlock* succ = *sItr;
17453       if (succ->isLiveIn(X86::EFLAGS))
17454         return false;
17455     }
17456   }
17457
17458   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17459   // out. SelectMI should have a kill flag on EFLAGS.
17460   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17461   return true;
17462 }
17463
17464 MachineBasicBlock *
17465 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17466                                      MachineBasicBlock *BB) const {
17467   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17468   DebugLoc DL = MI->getDebugLoc();
17469
17470   // To "insert" a SELECT_CC instruction, we actually have to insert the
17471   // diamond control-flow pattern.  The incoming instruction knows the
17472   // destination vreg to set, the condition code register to branch on, the
17473   // true/false values to select between, and a branch opcode to use.
17474   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17475   MachineFunction::iterator It = BB;
17476   ++It;
17477
17478   //  thisMBB:
17479   //  ...
17480   //   TrueVal = ...
17481   //   cmpTY ccX, r1, r2
17482   //   bCC copy1MBB
17483   //   fallthrough --> copy0MBB
17484   MachineBasicBlock *thisMBB = BB;
17485   MachineFunction *F = BB->getParent();
17486   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17487   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17488   F->insert(It, copy0MBB);
17489   F->insert(It, sinkMBB);
17490
17491   // If the EFLAGS register isn't dead in the terminator, then claim that it's
17492   // live into the sink and copy blocks.
17493   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17494   if (!MI->killsRegister(X86::EFLAGS) &&
17495       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17496     copy0MBB->addLiveIn(X86::EFLAGS);
17497     sinkMBB->addLiveIn(X86::EFLAGS);
17498   }
17499
17500   // Transfer the remainder of BB and its successor edges to sinkMBB.
17501   sinkMBB->splice(sinkMBB->begin(), BB,
17502                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
17503   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17504
17505   // Add the true and fallthrough blocks as its successors.
17506   BB->addSuccessor(copy0MBB);
17507   BB->addSuccessor(sinkMBB);
17508
17509   // Create the conditional branch instruction.
17510   unsigned Opc =
17511     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17512   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17513
17514   //  copy0MBB:
17515   //   %FalseValue = ...
17516   //   # fallthrough to sinkMBB
17517   copy0MBB->addSuccessor(sinkMBB);
17518
17519   //  sinkMBB:
17520   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17521   //  ...
17522   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17523           TII->get(X86::PHI), MI->getOperand(0).getReg())
17524     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17525     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17526
17527   MI->eraseFromParent();   // The pseudo instruction is gone now.
17528   return sinkMBB;
17529 }
17530
17531 MachineBasicBlock *
17532 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17533                                         bool Is64Bit) const {
17534   MachineFunction *MF = BB->getParent();
17535   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17536   DebugLoc DL = MI->getDebugLoc();
17537   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17538
17539   assert(MF->shouldSplitStack());
17540
17541   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17542   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17543
17544   // BB:
17545   //  ... [Till the alloca]
17546   // If stacklet is not large enough, jump to mallocMBB
17547   //
17548   // bumpMBB:
17549   //  Allocate by subtracting from RSP
17550   //  Jump to continueMBB
17551   //
17552   // mallocMBB:
17553   //  Allocate by call to runtime
17554   //
17555   // continueMBB:
17556   //  ...
17557   //  [rest of original BB]
17558   //
17559
17560   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17561   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17562   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17563
17564   MachineRegisterInfo &MRI = MF->getRegInfo();
17565   const TargetRegisterClass *AddrRegClass =
17566     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17567
17568   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17569     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17570     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17571     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17572     sizeVReg = MI->getOperand(1).getReg(),
17573     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17574
17575   MachineFunction::iterator MBBIter = BB;
17576   ++MBBIter;
17577
17578   MF->insert(MBBIter, bumpMBB);
17579   MF->insert(MBBIter, mallocMBB);
17580   MF->insert(MBBIter, continueMBB);
17581
17582   continueMBB->splice(continueMBB->begin(), BB,
17583                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
17584   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17585
17586   // Add code to the main basic block to check if the stack limit has been hit,
17587   // and if so, jump to mallocMBB otherwise to bumpMBB.
17588   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17589   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17590     .addReg(tmpSPVReg).addReg(sizeVReg);
17591   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17592     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17593     .addReg(SPLimitVReg);
17594   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17595
17596   // bumpMBB simply decreases the stack pointer, since we know the current
17597   // stacklet has enough space.
17598   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17599     .addReg(SPLimitVReg);
17600   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17601     .addReg(SPLimitVReg);
17602   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17603
17604   // Calls into a routine in libgcc to allocate more space from the heap.
17605   const uint32_t *RegMask =
17606     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17607   if (Is64Bit) {
17608     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17609       .addReg(sizeVReg);
17610     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17611       .addExternalSymbol("__morestack_allocate_stack_space")
17612       .addRegMask(RegMask)
17613       .addReg(X86::RDI, RegState::Implicit)
17614       .addReg(X86::RAX, RegState::ImplicitDefine);
17615   } else {
17616     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17617       .addImm(12);
17618     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17619     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17620       .addExternalSymbol("__morestack_allocate_stack_space")
17621       .addRegMask(RegMask)
17622       .addReg(X86::EAX, RegState::ImplicitDefine);
17623   }
17624
17625   if (!Is64Bit)
17626     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17627       .addImm(16);
17628
17629   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17630     .addReg(Is64Bit ? X86::RAX : X86::EAX);
17631   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17632
17633   // Set up the CFG correctly.
17634   BB->addSuccessor(bumpMBB);
17635   BB->addSuccessor(mallocMBB);
17636   mallocMBB->addSuccessor(continueMBB);
17637   bumpMBB->addSuccessor(continueMBB);
17638
17639   // Take care of the PHI nodes.
17640   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17641           MI->getOperand(0).getReg())
17642     .addReg(mallocPtrVReg).addMBB(mallocMBB)
17643     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17644
17645   // Delete the original pseudo instruction.
17646   MI->eraseFromParent();
17647
17648   // And we're done.
17649   return continueMBB;
17650 }
17651
17652 MachineBasicBlock *
17653 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17654                                         MachineBasicBlock *BB) const {
17655   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17656   DebugLoc DL = MI->getDebugLoc();
17657
17658   assert(!Subtarget->isTargetMacho());
17659
17660   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
17661   // non-trivial part is impdef of ESP.
17662
17663   if (Subtarget->isTargetWin64()) {
17664     if (Subtarget->isTargetCygMing()) {
17665       // ___chkstk(Mingw64):
17666       // Clobbers R10, R11, RAX and EFLAGS.
17667       // Updates RSP.
17668       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17669         .addExternalSymbol("___chkstk")
17670         .addReg(X86::RAX, RegState::Implicit)
17671         .addReg(X86::RSP, RegState::Implicit)
17672         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17673         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17674         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17675     } else {
17676       // __chkstk(MSVCRT): does not update stack pointer.
17677       // Clobbers R10, R11 and EFLAGS.
17678       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17679         .addExternalSymbol("__chkstk")
17680         .addReg(X86::RAX, RegState::Implicit)
17681         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17682       // RAX has the offset to be subtracted from RSP.
17683       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17684         .addReg(X86::RSP)
17685         .addReg(X86::RAX);
17686     }
17687   } else {
17688     const char *StackProbeSymbol =
17689       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17690
17691     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17692       .addExternalSymbol(StackProbeSymbol)
17693       .addReg(X86::EAX, RegState::Implicit)
17694       .addReg(X86::ESP, RegState::Implicit)
17695       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17696       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17697       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17698   }
17699
17700   MI->eraseFromParent();   // The pseudo instruction is gone now.
17701   return BB;
17702 }
17703
17704 MachineBasicBlock *
17705 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17706                                       MachineBasicBlock *BB) const {
17707   // This is pretty easy.  We're taking the value that we received from
17708   // our load from the relocation, sticking it in either RDI (x86-64)
17709   // or EAX and doing an indirect call.  The return value will then
17710   // be in the normal return register.
17711   MachineFunction *F = BB->getParent();
17712   const X86InstrInfo *TII
17713     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17714   DebugLoc DL = MI->getDebugLoc();
17715
17716   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17717   assert(MI->getOperand(3).isGlobal() && "This should be a global");
17718
17719   // Get a register mask for the lowered call.
17720   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17721   // proper register mask.
17722   const uint32_t *RegMask =
17723     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17724   if (Subtarget->is64Bit()) {
17725     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17726                                       TII->get(X86::MOV64rm), X86::RDI)
17727     .addReg(X86::RIP)
17728     .addImm(0).addReg(0)
17729     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17730                       MI->getOperand(3).getTargetFlags())
17731     .addReg(0);
17732     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17733     addDirectMem(MIB, X86::RDI);
17734     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17735   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17736     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17737                                       TII->get(X86::MOV32rm), X86::EAX)
17738     .addReg(0)
17739     .addImm(0).addReg(0)
17740     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17741                       MI->getOperand(3).getTargetFlags())
17742     .addReg(0);
17743     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17744     addDirectMem(MIB, X86::EAX);
17745     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17746   } else {
17747     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17748                                       TII->get(X86::MOV32rm), X86::EAX)
17749     .addReg(TII->getGlobalBaseReg(F))
17750     .addImm(0).addReg(0)
17751     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17752                       MI->getOperand(3).getTargetFlags())
17753     .addReg(0);
17754     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17755     addDirectMem(MIB, X86::EAX);
17756     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17757   }
17758
17759   MI->eraseFromParent(); // The pseudo instruction is gone now.
17760   return BB;
17761 }
17762
17763 MachineBasicBlock *
17764 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17765                                     MachineBasicBlock *MBB) const {
17766   DebugLoc DL = MI->getDebugLoc();
17767   MachineFunction *MF = MBB->getParent();
17768   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17769   MachineRegisterInfo &MRI = MF->getRegInfo();
17770
17771   const BasicBlock *BB = MBB->getBasicBlock();
17772   MachineFunction::iterator I = MBB;
17773   ++I;
17774
17775   // Memory Reference
17776   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17777   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17778
17779   unsigned DstReg;
17780   unsigned MemOpndSlot = 0;
17781
17782   unsigned CurOp = 0;
17783
17784   DstReg = MI->getOperand(CurOp++).getReg();
17785   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17786   assert(RC->hasType(MVT::i32) && "Invalid destination!");
17787   unsigned mainDstReg = MRI.createVirtualRegister(RC);
17788   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17789
17790   MemOpndSlot = CurOp;
17791
17792   MVT PVT = getPointerTy();
17793   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17794          "Invalid Pointer Size!");
17795
17796   // For v = setjmp(buf), we generate
17797   //
17798   // thisMBB:
17799   //  buf[LabelOffset] = restoreMBB
17800   //  SjLjSetup restoreMBB
17801   //
17802   // mainMBB:
17803   //  v_main = 0
17804   //
17805   // sinkMBB:
17806   //  v = phi(main, restore)
17807   //
17808   // restoreMBB:
17809   //  v_restore = 1
17810
17811   MachineBasicBlock *thisMBB = MBB;
17812   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17813   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17814   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17815   MF->insert(I, mainMBB);
17816   MF->insert(I, sinkMBB);
17817   MF->push_back(restoreMBB);
17818
17819   MachineInstrBuilder MIB;
17820
17821   // Transfer the remainder of BB and its successor edges to sinkMBB.
17822   sinkMBB->splice(sinkMBB->begin(), MBB,
17823                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17824   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17825
17826   // thisMBB:
17827   unsigned PtrStoreOpc = 0;
17828   unsigned LabelReg = 0;
17829   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17830   Reloc::Model RM = MF->getTarget().getRelocationModel();
17831   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17832                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17833
17834   // Prepare IP either in reg or imm.
17835   if (!UseImmLabel) {
17836     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17837     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17838     LabelReg = MRI.createVirtualRegister(PtrRC);
17839     if (Subtarget->is64Bit()) {
17840       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17841               .addReg(X86::RIP)
17842               .addImm(0)
17843               .addReg(0)
17844               .addMBB(restoreMBB)
17845               .addReg(0);
17846     } else {
17847       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17848       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17849               .addReg(XII->getGlobalBaseReg(MF))
17850               .addImm(0)
17851               .addReg(0)
17852               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17853               .addReg(0);
17854     }
17855   } else
17856     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17857   // Store IP
17858   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17859   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17860     if (i == X86::AddrDisp)
17861       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17862     else
17863       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17864   }
17865   if (!UseImmLabel)
17866     MIB.addReg(LabelReg);
17867   else
17868     MIB.addMBB(restoreMBB);
17869   MIB.setMemRefs(MMOBegin, MMOEnd);
17870   // Setup
17871   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17872           .addMBB(restoreMBB);
17873
17874   const X86RegisterInfo *RegInfo =
17875     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17876   MIB.addRegMask(RegInfo->getNoPreservedMask());
17877   thisMBB->addSuccessor(mainMBB);
17878   thisMBB->addSuccessor(restoreMBB);
17879
17880   // mainMBB:
17881   //  EAX = 0
17882   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17883   mainMBB->addSuccessor(sinkMBB);
17884
17885   // sinkMBB:
17886   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17887           TII->get(X86::PHI), DstReg)
17888     .addReg(mainDstReg).addMBB(mainMBB)
17889     .addReg(restoreDstReg).addMBB(restoreMBB);
17890
17891   // restoreMBB:
17892   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17893   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17894   restoreMBB->addSuccessor(sinkMBB);
17895
17896   MI->eraseFromParent();
17897   return sinkMBB;
17898 }
17899
17900 MachineBasicBlock *
17901 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17902                                      MachineBasicBlock *MBB) const {
17903   DebugLoc DL = MI->getDebugLoc();
17904   MachineFunction *MF = MBB->getParent();
17905   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17906   MachineRegisterInfo &MRI = MF->getRegInfo();
17907
17908   // Memory Reference
17909   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17910   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17911
17912   MVT PVT = getPointerTy();
17913   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17914          "Invalid Pointer Size!");
17915
17916   const TargetRegisterClass *RC =
17917     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17918   unsigned Tmp = MRI.createVirtualRegister(RC);
17919   // Since FP is only updated here but NOT referenced, it's treated as GPR.
17920   const X86RegisterInfo *RegInfo =
17921     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17922   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17923   unsigned SP = RegInfo->getStackRegister();
17924
17925   MachineInstrBuilder MIB;
17926
17927   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17928   const int64_t SPOffset = 2 * PVT.getStoreSize();
17929
17930   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17931   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17932
17933   // Reload FP
17934   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17935   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17936     MIB.addOperand(MI->getOperand(i));
17937   MIB.setMemRefs(MMOBegin, MMOEnd);
17938   // Reload IP
17939   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17940   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17941     if (i == X86::AddrDisp)
17942       MIB.addDisp(MI->getOperand(i), LabelOffset);
17943     else
17944       MIB.addOperand(MI->getOperand(i));
17945   }
17946   MIB.setMemRefs(MMOBegin, MMOEnd);
17947   // Reload SP
17948   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17949   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17950     if (i == X86::AddrDisp)
17951       MIB.addDisp(MI->getOperand(i), SPOffset);
17952     else
17953       MIB.addOperand(MI->getOperand(i));
17954   }
17955   MIB.setMemRefs(MMOBegin, MMOEnd);
17956   // Jump
17957   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17958
17959   MI->eraseFromParent();
17960   return MBB;
17961 }
17962
17963 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17964 // accumulator loops. Writing back to the accumulator allows the coalescer
17965 // to remove extra copies in the loop.   
17966 MachineBasicBlock *
17967 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17968                                  MachineBasicBlock *MBB) const {
17969   MachineOperand &AddendOp = MI->getOperand(3);
17970
17971   // Bail out early if the addend isn't a register - we can't switch these.
17972   if (!AddendOp.isReg())
17973     return MBB;
17974
17975   MachineFunction &MF = *MBB->getParent();
17976   MachineRegisterInfo &MRI = MF.getRegInfo();
17977
17978   // Check whether the addend is defined by a PHI:
17979   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17980   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17981   if (!AddendDef.isPHI())
17982     return MBB;
17983
17984   // Look for the following pattern:
17985   // loop:
17986   //   %addend = phi [%entry, 0], [%loop, %result]
17987   //   ...
17988   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17989
17990   // Replace with:
17991   //   loop:
17992   //   %addend = phi [%entry, 0], [%loop, %result]
17993   //   ...
17994   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17995
17996   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17997     assert(AddendDef.getOperand(i).isReg());
17998     MachineOperand PHISrcOp = AddendDef.getOperand(i);
17999     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18000     if (&PHISrcInst == MI) {
18001       // Found a matching instruction.
18002       unsigned NewFMAOpc = 0;
18003       switch (MI->getOpcode()) {
18004         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18005         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18006         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18007         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18008         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18009         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18010         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18011         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18012         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18013         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18014         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18015         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18016         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18017         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18018         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18019         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18020         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18021         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18022         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18023         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18024         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18025         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18026         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18027         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18028         default: llvm_unreachable("Unrecognized FMA variant.");
18029       }
18030
18031       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18032       MachineInstrBuilder MIB =
18033         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18034         .addOperand(MI->getOperand(0))
18035         .addOperand(MI->getOperand(3))
18036         .addOperand(MI->getOperand(2))
18037         .addOperand(MI->getOperand(1));
18038       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18039       MI->eraseFromParent();
18040     }
18041   }
18042
18043   return MBB;
18044 }
18045
18046 MachineBasicBlock *
18047 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18048                                                MachineBasicBlock *BB) const {
18049   switch (MI->getOpcode()) {
18050   default: llvm_unreachable("Unexpected instr type to insert");
18051   case X86::TAILJMPd64:
18052   case X86::TAILJMPr64:
18053   case X86::TAILJMPm64:
18054     llvm_unreachable("TAILJMP64 would not be touched here.");
18055   case X86::TCRETURNdi64:
18056   case X86::TCRETURNri64:
18057   case X86::TCRETURNmi64:
18058     return BB;
18059   case X86::WIN_ALLOCA:
18060     return EmitLoweredWinAlloca(MI, BB);
18061   case X86::SEG_ALLOCA_32:
18062     return EmitLoweredSegAlloca(MI, BB, false);
18063   case X86::SEG_ALLOCA_64:
18064     return EmitLoweredSegAlloca(MI, BB, true);
18065   case X86::TLSCall_32:
18066   case X86::TLSCall_64:
18067     return EmitLoweredTLSCall(MI, BB);
18068   case X86::CMOV_GR8:
18069   case X86::CMOV_FR32:
18070   case X86::CMOV_FR64:
18071   case X86::CMOV_V4F32:
18072   case X86::CMOV_V2F64:
18073   case X86::CMOV_V2I64:
18074   case X86::CMOV_V8F32:
18075   case X86::CMOV_V4F64:
18076   case X86::CMOV_V4I64:
18077   case X86::CMOV_V16F32:
18078   case X86::CMOV_V8F64:
18079   case X86::CMOV_V8I64:
18080   case X86::CMOV_GR16:
18081   case X86::CMOV_GR32:
18082   case X86::CMOV_RFP32:
18083   case X86::CMOV_RFP64:
18084   case X86::CMOV_RFP80:
18085     return EmitLoweredSelect(MI, BB);
18086
18087   case X86::FP32_TO_INT16_IN_MEM:
18088   case X86::FP32_TO_INT32_IN_MEM:
18089   case X86::FP32_TO_INT64_IN_MEM:
18090   case X86::FP64_TO_INT16_IN_MEM:
18091   case X86::FP64_TO_INT32_IN_MEM:
18092   case X86::FP64_TO_INT64_IN_MEM:
18093   case X86::FP80_TO_INT16_IN_MEM:
18094   case X86::FP80_TO_INT32_IN_MEM:
18095   case X86::FP80_TO_INT64_IN_MEM: {
18096     MachineFunction *F = BB->getParent();
18097     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18098     DebugLoc DL = MI->getDebugLoc();
18099
18100     // Change the floating point control register to use "round towards zero"
18101     // mode when truncating to an integer value.
18102     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18103     addFrameReference(BuildMI(*BB, MI, DL,
18104                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18105
18106     // Load the old value of the high byte of the control word...
18107     unsigned OldCW =
18108       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18109     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18110                       CWFrameIdx);
18111
18112     // Set the high part to be round to zero...
18113     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18114       .addImm(0xC7F);
18115
18116     // Reload the modified control word now...
18117     addFrameReference(BuildMI(*BB, MI, DL,
18118                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18119
18120     // Restore the memory image of control word to original value
18121     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18122       .addReg(OldCW);
18123
18124     // Get the X86 opcode to use.
18125     unsigned Opc;
18126     switch (MI->getOpcode()) {
18127     default: llvm_unreachable("illegal opcode!");
18128     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18129     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18130     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18131     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18132     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18133     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18134     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18135     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18136     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18137     }
18138
18139     X86AddressMode AM;
18140     MachineOperand &Op = MI->getOperand(0);
18141     if (Op.isReg()) {
18142       AM.BaseType = X86AddressMode::RegBase;
18143       AM.Base.Reg = Op.getReg();
18144     } else {
18145       AM.BaseType = X86AddressMode::FrameIndexBase;
18146       AM.Base.FrameIndex = Op.getIndex();
18147     }
18148     Op = MI->getOperand(1);
18149     if (Op.isImm())
18150       AM.Scale = Op.getImm();
18151     Op = MI->getOperand(2);
18152     if (Op.isImm())
18153       AM.IndexReg = Op.getImm();
18154     Op = MI->getOperand(3);
18155     if (Op.isGlobal()) {
18156       AM.GV = Op.getGlobal();
18157     } else {
18158       AM.Disp = Op.getImm();
18159     }
18160     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18161                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18162
18163     // Reload the original control word now.
18164     addFrameReference(BuildMI(*BB, MI, DL,
18165                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18166
18167     MI->eraseFromParent();   // The pseudo instruction is gone now.
18168     return BB;
18169   }
18170     // String/text processing lowering.
18171   case X86::PCMPISTRM128REG:
18172   case X86::VPCMPISTRM128REG:
18173   case X86::PCMPISTRM128MEM:
18174   case X86::VPCMPISTRM128MEM:
18175   case X86::PCMPESTRM128REG:
18176   case X86::VPCMPESTRM128REG:
18177   case X86::PCMPESTRM128MEM:
18178   case X86::VPCMPESTRM128MEM:
18179     assert(Subtarget->hasSSE42() &&
18180            "Target must have SSE4.2 or AVX features enabled");
18181     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18182
18183   // String/text processing lowering.
18184   case X86::PCMPISTRIREG:
18185   case X86::VPCMPISTRIREG:
18186   case X86::PCMPISTRIMEM:
18187   case X86::VPCMPISTRIMEM:
18188   case X86::PCMPESTRIREG:
18189   case X86::VPCMPESTRIREG:
18190   case X86::PCMPESTRIMEM:
18191   case X86::VPCMPESTRIMEM:
18192     assert(Subtarget->hasSSE42() &&
18193            "Target must have SSE4.2 or AVX features enabled");
18194     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18195
18196   // Thread synchronization.
18197   case X86::MONITOR:
18198     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18199
18200   // xbegin
18201   case X86::XBEGIN:
18202     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18203
18204   case X86::VASTART_SAVE_XMM_REGS:
18205     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18206
18207   case X86::VAARG_64:
18208     return EmitVAARG64WithCustomInserter(MI, BB);
18209
18210   case X86::EH_SjLj_SetJmp32:
18211   case X86::EH_SjLj_SetJmp64:
18212     return emitEHSjLjSetJmp(MI, BB);
18213
18214   case X86::EH_SjLj_LongJmp32:
18215   case X86::EH_SjLj_LongJmp64:
18216     return emitEHSjLjLongJmp(MI, BB);
18217
18218   case TargetOpcode::STACKMAP:
18219   case TargetOpcode::PATCHPOINT:
18220     return emitPatchPoint(MI, BB);
18221
18222   case X86::VFMADDPDr213r:
18223   case X86::VFMADDPSr213r:
18224   case X86::VFMADDSDr213r:
18225   case X86::VFMADDSSr213r:
18226   case X86::VFMSUBPDr213r:
18227   case X86::VFMSUBPSr213r:
18228   case X86::VFMSUBSDr213r:
18229   case X86::VFMSUBSSr213r:
18230   case X86::VFNMADDPDr213r:
18231   case X86::VFNMADDPSr213r:
18232   case X86::VFNMADDSDr213r:
18233   case X86::VFNMADDSSr213r:
18234   case X86::VFNMSUBPDr213r:
18235   case X86::VFNMSUBPSr213r:
18236   case X86::VFNMSUBSDr213r:
18237   case X86::VFNMSUBSSr213r:
18238   case X86::VFMADDPDr213rY:
18239   case X86::VFMADDPSr213rY:
18240   case X86::VFMSUBPDr213rY:
18241   case X86::VFMSUBPSr213rY:
18242   case X86::VFNMADDPDr213rY:
18243   case X86::VFNMADDPSr213rY:
18244   case X86::VFNMSUBPDr213rY:
18245   case X86::VFNMSUBPSr213rY:
18246     return emitFMA3Instr(MI, BB);
18247   }
18248 }
18249
18250 //===----------------------------------------------------------------------===//
18251 //                           X86 Optimization Hooks
18252 //===----------------------------------------------------------------------===//
18253
18254 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18255                                                       APInt &KnownZero,
18256                                                       APInt &KnownOne,
18257                                                       const SelectionDAG &DAG,
18258                                                       unsigned Depth) const {
18259   unsigned BitWidth = KnownZero.getBitWidth();
18260   unsigned Opc = Op.getOpcode();
18261   assert((Opc >= ISD::BUILTIN_OP_END ||
18262           Opc == ISD::INTRINSIC_WO_CHAIN ||
18263           Opc == ISD::INTRINSIC_W_CHAIN ||
18264           Opc == ISD::INTRINSIC_VOID) &&
18265          "Should use MaskedValueIsZero if you don't know whether Op"
18266          " is a target node!");
18267
18268   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18269   switch (Opc) {
18270   default: break;
18271   case X86ISD::ADD:
18272   case X86ISD::SUB:
18273   case X86ISD::ADC:
18274   case X86ISD::SBB:
18275   case X86ISD::SMUL:
18276   case X86ISD::UMUL:
18277   case X86ISD::INC:
18278   case X86ISD::DEC:
18279   case X86ISD::OR:
18280   case X86ISD::XOR:
18281   case X86ISD::AND:
18282     // These nodes' second result is a boolean.
18283     if (Op.getResNo() == 0)
18284       break;
18285     // Fallthrough
18286   case X86ISD::SETCC:
18287     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18288     break;
18289   case ISD::INTRINSIC_WO_CHAIN: {
18290     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18291     unsigned NumLoBits = 0;
18292     switch (IntId) {
18293     default: break;
18294     case Intrinsic::x86_sse_movmsk_ps:
18295     case Intrinsic::x86_avx_movmsk_ps_256:
18296     case Intrinsic::x86_sse2_movmsk_pd:
18297     case Intrinsic::x86_avx_movmsk_pd_256:
18298     case Intrinsic::x86_mmx_pmovmskb:
18299     case Intrinsic::x86_sse2_pmovmskb_128:
18300     case Intrinsic::x86_avx2_pmovmskb: {
18301       // High bits of movmskp{s|d}, pmovmskb are known zero.
18302       switch (IntId) {
18303         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18304         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18305         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18306         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18307         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18308         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18309         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18310         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18311       }
18312       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18313       break;
18314     }
18315     }
18316     break;
18317   }
18318   }
18319 }
18320
18321 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18322   SDValue Op,
18323   const SelectionDAG &,
18324   unsigned Depth) const {
18325   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18326   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18327     return Op.getValueType().getScalarType().getSizeInBits();
18328
18329   // Fallback case.
18330   return 1;
18331 }
18332
18333 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18334 /// node is a GlobalAddress + offset.
18335 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18336                                        const GlobalValue* &GA,
18337                                        int64_t &Offset) const {
18338   if (N->getOpcode() == X86ISD::Wrapper) {
18339     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18340       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18341       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18342       return true;
18343     }
18344   }
18345   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18346 }
18347
18348 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18349 /// same as extracting the high 128-bit part of 256-bit vector and then
18350 /// inserting the result into the low part of a new 256-bit vector
18351 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18352   EVT VT = SVOp->getValueType(0);
18353   unsigned NumElems = VT.getVectorNumElements();
18354
18355   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18356   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18357     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18358         SVOp->getMaskElt(j) >= 0)
18359       return false;
18360
18361   return true;
18362 }
18363
18364 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18365 /// same as extracting the low 128-bit part of 256-bit vector and then
18366 /// inserting the result into the high part of a new 256-bit vector
18367 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18368   EVT VT = SVOp->getValueType(0);
18369   unsigned NumElems = VT.getVectorNumElements();
18370
18371   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18372   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18373     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18374         SVOp->getMaskElt(j) >= 0)
18375       return false;
18376
18377   return true;
18378 }
18379
18380 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18381 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18382                                         TargetLowering::DAGCombinerInfo &DCI,
18383                                         const X86Subtarget* Subtarget) {
18384   SDLoc dl(N);
18385   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18386   SDValue V1 = SVOp->getOperand(0);
18387   SDValue V2 = SVOp->getOperand(1);
18388   EVT VT = SVOp->getValueType(0);
18389   unsigned NumElems = VT.getVectorNumElements();
18390
18391   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18392       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18393     //
18394     //                   0,0,0,...
18395     //                      |
18396     //    V      UNDEF    BUILD_VECTOR    UNDEF
18397     //     \      /           \           /
18398     //  CONCAT_VECTOR         CONCAT_VECTOR
18399     //         \                  /
18400     //          \                /
18401     //          RESULT: V + zero extended
18402     //
18403     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18404         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18405         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18406       return SDValue();
18407
18408     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18409       return SDValue();
18410
18411     // To match the shuffle mask, the first half of the mask should
18412     // be exactly the first vector, and all the rest a splat with the
18413     // first element of the second one.
18414     for (unsigned i = 0; i != NumElems/2; ++i)
18415       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18416           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18417         return SDValue();
18418
18419     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18420     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18421       if (Ld->hasNUsesOfValue(1, 0)) {
18422         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18423         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18424         SDValue ResNode =
18425           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18426                                   Ld->getMemoryVT(),
18427                                   Ld->getPointerInfo(),
18428                                   Ld->getAlignment(),
18429                                   false/*isVolatile*/, true/*ReadMem*/,
18430                                   false/*WriteMem*/);
18431
18432         // Make sure the newly-created LOAD is in the same position as Ld in
18433         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18434         // and update uses of Ld's output chain to use the TokenFactor.
18435         if (Ld->hasAnyUseOfValue(1)) {
18436           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18437                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18438           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18439           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18440                                  SDValue(ResNode.getNode(), 1));
18441         }
18442
18443         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18444       }
18445     }
18446
18447     // Emit a zeroed vector and insert the desired subvector on its
18448     // first half.
18449     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18450     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18451     return DCI.CombineTo(N, InsV);
18452   }
18453
18454   //===--------------------------------------------------------------------===//
18455   // Combine some shuffles into subvector extracts and inserts:
18456   //
18457
18458   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18459   if (isShuffleHigh128VectorInsertLow(SVOp)) {
18460     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18461     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18462     return DCI.CombineTo(N, InsV);
18463   }
18464
18465   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18466   if (isShuffleLow128VectorInsertHigh(SVOp)) {
18467     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18468     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18469     return DCI.CombineTo(N, InsV);
18470   }
18471
18472   return SDValue();
18473 }
18474
18475 /// \brief Get the PSHUF-style mask from PSHUF node.
18476 ///
18477 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18478 /// PSHUF-style masks that can be reused with such instructions.
18479 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18480   SmallVector<int, 4> Mask;
18481   bool IsUnary;
18482   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18483   (void)HaveMask;
18484   assert(HaveMask);
18485
18486   switch (N.getOpcode()) {
18487   case X86ISD::PSHUFD:
18488     return Mask;
18489   case X86ISD::PSHUFLW:
18490     Mask.resize(4);
18491     return Mask;
18492   case X86ISD::PSHUFHW:
18493     Mask.erase(Mask.begin(), Mask.begin() + 4);
18494     for (int &M : Mask)
18495       M -= 4;
18496     return Mask;
18497   default:
18498     llvm_unreachable("No valid shuffle instruction found!");
18499   }
18500 }
18501
18502 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18503 ///
18504 /// We walk up the chain and look for a combinable shuffle, skipping over
18505 /// shuffles that we could hoist this shuffle's transformation past without
18506 /// altering anything.
18507 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18508                                          SelectionDAG &DAG,
18509                                          TargetLowering::DAGCombinerInfo &DCI) {
18510   assert(N.getOpcode() == X86ISD::PSHUFD &&
18511          "Called with something other than an x86 128-bit half shuffle!");
18512   SDLoc DL(N);
18513
18514   // Walk up a single-use chain looking for a combinable shuffle.
18515   SDValue V = N.getOperand(0);
18516   for (; V.hasOneUse(); V = V.getOperand(0)) {
18517     switch (V.getOpcode()) {
18518     default:
18519       return false; // Nothing combined!
18520
18521     case ISD::BITCAST:
18522       // Skip bitcasts as we always know the type for the target specific
18523       // instructions.
18524       continue;
18525
18526     case X86ISD::PSHUFD:
18527       // Found another dword shuffle.
18528       break;
18529
18530     case X86ISD::PSHUFLW:
18531       // Check that the low words (being shuffled) are the identity in the
18532       // dword shuffle, and the high words are self-contained.
18533       if (Mask[0] != 0 || Mask[1] != 1 ||
18534           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18535         return false;
18536
18537       continue;
18538
18539     case X86ISD::PSHUFHW:
18540       // Check that the high words (being shuffled) are the identity in the
18541       // dword shuffle, and the low words are self-contained.
18542       if (Mask[2] != 2 || Mask[3] != 3 ||
18543           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18544         return false;
18545
18546       continue;
18547
18548     case X86ISD::UNPCKL:
18549     case X86ISD::UNPCKH:
18550       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
18551       // shuffle into a preceding word shuffle.
18552       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
18553         return false;
18554
18555       // Search for a half-shuffle which we can combine with.
18556       unsigned CombineOp =
18557           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18558       if (V.getOperand(0) != V.getOperand(1) ||
18559           !V->isOnlyUserOf(V.getOperand(0).getNode()))
18560         return false;
18561       V = V.getOperand(0);
18562       do {
18563         switch (V.getOpcode()) {
18564         default:
18565           return false; // Nothing to combine.
18566
18567         case X86ISD::PSHUFLW:
18568         case X86ISD::PSHUFHW:
18569           if (V.getOpcode() == CombineOp)
18570             break;
18571
18572           // Fallthrough!
18573         case ISD::BITCAST:
18574           V = V.getOperand(0);
18575           continue;
18576         }
18577         break;
18578       } while (V.hasOneUse());
18579       break;
18580     }
18581     // Break out of the loop if we break out of the switch.
18582     break;
18583   }
18584
18585   if (!V.hasOneUse())
18586     // We fell out of the loop without finding a viable combining instruction.
18587     return false;
18588
18589   // Record the old value to use in RAUW-ing.
18590   SDValue Old = V;
18591
18592   // Merge this node's mask and our incoming mask.
18593   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18594   for (int &M : Mask)
18595     M = VMask[M];
18596   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
18597                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18598
18599   // It is possible that one of the combinable shuffles was completely absorbed
18600   // by the other, just replace it and revisit all users in that case.
18601   if (Old.getNode() == V.getNode()) {
18602     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
18603     return true;
18604   }
18605
18606   // Replace N with its operand as we're going to combine that shuffle away.
18607   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18608
18609   // Replace the combinable shuffle with the combined one, updating all users
18610   // so that we re-evaluate the chain here.
18611   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18612   return true;
18613 }
18614
18615 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18616 ///
18617 /// We walk up the chain, skipping shuffles of the other half and looking
18618 /// through shuffles which switch halves trying to find a shuffle of the same
18619 /// pair of dwords.
18620 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18621                                         SelectionDAG &DAG,
18622                                         TargetLowering::DAGCombinerInfo &DCI) {
18623   assert(
18624       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18625       "Called with something other than an x86 128-bit half shuffle!");
18626   SDLoc DL(N);
18627   unsigned CombineOpcode = N.getOpcode();
18628
18629   // Walk up a single-use chain looking for a combinable shuffle.
18630   SDValue V = N.getOperand(0);
18631   for (; V.hasOneUse(); V = V.getOperand(0)) {
18632     switch (V.getOpcode()) {
18633     default:
18634       return false; // Nothing combined!
18635
18636     case ISD::BITCAST:
18637       // Skip bitcasts as we always know the type for the target specific
18638       // instructions.
18639       continue;
18640
18641     case X86ISD::PSHUFLW:
18642     case X86ISD::PSHUFHW:
18643       if (V.getOpcode() == CombineOpcode)
18644         break;
18645
18646       // Other-half shuffles are no-ops.
18647       continue;
18648
18649     case X86ISD::PSHUFD: {
18650       // We can only handle pshufd if the half we are combining either stays in
18651       // its half, or switches to the other half. Bail if one of these isn't
18652       // true.
18653       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18654       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18655       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18656             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18657         return false;
18658
18659       // Map the mask through the pshufd and keep walking up the chain.
18660       for (int i = 0; i < 4; ++i)
18661         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18662
18663       // Switch halves if the pshufd does.
18664       CombineOpcode =
18665           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18666       continue;
18667     }
18668     }
18669     // Break out of the loop if we break out of the switch.
18670     break;
18671   }
18672
18673   if (!V.hasOneUse())
18674     // We fell out of the loop without finding a viable combining instruction.
18675     return false;
18676
18677   // Record the old value to use in RAUW-ing.
18678   SDValue Old = V;
18679
18680   // Merge this node's mask and our incoming mask (adjusted to account for all
18681   // the pshufd instructions encountered).
18682   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18683   for (int &M : Mask)
18684     M = VMask[M];
18685   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18686                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18687
18688   // Replace N with its operand as we're going to combine that shuffle away.
18689   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18690
18691   // Replace the combinable shuffle with the combined one, updating all users
18692   // so that we re-evaluate the chain here.
18693   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18694   return true;
18695 }
18696
18697 /// \brief Try to combine x86 target specific shuffles.
18698 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18699                                            TargetLowering::DAGCombinerInfo &DCI,
18700                                            const X86Subtarget *Subtarget) {
18701   SDLoc DL(N);
18702   MVT VT = N.getSimpleValueType();
18703   SmallVector<int, 4> Mask;
18704
18705   switch (N.getOpcode()) {
18706   case X86ISD::PSHUFD:
18707   case X86ISD::PSHUFLW:
18708   case X86ISD::PSHUFHW:
18709     Mask = getPSHUFShuffleMask(N);
18710     assert(Mask.size() == 4);
18711     break;
18712   default:
18713     return SDValue();
18714   }
18715
18716   // Nuke no-op shuffles that show up after combining.
18717   if (isNoopShuffleMask(Mask))
18718     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18719
18720   // Look for simplifications involving one or two shuffle instructions.
18721   SDValue V = N.getOperand(0);
18722   switch (N.getOpcode()) {
18723   default:
18724     break;
18725   case X86ISD::PSHUFLW:
18726   case X86ISD::PSHUFHW:
18727     assert(VT == MVT::v8i16);
18728     (void)VT;
18729
18730     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18731       return SDValue(); // We combined away this shuffle, so we're done.
18732
18733     // See if this reduces to a PSHUFD which is no more expensive and can
18734     // combine with more operations.
18735     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18736         areAdjacentMasksSequential(Mask)) {
18737       int DMask[] = {-1, -1, -1, -1};
18738       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18739       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18740       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18741       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18742       DCI.AddToWorklist(V.getNode());
18743       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18744                       getV4X86ShuffleImm8ForMask(DMask, DAG));
18745       DCI.AddToWorklist(V.getNode());
18746       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18747     }
18748
18749     // Look for shuffle patterns which can be implemented as a single unpack.
18750     // FIXME: This doesn't handle the location of the PSHUFD generically, and
18751     // only works when we have a PSHUFD followed by two half-shuffles.
18752     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
18753         (V.getOpcode() == X86ISD::PSHUFLW ||
18754          V.getOpcode() == X86ISD::PSHUFHW) &&
18755         V.getOpcode() != N.getOpcode() &&
18756         V.hasOneUse()) {
18757       SDValue D = V.getOperand(0);
18758       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
18759         D = D.getOperand(0);
18760       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
18761         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18762         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
18763         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
18764         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
18765         int WordMask[8];
18766         for (int i = 0; i < 4; ++i) {
18767           WordMask[i + NOffset] = Mask[i] + NOffset;
18768           WordMask[i + VOffset] = VMask[i] + VOffset;
18769         }
18770         // Map the word mask through the DWord mask.
18771         int MappedMask[8];
18772         for (int i = 0; i < 8; ++i)
18773           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
18774         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
18775         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
18776         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
18777                        std::begin(UnpackLoMask)) ||
18778             std::equal(std::begin(MappedMask), std::end(MappedMask),
18779                        std::begin(UnpackHiMask))) {
18780           // We can replace all three shuffles with an unpack.
18781           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
18782           DCI.AddToWorklist(V.getNode());
18783           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
18784                                                 : X86ISD::UNPCKH,
18785                              DL, MVT::v8i16, V, V);
18786         }
18787       }
18788     }
18789
18790     break;
18791
18792   case X86ISD::PSHUFD:
18793     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
18794       return SDValue(); // We combined away this shuffle.
18795
18796     break;
18797   }
18798
18799   return SDValue();
18800 }
18801
18802 /// PerformShuffleCombine - Performs several different shuffle combines.
18803 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
18804                                      TargetLowering::DAGCombinerInfo &DCI,
18805                                      const X86Subtarget *Subtarget) {
18806   SDLoc dl(N);
18807   SDValue N0 = N->getOperand(0);
18808   SDValue N1 = N->getOperand(1);
18809   EVT VT = N->getValueType(0);
18810
18811   // Don't create instructions with illegal types after legalize types has run.
18812   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18813   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18814     return SDValue();
18815
18816   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18817   if (Subtarget->hasFp256() && VT.is256BitVector() &&
18818       N->getOpcode() == ISD::VECTOR_SHUFFLE)
18819     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18820
18821   // During Type Legalization, when promoting illegal vector types,
18822   // the backend might introduce new shuffle dag nodes and bitcasts.
18823   //
18824   // This code performs the following transformation:
18825   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18826   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18827   //
18828   // We do this only if both the bitcast and the BINOP dag nodes have
18829   // one use. Also, perform this transformation only if the new binary
18830   // operation is legal. This is to avoid introducing dag nodes that
18831   // potentially need to be further expanded (or custom lowered) into a
18832   // less optimal sequence of dag nodes.
18833   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18834       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18835       N0.getOpcode() == ISD::BITCAST) {
18836     SDValue BC0 = N0.getOperand(0);
18837     EVT SVT = BC0.getValueType();
18838     unsigned Opcode = BC0.getOpcode();
18839     unsigned NumElts = VT.getVectorNumElements();
18840     
18841     if (BC0.hasOneUse() && SVT.isVector() &&
18842         SVT.getVectorNumElements() * 2 == NumElts &&
18843         TLI.isOperationLegal(Opcode, VT)) {
18844       bool CanFold = false;
18845       switch (Opcode) {
18846       default : break;
18847       case ISD::ADD :
18848       case ISD::FADD :
18849       case ISD::SUB :
18850       case ISD::FSUB :
18851       case ISD::MUL :
18852       case ISD::FMUL :
18853         CanFold = true;
18854       }
18855
18856       unsigned SVTNumElts = SVT.getVectorNumElements();
18857       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18858       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18859         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18860       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18861         CanFold = SVOp->getMaskElt(i) < 0;
18862
18863       if (CanFold) {
18864         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18865         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18866         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18867         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18868       }
18869     }
18870   }
18871
18872   // Only handle 128 wide vector from here on.
18873   if (!VT.is128BitVector())
18874     return SDValue();
18875
18876   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18877   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18878   // consecutive, non-overlapping, and in the right order.
18879   SmallVector<SDValue, 16> Elts;
18880   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18881     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18882
18883   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18884   if (LD.getNode())
18885     return LD;
18886
18887   if (isTargetShuffle(N->getOpcode())) {
18888     SDValue Shuffle =
18889         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
18890     if (Shuffle.getNode())
18891       return Shuffle;
18892   }
18893
18894   return SDValue();
18895 }
18896
18897 /// PerformTruncateCombine - Converts truncate operation to
18898 /// a sequence of vector shuffle operations.
18899 /// It is possible when we truncate 256-bit vector to 128-bit vector
18900 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18901                                       TargetLowering::DAGCombinerInfo &DCI,
18902                                       const X86Subtarget *Subtarget)  {
18903   return SDValue();
18904 }
18905
18906 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18907 /// specific shuffle of a load can be folded into a single element load.
18908 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18909 /// shuffles have been customed lowered so we need to handle those here.
18910 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18911                                          TargetLowering::DAGCombinerInfo &DCI) {
18912   if (DCI.isBeforeLegalizeOps())
18913     return SDValue();
18914
18915   SDValue InVec = N->getOperand(0);
18916   SDValue EltNo = N->getOperand(1);
18917
18918   if (!isa<ConstantSDNode>(EltNo))
18919     return SDValue();
18920
18921   EVT VT = InVec.getValueType();
18922
18923   bool HasShuffleIntoBitcast = false;
18924   if (InVec.getOpcode() == ISD::BITCAST) {
18925     // Don't duplicate a load with other uses.
18926     if (!InVec.hasOneUse())
18927       return SDValue();
18928     EVT BCVT = InVec.getOperand(0).getValueType();
18929     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18930       return SDValue();
18931     InVec = InVec.getOperand(0);
18932     HasShuffleIntoBitcast = true;
18933   }
18934
18935   if (!isTargetShuffle(InVec.getOpcode()))
18936     return SDValue();
18937
18938   // Don't duplicate a load with other uses.
18939   if (!InVec.hasOneUse())
18940     return SDValue();
18941
18942   SmallVector<int, 16> ShuffleMask;
18943   bool UnaryShuffle;
18944   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18945                             UnaryShuffle))
18946     return SDValue();
18947
18948   // Select the input vector, guarding against out of range extract vector.
18949   unsigned NumElems = VT.getVectorNumElements();
18950   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18951   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18952   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18953                                          : InVec.getOperand(1);
18954
18955   // If inputs to shuffle are the same for both ops, then allow 2 uses
18956   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18957
18958   if (LdNode.getOpcode() == ISD::BITCAST) {
18959     // Don't duplicate a load with other uses.
18960     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18961       return SDValue();
18962
18963     AllowedUses = 1; // only allow 1 load use if we have a bitcast
18964     LdNode = LdNode.getOperand(0);
18965   }
18966
18967   if (!ISD::isNormalLoad(LdNode.getNode()))
18968     return SDValue();
18969
18970   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18971
18972   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18973     return SDValue();
18974
18975   if (HasShuffleIntoBitcast) {
18976     // If there's a bitcast before the shuffle, check if the load type and
18977     // alignment is valid.
18978     unsigned Align = LN0->getAlignment();
18979     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18980     unsigned NewAlign = TLI.getDataLayout()->
18981       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18982
18983     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18984       return SDValue();
18985   }
18986
18987   // All checks match so transform back to vector_shuffle so that DAG combiner
18988   // can finish the job
18989   SDLoc dl(N);
18990
18991   // Create shuffle node taking into account the case that its a unary shuffle
18992   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18993   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18994                                  InVec.getOperand(0), Shuffle,
18995                                  &ShuffleMask[0]);
18996   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18997   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18998                      EltNo);
18999 }
19000
19001 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19002 /// generation and convert it from being a bunch of shuffles and extracts
19003 /// to a simple store and scalar loads to extract the elements.
19004 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19005                                          TargetLowering::DAGCombinerInfo &DCI) {
19006   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19007   if (NewOp.getNode())
19008     return NewOp;
19009
19010   SDValue InputVector = N->getOperand(0);
19011
19012   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19013   // from mmx to v2i32 has a single usage.
19014   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19015       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19016       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19017     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19018                        N->getValueType(0),
19019                        InputVector.getNode()->getOperand(0));
19020
19021   // Only operate on vectors of 4 elements, where the alternative shuffling
19022   // gets to be more expensive.
19023   if (InputVector.getValueType() != MVT::v4i32)
19024     return SDValue();
19025
19026   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19027   // single use which is a sign-extend or zero-extend, and all elements are
19028   // used.
19029   SmallVector<SDNode *, 4> Uses;
19030   unsigned ExtractedElements = 0;
19031   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19032        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19033     if (UI.getUse().getResNo() != InputVector.getResNo())
19034       return SDValue();
19035
19036     SDNode *Extract = *UI;
19037     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19038       return SDValue();
19039
19040     if (Extract->getValueType(0) != MVT::i32)
19041       return SDValue();
19042     if (!Extract->hasOneUse())
19043       return SDValue();
19044     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19045         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19046       return SDValue();
19047     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19048       return SDValue();
19049
19050     // Record which element was extracted.
19051     ExtractedElements |=
19052       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19053
19054     Uses.push_back(Extract);
19055   }
19056
19057   // If not all the elements were used, this may not be worthwhile.
19058   if (ExtractedElements != 15)
19059     return SDValue();
19060
19061   // Ok, we've now decided to do the transformation.
19062   SDLoc dl(InputVector);
19063
19064   // Store the value to a temporary stack slot.
19065   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19066   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19067                             MachinePointerInfo(), false, false, 0);
19068
19069   // Replace each use (extract) with a load of the appropriate element.
19070   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19071        UE = Uses.end(); UI != UE; ++UI) {
19072     SDNode *Extract = *UI;
19073
19074     // cOMpute the element's address.
19075     SDValue Idx = Extract->getOperand(1);
19076     unsigned EltSize =
19077         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19078     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19079     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19080     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19081
19082     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19083                                      StackPtr, OffsetVal);
19084
19085     // Load the scalar.
19086     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19087                                      ScalarAddr, MachinePointerInfo(),
19088                                      false, false, false, 0);
19089
19090     // Replace the exact with the load.
19091     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19092   }
19093
19094   // The replacement was made in place; don't return anything.
19095   return SDValue();
19096 }
19097
19098 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19099 static std::pair<unsigned, bool>
19100 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19101                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19102   if (!VT.isVector())
19103     return std::make_pair(0, false);
19104
19105   bool NeedSplit = false;
19106   switch (VT.getSimpleVT().SimpleTy) {
19107   default: return std::make_pair(0, false);
19108   case MVT::v32i8:
19109   case MVT::v16i16:
19110   case MVT::v8i32:
19111     if (!Subtarget->hasAVX2())
19112       NeedSplit = true;
19113     if (!Subtarget->hasAVX())
19114       return std::make_pair(0, false);
19115     break;
19116   case MVT::v16i8:
19117   case MVT::v8i16:
19118   case MVT::v4i32:
19119     if (!Subtarget->hasSSE2())
19120       return std::make_pair(0, false);
19121   }
19122
19123   // SSE2 has only a small subset of the operations.
19124   bool hasUnsigned = Subtarget->hasSSE41() ||
19125                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19126   bool hasSigned = Subtarget->hasSSE41() ||
19127                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19128
19129   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19130
19131   unsigned Opc = 0;
19132   // Check for x CC y ? x : y.
19133   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19134       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19135     switch (CC) {
19136     default: break;
19137     case ISD::SETULT:
19138     case ISD::SETULE:
19139       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19140     case ISD::SETUGT:
19141     case ISD::SETUGE:
19142       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19143     case ISD::SETLT:
19144     case ISD::SETLE:
19145       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19146     case ISD::SETGT:
19147     case ISD::SETGE:
19148       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19149     }
19150   // Check for x CC y ? y : x -- a min/max with reversed arms.
19151   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19152              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19153     switch (CC) {
19154     default: break;
19155     case ISD::SETULT:
19156     case ISD::SETULE:
19157       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19158     case ISD::SETUGT:
19159     case ISD::SETUGE:
19160       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19161     case ISD::SETLT:
19162     case ISD::SETLE:
19163       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19164     case ISD::SETGT:
19165     case ISD::SETGE:
19166       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19167     }
19168   }
19169
19170   return std::make_pair(Opc, NeedSplit);
19171 }
19172
19173 static SDValue
19174 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19175                                       const X86Subtarget *Subtarget) {
19176   SDLoc dl(N);
19177   SDValue Cond = N->getOperand(0);
19178   SDValue LHS = N->getOperand(1);
19179   SDValue RHS = N->getOperand(2);
19180
19181   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19182     SDValue CondSrc = Cond->getOperand(0);
19183     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19184       Cond = CondSrc->getOperand(0);
19185   }
19186
19187   MVT VT = N->getSimpleValueType(0);
19188   MVT EltVT = VT.getVectorElementType();
19189   unsigned NumElems = VT.getVectorNumElements();
19190   // There is no blend with immediate in AVX-512.
19191   if (VT.is512BitVector())
19192     return SDValue();
19193
19194   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19195     return SDValue();
19196   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19197     return SDValue();
19198
19199   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19200     return SDValue();
19201
19202   unsigned MaskValue = 0;
19203   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19204     return SDValue();
19205
19206   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19207   for (unsigned i = 0; i < NumElems; ++i) {
19208     // Be sure we emit undef where we can.
19209     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19210       ShuffleMask[i] = -1;
19211     else
19212       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19213   }
19214
19215   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19216 }
19217
19218 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19219 /// nodes.
19220 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19221                                     TargetLowering::DAGCombinerInfo &DCI,
19222                                     const X86Subtarget *Subtarget) {
19223   SDLoc DL(N);
19224   SDValue Cond = N->getOperand(0);
19225   // Get the LHS/RHS of the select.
19226   SDValue LHS = N->getOperand(1);
19227   SDValue RHS = N->getOperand(2);
19228   EVT VT = LHS.getValueType();
19229   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19230
19231   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19232   // instructions match the semantics of the common C idiom x<y?x:y but not
19233   // x<=y?x:y, because of how they handle negative zero (which can be
19234   // ignored in unsafe-math mode).
19235   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19236       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19237       (Subtarget->hasSSE2() ||
19238        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19239     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19240
19241     unsigned Opcode = 0;
19242     // Check for x CC y ? x : y.
19243     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19244         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19245       switch (CC) {
19246       default: break;
19247       case ISD::SETULT:
19248         // Converting this to a min would handle NaNs incorrectly, and swapping
19249         // the operands would cause it to handle comparisons between positive
19250         // and negative zero incorrectly.
19251         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19252           if (!DAG.getTarget().Options.UnsafeFPMath &&
19253               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19254             break;
19255           std::swap(LHS, RHS);
19256         }
19257         Opcode = X86ISD::FMIN;
19258         break;
19259       case ISD::SETOLE:
19260         // Converting this to a min would handle comparisons between positive
19261         // and negative zero incorrectly.
19262         if (!DAG.getTarget().Options.UnsafeFPMath &&
19263             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19264           break;
19265         Opcode = X86ISD::FMIN;
19266         break;
19267       case ISD::SETULE:
19268         // Converting this to a min would handle both negative zeros and NaNs
19269         // incorrectly, but we can swap the operands to fix both.
19270         std::swap(LHS, RHS);
19271       case ISD::SETOLT:
19272       case ISD::SETLT:
19273       case ISD::SETLE:
19274         Opcode = X86ISD::FMIN;
19275         break;
19276
19277       case ISD::SETOGE:
19278         // Converting this to a max would handle comparisons between positive
19279         // and negative zero incorrectly.
19280         if (!DAG.getTarget().Options.UnsafeFPMath &&
19281             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19282           break;
19283         Opcode = X86ISD::FMAX;
19284         break;
19285       case ISD::SETUGT:
19286         // Converting this to a max would handle NaNs incorrectly, and swapping
19287         // the operands would cause it to handle comparisons between positive
19288         // and negative zero incorrectly.
19289         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19290           if (!DAG.getTarget().Options.UnsafeFPMath &&
19291               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19292             break;
19293           std::swap(LHS, RHS);
19294         }
19295         Opcode = X86ISD::FMAX;
19296         break;
19297       case ISD::SETUGE:
19298         // Converting this to a max would handle both negative zeros and NaNs
19299         // incorrectly, but we can swap the operands to fix both.
19300         std::swap(LHS, RHS);
19301       case ISD::SETOGT:
19302       case ISD::SETGT:
19303       case ISD::SETGE:
19304         Opcode = X86ISD::FMAX;
19305         break;
19306       }
19307     // Check for x CC y ? y : x -- a min/max with reversed arms.
19308     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19309                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19310       switch (CC) {
19311       default: break;
19312       case ISD::SETOGE:
19313         // Converting this to a min would handle comparisons between positive
19314         // and negative zero incorrectly, and swapping the operands would
19315         // cause it to handle NaNs incorrectly.
19316         if (!DAG.getTarget().Options.UnsafeFPMath &&
19317             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19318           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19319             break;
19320           std::swap(LHS, RHS);
19321         }
19322         Opcode = X86ISD::FMIN;
19323         break;
19324       case ISD::SETUGT:
19325         // Converting this to a min would handle NaNs incorrectly.
19326         if (!DAG.getTarget().Options.UnsafeFPMath &&
19327             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19328           break;
19329         Opcode = X86ISD::FMIN;
19330         break;
19331       case ISD::SETUGE:
19332         // Converting this to a min would handle both negative zeros and NaNs
19333         // incorrectly, but we can swap the operands to fix both.
19334         std::swap(LHS, RHS);
19335       case ISD::SETOGT:
19336       case ISD::SETGT:
19337       case ISD::SETGE:
19338         Opcode = X86ISD::FMIN;
19339         break;
19340
19341       case ISD::SETULT:
19342         // Converting this to a max would handle NaNs incorrectly.
19343         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19344           break;
19345         Opcode = X86ISD::FMAX;
19346         break;
19347       case ISD::SETOLE:
19348         // Converting this to a max would handle comparisons between positive
19349         // and negative zero incorrectly, and swapping the operands would
19350         // cause it to handle NaNs incorrectly.
19351         if (!DAG.getTarget().Options.UnsafeFPMath &&
19352             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19353           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19354             break;
19355           std::swap(LHS, RHS);
19356         }
19357         Opcode = X86ISD::FMAX;
19358         break;
19359       case ISD::SETULE:
19360         // Converting this to a max would handle both negative zeros and NaNs
19361         // incorrectly, but we can swap the operands to fix both.
19362         std::swap(LHS, RHS);
19363       case ISD::SETOLT:
19364       case ISD::SETLT:
19365       case ISD::SETLE:
19366         Opcode = X86ISD::FMAX;
19367         break;
19368       }
19369     }
19370
19371     if (Opcode)
19372       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19373   }
19374
19375   EVT CondVT = Cond.getValueType();
19376   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19377       CondVT.getVectorElementType() == MVT::i1) {
19378     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19379     // lowering on AVX-512. In this case we convert it to
19380     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19381     // The same situation for all 128 and 256-bit vectors of i8 and i16
19382     EVT OpVT = LHS.getValueType();
19383     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19384         (OpVT.getVectorElementType() == MVT::i8 ||
19385          OpVT.getVectorElementType() == MVT::i16)) {
19386       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19387       DCI.AddToWorklist(Cond.getNode());
19388       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19389     }
19390   }
19391   // If this is a select between two integer constants, try to do some
19392   // optimizations.
19393   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19394     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19395       // Don't do this for crazy integer types.
19396       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19397         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19398         // so that TrueC (the true value) is larger than FalseC.
19399         bool NeedsCondInvert = false;
19400
19401         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19402             // Efficiently invertible.
19403             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
19404              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
19405               isa<ConstantSDNode>(Cond.getOperand(1))))) {
19406           NeedsCondInvert = true;
19407           std::swap(TrueC, FalseC);
19408         }
19409
19410         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
19411         if (FalseC->getAPIntValue() == 0 &&
19412             TrueC->getAPIntValue().isPowerOf2()) {
19413           if (NeedsCondInvert) // Invert the condition if needed.
19414             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19415                                DAG.getConstant(1, Cond.getValueType()));
19416
19417           // Zero extend the condition if needed.
19418           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19419
19420           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19421           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19422                              DAG.getConstant(ShAmt, MVT::i8));
19423         }
19424
19425         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19426         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19427           if (NeedsCondInvert) // Invert the condition if needed.
19428             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19429                                DAG.getConstant(1, Cond.getValueType()));
19430
19431           // Zero extend the condition if needed.
19432           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19433                              FalseC->getValueType(0), Cond);
19434           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19435                              SDValue(FalseC, 0));
19436         }
19437
19438         // Optimize cases that will turn into an LEA instruction.  This requires
19439         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19440         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19441           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19442           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19443
19444           bool isFastMultiplier = false;
19445           if (Diff < 10) {
19446             switch ((unsigned char)Diff) {
19447               default: break;
19448               case 1:  // result = add base, cond
19449               case 2:  // result = lea base(    , cond*2)
19450               case 3:  // result = lea base(cond, cond*2)
19451               case 4:  // result = lea base(    , cond*4)
19452               case 5:  // result = lea base(cond, cond*4)
19453               case 8:  // result = lea base(    , cond*8)
19454               case 9:  // result = lea base(cond, cond*8)
19455                 isFastMultiplier = true;
19456                 break;
19457             }
19458           }
19459
19460           if (isFastMultiplier) {
19461             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19462             if (NeedsCondInvert) // Invert the condition if needed.
19463               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19464                                  DAG.getConstant(1, Cond.getValueType()));
19465
19466             // Zero extend the condition if needed.
19467             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19468                                Cond);
19469             // Scale the condition by the difference.
19470             if (Diff != 1)
19471               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19472                                  DAG.getConstant(Diff, Cond.getValueType()));
19473
19474             // Add the base if non-zero.
19475             if (FalseC->getAPIntValue() != 0)
19476               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19477                                  SDValue(FalseC, 0));
19478             return Cond;
19479           }
19480         }
19481       }
19482   }
19483
19484   // Canonicalize max and min:
19485   // (x > y) ? x : y -> (x >= y) ? x : y
19486   // (x < y) ? x : y -> (x <= y) ? x : y
19487   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19488   // the need for an extra compare
19489   // against zero. e.g.
19490   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19491   // subl   %esi, %edi
19492   // testl  %edi, %edi
19493   // movl   $0, %eax
19494   // cmovgl %edi, %eax
19495   // =>
19496   // xorl   %eax, %eax
19497   // subl   %esi, $edi
19498   // cmovsl %eax, %edi
19499   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19500       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19501       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19502     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19503     switch (CC) {
19504     default: break;
19505     case ISD::SETLT:
19506     case ISD::SETGT: {
19507       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19508       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19509                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
19510       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19511     }
19512     }
19513   }
19514
19515   // Early exit check
19516   if (!TLI.isTypeLegal(VT))
19517     return SDValue();
19518
19519   // Match VSELECTs into subs with unsigned saturation.
19520   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19521       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19522       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19523        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19524     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19525
19526     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19527     // left side invert the predicate to simplify logic below.
19528     SDValue Other;
19529     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19530       Other = RHS;
19531       CC = ISD::getSetCCInverse(CC, true);
19532     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19533       Other = LHS;
19534     }
19535
19536     if (Other.getNode() && Other->getNumOperands() == 2 &&
19537         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19538       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19539       SDValue CondRHS = Cond->getOperand(1);
19540
19541       // Look for a general sub with unsigned saturation first.
19542       // x >= y ? x-y : 0 --> subus x, y
19543       // x >  y ? x-y : 0 --> subus x, y
19544       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19545           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19546         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19547
19548       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
19549         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
19550           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
19551             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
19552               // If the RHS is a constant we have to reverse the const
19553               // canonicalization.
19554               // x > C-1 ? x+-C : 0 --> subus x, C
19555               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19556                   CondRHSConst->getAPIntValue() ==
19557                       (-OpRHSConst->getAPIntValue() - 1))
19558                 return DAG.getNode(
19559                     X86ISD::SUBUS, DL, VT, OpLHS,
19560                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
19561
19562           // Another special case: If C was a sign bit, the sub has been
19563           // canonicalized into a xor.
19564           // FIXME: Would it be better to use computeKnownBits to determine
19565           //        whether it's safe to decanonicalize the xor?
19566           // x s< 0 ? x^C : 0 --> subus x, C
19567           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19568               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
19569               OpRHSConst->getAPIntValue().isSignBit())
19570             // Note that we have to rebuild the RHS constant here to ensure we
19571             // don't rely on particular values of undef lanes.
19572             return DAG.getNode(
19573                 X86ISD::SUBUS, DL, VT, OpLHS,
19574                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
19575         }
19576     }
19577   }
19578
19579   // Try to match a min/max vector operation.
19580   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19581     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19582     unsigned Opc = ret.first;
19583     bool NeedSplit = ret.second;
19584
19585     if (Opc && NeedSplit) {
19586       unsigned NumElems = VT.getVectorNumElements();
19587       // Extract the LHS vectors
19588       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19589       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19590
19591       // Extract the RHS vectors
19592       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19593       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19594
19595       // Create min/max for each subvector
19596       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19597       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19598
19599       // Merge the result
19600       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19601     } else if (Opc)
19602       return DAG.getNode(Opc, DL, VT, LHS, RHS);
19603   }
19604
19605   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19606   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19607       // Check if SETCC has already been promoted
19608       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19609       // Check that condition value type matches vselect operand type
19610       CondVT == VT) { 
19611
19612     assert(Cond.getValueType().isVector() &&
19613            "vector select expects a vector selector!");
19614
19615     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19616     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19617
19618     if (!TValIsAllOnes && !FValIsAllZeros) {
19619       // Try invert the condition if true value is not all 1s and false value
19620       // is not all 0s.
19621       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19622       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19623
19624       if (TValIsAllZeros || FValIsAllOnes) {
19625         SDValue CC = Cond.getOperand(2);
19626         ISD::CondCode NewCC =
19627           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19628                                Cond.getOperand(0).getValueType().isInteger());
19629         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19630         std::swap(LHS, RHS);
19631         TValIsAllOnes = FValIsAllOnes;
19632         FValIsAllZeros = TValIsAllZeros;
19633       }
19634     }
19635
19636     if (TValIsAllOnes || FValIsAllZeros) {
19637       SDValue Ret;
19638
19639       if (TValIsAllOnes && FValIsAllZeros)
19640         Ret = Cond;
19641       else if (TValIsAllOnes)
19642         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19643                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19644       else if (FValIsAllZeros)
19645         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19646                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19647
19648       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19649     }
19650   }
19651
19652   // Try to fold this VSELECT into a MOVSS/MOVSD
19653   if (N->getOpcode() == ISD::VSELECT &&
19654       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19655     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19656         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19657       bool CanFold = false;
19658       unsigned NumElems = Cond.getNumOperands();
19659       SDValue A = LHS;
19660       SDValue B = RHS;
19661       
19662       if (isZero(Cond.getOperand(0))) {
19663         CanFold = true;
19664
19665         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19666         // fold (vselect <0,-1> -> (movsd A, B)
19667         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19668           CanFold = isAllOnes(Cond.getOperand(i));
19669       } else if (isAllOnes(Cond.getOperand(0))) {
19670         CanFold = true;
19671         std::swap(A, B);
19672
19673         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19674         // fold (vselect <-1,0> -> (movsd B, A)
19675         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19676           CanFold = isZero(Cond.getOperand(i));
19677       }
19678
19679       if (CanFold) {
19680         if (VT == MVT::v4i32 || VT == MVT::v4f32)
19681           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19682         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19683       }
19684
19685       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19686         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19687         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19688         //                             (v2i64 (bitcast B)))))
19689         //
19690         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19691         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19692         //                             (v2f64 (bitcast B)))))
19693         //
19694         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19695         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19696         //                             (v2i64 (bitcast A)))))
19697         //
19698         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19699         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19700         //                             (v2f64 (bitcast A)))))
19701
19702         CanFold = (isZero(Cond.getOperand(0)) &&
19703                    isZero(Cond.getOperand(1)) &&
19704                    isAllOnes(Cond.getOperand(2)) &&
19705                    isAllOnes(Cond.getOperand(3)));
19706
19707         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19708             isAllOnes(Cond.getOperand(1)) &&
19709             isZero(Cond.getOperand(2)) &&
19710             isZero(Cond.getOperand(3))) {
19711           CanFold = true;
19712           std::swap(LHS, RHS);
19713         }
19714
19715         if (CanFold) {
19716           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19717           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19718           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19719           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19720                                                 NewB, DAG);
19721           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19722         }
19723       }
19724     }
19725   }
19726
19727   // If we know that this node is legal then we know that it is going to be
19728   // matched by one of the SSE/AVX BLEND instructions. These instructions only
19729   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19730   // to simplify previous instructions.
19731   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19732       !DCI.isBeforeLegalize() &&
19733       // We explicitly check against v8i16 and v16i16 because, although
19734       // they're marked as Custom, they might only be legal when Cond is a
19735       // build_vector of constants. This will be taken care in a later
19736       // condition.
19737       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19738        VT != MVT::v8i16)) {
19739     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19740
19741     // Don't optimize vector selects that map to mask-registers.
19742     if (BitWidth == 1)
19743       return SDValue();
19744
19745     // Check all uses of that condition operand to check whether it will be
19746     // consumed by non-BLEND instructions, which may depend on all bits are set
19747     // properly.
19748     for (SDNode::use_iterator I = Cond->use_begin(),
19749                               E = Cond->use_end(); I != E; ++I)
19750       if (I->getOpcode() != ISD::VSELECT)
19751         // TODO: Add other opcodes eventually lowered into BLEND.
19752         return SDValue();
19753
19754     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19755     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19756
19757     APInt KnownZero, KnownOne;
19758     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19759                                           DCI.isBeforeLegalizeOps());
19760     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
19761         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
19762       DCI.CommitTargetLoweringOpt(TLO);
19763   }
19764
19765   // We should generate an X86ISD::BLENDI from a vselect if its argument
19766   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
19767   // constants. This specific pattern gets generated when we split a
19768   // selector for a 512 bit vector in a machine without AVX512 (but with
19769   // 256-bit vectors), during legalization:
19770   //
19771   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
19772   //
19773   // Iff we find this pattern and the build_vectors are built from
19774   // constants, we translate the vselect into a shuffle_vector that we
19775   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
19776   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
19777     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
19778     if (Shuffle.getNode())
19779       return Shuffle;
19780   }
19781
19782   return SDValue();
19783 }
19784
19785 // Check whether a boolean test is testing a boolean value generated by
19786 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
19787 // code.
19788 //
19789 // Simplify the following patterns:
19790 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
19791 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
19792 // to (Op EFLAGS Cond)
19793 //
19794 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
19795 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
19796 // to (Op EFLAGS !Cond)
19797 //
19798 // where Op could be BRCOND or CMOV.
19799 //
19800 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
19801   // Quit if not CMP and SUB with its value result used.
19802   if (Cmp.getOpcode() != X86ISD::CMP &&
19803       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
19804       return SDValue();
19805
19806   // Quit if not used as a boolean value.
19807   if (CC != X86::COND_E && CC != X86::COND_NE)
19808     return SDValue();
19809
19810   // Check CMP operands. One of them should be 0 or 1 and the other should be
19811   // an SetCC or extended from it.
19812   SDValue Op1 = Cmp.getOperand(0);
19813   SDValue Op2 = Cmp.getOperand(1);
19814
19815   SDValue SetCC;
19816   const ConstantSDNode* C = nullptr;
19817   bool needOppositeCond = (CC == X86::COND_E);
19818   bool checkAgainstTrue = false; // Is it a comparison against 1?
19819
19820   if ((C = dyn_cast<ConstantSDNode>(Op1)))
19821     SetCC = Op2;
19822   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19823     SetCC = Op1;
19824   else // Quit if all operands are not constants.
19825     return SDValue();
19826
19827   if (C->getZExtValue() == 1) {
19828     needOppositeCond = !needOppositeCond;
19829     checkAgainstTrue = true;
19830   } else if (C->getZExtValue() != 0)
19831     // Quit if the constant is neither 0 or 1.
19832     return SDValue();
19833
19834   bool truncatedToBoolWithAnd = false;
19835   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19836   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19837          SetCC.getOpcode() == ISD::TRUNCATE ||
19838          SetCC.getOpcode() == ISD::AND) {
19839     if (SetCC.getOpcode() == ISD::AND) {
19840       int OpIdx = -1;
19841       ConstantSDNode *CS;
19842       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19843           CS->getZExtValue() == 1)
19844         OpIdx = 1;
19845       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19846           CS->getZExtValue() == 1)
19847         OpIdx = 0;
19848       if (OpIdx == -1)
19849         break;
19850       SetCC = SetCC.getOperand(OpIdx);
19851       truncatedToBoolWithAnd = true;
19852     } else
19853       SetCC = SetCC.getOperand(0);
19854   }
19855
19856   switch (SetCC.getOpcode()) {
19857   case X86ISD::SETCC_CARRY:
19858     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19859     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19860     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19861     // truncated to i1 using 'and'.
19862     if (checkAgainstTrue && !truncatedToBoolWithAnd)
19863       break;
19864     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19865            "Invalid use of SETCC_CARRY!");
19866     // FALL THROUGH
19867   case X86ISD::SETCC:
19868     // Set the condition code or opposite one if necessary.
19869     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19870     if (needOppositeCond)
19871       CC = X86::GetOppositeBranchCondition(CC);
19872     return SetCC.getOperand(1);
19873   case X86ISD::CMOV: {
19874     // Check whether false/true value has canonical one, i.e. 0 or 1.
19875     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19876     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19877     // Quit if true value is not a constant.
19878     if (!TVal)
19879       return SDValue();
19880     // Quit if false value is not a constant.
19881     if (!FVal) {
19882       SDValue Op = SetCC.getOperand(0);
19883       // Skip 'zext' or 'trunc' node.
19884       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19885           Op.getOpcode() == ISD::TRUNCATE)
19886         Op = Op.getOperand(0);
19887       // A special case for rdrand/rdseed, where 0 is set if false cond is
19888       // found.
19889       if ((Op.getOpcode() != X86ISD::RDRAND &&
19890            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19891         return SDValue();
19892     }
19893     // Quit if false value is not the constant 0 or 1.
19894     bool FValIsFalse = true;
19895     if (FVal && FVal->getZExtValue() != 0) {
19896       if (FVal->getZExtValue() != 1)
19897         return SDValue();
19898       // If FVal is 1, opposite cond is needed.
19899       needOppositeCond = !needOppositeCond;
19900       FValIsFalse = false;
19901     }
19902     // Quit if TVal is not the constant opposite of FVal.
19903     if (FValIsFalse && TVal->getZExtValue() != 1)
19904       return SDValue();
19905     if (!FValIsFalse && TVal->getZExtValue() != 0)
19906       return SDValue();
19907     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19908     if (needOppositeCond)
19909       CC = X86::GetOppositeBranchCondition(CC);
19910     return SetCC.getOperand(3);
19911   }
19912   }
19913
19914   return SDValue();
19915 }
19916
19917 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19918 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19919                                   TargetLowering::DAGCombinerInfo &DCI,
19920                                   const X86Subtarget *Subtarget) {
19921   SDLoc DL(N);
19922
19923   // If the flag operand isn't dead, don't touch this CMOV.
19924   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19925     return SDValue();
19926
19927   SDValue FalseOp = N->getOperand(0);
19928   SDValue TrueOp = N->getOperand(1);
19929   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19930   SDValue Cond = N->getOperand(3);
19931
19932   if (CC == X86::COND_E || CC == X86::COND_NE) {
19933     switch (Cond.getOpcode()) {
19934     default: break;
19935     case X86ISD::BSR:
19936     case X86ISD::BSF:
19937       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19938       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19939         return (CC == X86::COND_E) ? FalseOp : TrueOp;
19940     }
19941   }
19942
19943   SDValue Flags;
19944
19945   Flags = checkBoolTestSetCCCombine(Cond, CC);
19946   if (Flags.getNode() &&
19947       // Extra check as FCMOV only supports a subset of X86 cond.
19948       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19949     SDValue Ops[] = { FalseOp, TrueOp,
19950                       DAG.getConstant(CC, MVT::i8), Flags };
19951     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19952   }
19953
19954   // If this is a select between two integer constants, try to do some
19955   // optimizations.  Note that the operands are ordered the opposite of SELECT
19956   // operands.
19957   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19958     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19959       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19960       // larger than FalseC (the false value).
19961       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19962         CC = X86::GetOppositeBranchCondition(CC);
19963         std::swap(TrueC, FalseC);
19964         std::swap(TrueOp, FalseOp);
19965       }
19966
19967       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
19968       // This is efficient for any integer data type (including i8/i16) and
19969       // shift amount.
19970       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19971         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19972                            DAG.getConstant(CC, MVT::i8), Cond);
19973
19974         // Zero extend the condition if needed.
19975         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19976
19977         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19978         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19979                            DAG.getConstant(ShAmt, MVT::i8));
19980         if (N->getNumValues() == 2)  // Dead flag value?
19981           return DCI.CombineTo(N, Cond, SDValue());
19982         return Cond;
19983       }
19984
19985       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
19986       // for any integer data type, including i8/i16.
19987       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19988         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19989                            DAG.getConstant(CC, MVT::i8), Cond);
19990
19991         // Zero extend the condition if needed.
19992         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19993                            FalseC->getValueType(0), Cond);
19994         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19995                            SDValue(FalseC, 0));
19996
19997         if (N->getNumValues() == 2)  // Dead flag value?
19998           return DCI.CombineTo(N, Cond, SDValue());
19999         return Cond;
20000       }
20001
20002       // Optimize cases that will turn into an LEA instruction.  This requires
20003       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20004       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20005         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20006         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20007
20008         bool isFastMultiplier = false;
20009         if (Diff < 10) {
20010           switch ((unsigned char)Diff) {
20011           default: break;
20012           case 1:  // result = add base, cond
20013           case 2:  // result = lea base(    , cond*2)
20014           case 3:  // result = lea base(cond, cond*2)
20015           case 4:  // result = lea base(    , cond*4)
20016           case 5:  // result = lea base(cond, cond*4)
20017           case 8:  // result = lea base(    , cond*8)
20018           case 9:  // result = lea base(cond, cond*8)
20019             isFastMultiplier = true;
20020             break;
20021           }
20022         }
20023
20024         if (isFastMultiplier) {
20025           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20026           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20027                              DAG.getConstant(CC, MVT::i8), Cond);
20028           // Zero extend the condition if needed.
20029           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20030                              Cond);
20031           // Scale the condition by the difference.
20032           if (Diff != 1)
20033             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20034                                DAG.getConstant(Diff, Cond.getValueType()));
20035
20036           // Add the base if non-zero.
20037           if (FalseC->getAPIntValue() != 0)
20038             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20039                                SDValue(FalseC, 0));
20040           if (N->getNumValues() == 2)  // Dead flag value?
20041             return DCI.CombineTo(N, Cond, SDValue());
20042           return Cond;
20043         }
20044       }
20045     }
20046   }
20047
20048   // Handle these cases:
20049   //   (select (x != c), e, c) -> select (x != c), e, x),
20050   //   (select (x == c), c, e) -> select (x == c), x, e)
20051   // where the c is an integer constant, and the "select" is the combination
20052   // of CMOV and CMP.
20053   //
20054   // The rationale for this change is that the conditional-move from a constant
20055   // needs two instructions, however, conditional-move from a register needs
20056   // only one instruction.
20057   //
20058   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20059   //  some instruction-combining opportunities. This opt needs to be
20060   //  postponed as late as possible.
20061   //
20062   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20063     // the DCI.xxxx conditions are provided to postpone the optimization as
20064     // late as possible.
20065
20066     ConstantSDNode *CmpAgainst = nullptr;
20067     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20068         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20069         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20070
20071       if (CC == X86::COND_NE &&
20072           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20073         CC = X86::GetOppositeBranchCondition(CC);
20074         std::swap(TrueOp, FalseOp);
20075       }
20076
20077       if (CC == X86::COND_E &&
20078           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20079         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20080                           DAG.getConstant(CC, MVT::i8), Cond };
20081         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20082       }
20083     }
20084   }
20085
20086   return SDValue();
20087 }
20088
20089 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20090                                                 const X86Subtarget *Subtarget) {
20091   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20092   switch (IntNo) {
20093   default: return SDValue();
20094   // SSE/AVX/AVX2 blend intrinsics.
20095   case Intrinsic::x86_avx2_pblendvb:
20096   case Intrinsic::x86_avx2_pblendw:
20097   case Intrinsic::x86_avx2_pblendd_128:
20098   case Intrinsic::x86_avx2_pblendd_256:
20099     // Don't try to simplify this intrinsic if we don't have AVX2.
20100     if (!Subtarget->hasAVX2())
20101       return SDValue();
20102     // FALL-THROUGH
20103   case Intrinsic::x86_avx_blend_pd_256:
20104   case Intrinsic::x86_avx_blend_ps_256:
20105   case Intrinsic::x86_avx_blendv_pd_256:
20106   case Intrinsic::x86_avx_blendv_ps_256:
20107     // Don't try to simplify this intrinsic if we don't have AVX.
20108     if (!Subtarget->hasAVX())
20109       return SDValue();
20110     // FALL-THROUGH
20111   case Intrinsic::x86_sse41_pblendw:
20112   case Intrinsic::x86_sse41_blendpd:
20113   case Intrinsic::x86_sse41_blendps:
20114   case Intrinsic::x86_sse41_blendvps:
20115   case Intrinsic::x86_sse41_blendvpd:
20116   case Intrinsic::x86_sse41_pblendvb: {
20117     SDValue Op0 = N->getOperand(1);
20118     SDValue Op1 = N->getOperand(2);
20119     SDValue Mask = N->getOperand(3);
20120
20121     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20122     if (!Subtarget->hasSSE41())
20123       return SDValue();
20124
20125     // fold (blend A, A, Mask) -> A
20126     if (Op0 == Op1)
20127       return Op0;
20128     // fold (blend A, B, allZeros) -> A
20129     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20130       return Op0;
20131     // fold (blend A, B, allOnes) -> B
20132     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20133       return Op1;
20134     
20135     // Simplify the case where the mask is a constant i32 value.
20136     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20137       if (C->isNullValue())
20138         return Op0;
20139       if (C->isAllOnesValue())
20140         return Op1;
20141     }
20142
20143     return SDValue();
20144   }
20145
20146   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20147   case Intrinsic::x86_sse2_psrai_w:
20148   case Intrinsic::x86_sse2_psrai_d:
20149   case Intrinsic::x86_avx2_psrai_w:
20150   case Intrinsic::x86_avx2_psrai_d:
20151   case Intrinsic::x86_sse2_psra_w:
20152   case Intrinsic::x86_sse2_psra_d:
20153   case Intrinsic::x86_avx2_psra_w:
20154   case Intrinsic::x86_avx2_psra_d: {
20155     SDValue Op0 = N->getOperand(1);
20156     SDValue Op1 = N->getOperand(2);
20157     EVT VT = Op0.getValueType();
20158     assert(VT.isVector() && "Expected a vector type!");
20159
20160     if (isa<BuildVectorSDNode>(Op1))
20161       Op1 = Op1.getOperand(0);
20162
20163     if (!isa<ConstantSDNode>(Op1))
20164       return SDValue();
20165
20166     EVT SVT = VT.getVectorElementType();
20167     unsigned SVTBits = SVT.getSizeInBits();
20168
20169     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20170     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20171     uint64_t ShAmt = C.getZExtValue();
20172
20173     // Don't try to convert this shift into a ISD::SRA if the shift
20174     // count is bigger than or equal to the element size.
20175     if (ShAmt >= SVTBits)
20176       return SDValue();
20177
20178     // Trivial case: if the shift count is zero, then fold this
20179     // into the first operand.
20180     if (ShAmt == 0)
20181       return Op0;
20182
20183     // Replace this packed shift intrinsic with a target independent
20184     // shift dag node.
20185     SDValue Splat = DAG.getConstant(C, VT);
20186     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20187   }
20188   }
20189 }
20190
20191 /// PerformMulCombine - Optimize a single multiply with constant into two
20192 /// in order to implement it with two cheaper instructions, e.g.
20193 /// LEA + SHL, LEA + LEA.
20194 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20195                                  TargetLowering::DAGCombinerInfo &DCI) {
20196   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20197     return SDValue();
20198
20199   EVT VT = N->getValueType(0);
20200   if (VT != MVT::i64)
20201     return SDValue();
20202
20203   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20204   if (!C)
20205     return SDValue();
20206   uint64_t MulAmt = C->getZExtValue();
20207   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20208     return SDValue();
20209
20210   uint64_t MulAmt1 = 0;
20211   uint64_t MulAmt2 = 0;
20212   if ((MulAmt % 9) == 0) {
20213     MulAmt1 = 9;
20214     MulAmt2 = MulAmt / 9;
20215   } else if ((MulAmt % 5) == 0) {
20216     MulAmt1 = 5;
20217     MulAmt2 = MulAmt / 5;
20218   } else if ((MulAmt % 3) == 0) {
20219     MulAmt1 = 3;
20220     MulAmt2 = MulAmt / 3;
20221   }
20222   if (MulAmt2 &&
20223       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20224     SDLoc DL(N);
20225
20226     if (isPowerOf2_64(MulAmt2) &&
20227         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20228       // If second multiplifer is pow2, issue it first. We want the multiply by
20229       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20230       // is an add.
20231       std::swap(MulAmt1, MulAmt2);
20232
20233     SDValue NewMul;
20234     if (isPowerOf2_64(MulAmt1))
20235       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20236                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20237     else
20238       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20239                            DAG.getConstant(MulAmt1, VT));
20240
20241     if (isPowerOf2_64(MulAmt2))
20242       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20243                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20244     else
20245       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20246                            DAG.getConstant(MulAmt2, VT));
20247
20248     // Do not add new nodes to DAG combiner worklist.
20249     DCI.CombineTo(N, NewMul, false);
20250   }
20251   return SDValue();
20252 }
20253
20254 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20255   SDValue N0 = N->getOperand(0);
20256   SDValue N1 = N->getOperand(1);
20257   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20258   EVT VT = N0.getValueType();
20259
20260   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20261   // since the result of setcc_c is all zero's or all ones.
20262   if (VT.isInteger() && !VT.isVector() &&
20263       N1C && N0.getOpcode() == ISD::AND &&
20264       N0.getOperand(1).getOpcode() == ISD::Constant) {
20265     SDValue N00 = N0.getOperand(0);
20266     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20267         ((N00.getOpcode() == ISD::ANY_EXTEND ||
20268           N00.getOpcode() == ISD::ZERO_EXTEND) &&
20269          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20270       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20271       APInt ShAmt = N1C->getAPIntValue();
20272       Mask = Mask.shl(ShAmt);
20273       if (Mask != 0)
20274         return DAG.getNode(ISD::AND, SDLoc(N), VT,
20275                            N00, DAG.getConstant(Mask, VT));
20276     }
20277   }
20278
20279   // Hardware support for vector shifts is sparse which makes us scalarize the
20280   // vector operations in many cases. Also, on sandybridge ADD is faster than
20281   // shl.
20282   // (shl V, 1) -> add V,V
20283   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20284     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
20285       assert(N0.getValueType().isVector() && "Invalid vector shift type");
20286       // We shift all of the values by one. In many cases we do not have
20287       // hardware support for this operation. This is better expressed as an ADD
20288       // of two values.
20289       if (N1SplatC->getZExtValue() == 1)
20290         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20291     }
20292
20293   return SDValue();
20294 }
20295
20296 /// \brief Returns a vector of 0s if the node in input is a vector logical
20297 /// shift by a constant amount which is known to be bigger than or equal
20298 /// to the vector element size in bits.
20299 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20300                                       const X86Subtarget *Subtarget) {
20301   EVT VT = N->getValueType(0);
20302
20303   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20304       (!Subtarget->hasInt256() ||
20305        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20306     return SDValue();
20307
20308   SDValue Amt = N->getOperand(1);
20309   SDLoc DL(N);
20310   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20311     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
20312       APInt ShiftAmt = AmtSplat->getAPIntValue();
20313       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20314
20315       // SSE2/AVX2 logical shifts always return a vector of 0s
20316       // if the shift amount is bigger than or equal to
20317       // the element size. The constant shift amount will be
20318       // encoded as a 8-bit immediate.
20319       if (ShiftAmt.trunc(8).uge(MaxAmount))
20320         return getZeroVector(VT, Subtarget, DAG, DL);
20321     }
20322
20323   return SDValue();
20324 }
20325
20326 /// PerformShiftCombine - Combine shifts.
20327 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20328                                    TargetLowering::DAGCombinerInfo &DCI,
20329                                    const X86Subtarget *Subtarget) {
20330   if (N->getOpcode() == ISD::SHL) {
20331     SDValue V = PerformSHLCombine(N, DAG);
20332     if (V.getNode()) return V;
20333   }
20334
20335   if (N->getOpcode() != ISD::SRA) {
20336     // Try to fold this logical shift into a zero vector.
20337     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20338     if (V.getNode()) return V;
20339   }
20340
20341   return SDValue();
20342 }
20343
20344 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
20345 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20346 // and friends.  Likewise for OR -> CMPNEQSS.
20347 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20348                             TargetLowering::DAGCombinerInfo &DCI,
20349                             const X86Subtarget *Subtarget) {
20350   unsigned opcode;
20351
20352   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20353   // we're requiring SSE2 for both.
20354   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20355     SDValue N0 = N->getOperand(0);
20356     SDValue N1 = N->getOperand(1);
20357     SDValue CMP0 = N0->getOperand(1);
20358     SDValue CMP1 = N1->getOperand(1);
20359     SDLoc DL(N);
20360
20361     // The SETCCs should both refer to the same CMP.
20362     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20363       return SDValue();
20364
20365     SDValue CMP00 = CMP0->getOperand(0);
20366     SDValue CMP01 = CMP0->getOperand(1);
20367     EVT     VT    = CMP00.getValueType();
20368
20369     if (VT == MVT::f32 || VT == MVT::f64) {
20370       bool ExpectingFlags = false;
20371       // Check for any users that want flags:
20372       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20373            !ExpectingFlags && UI != UE; ++UI)
20374         switch (UI->getOpcode()) {
20375         default:
20376         case ISD::BR_CC:
20377         case ISD::BRCOND:
20378         case ISD::SELECT:
20379           ExpectingFlags = true;
20380           break;
20381         case ISD::CopyToReg:
20382         case ISD::SIGN_EXTEND:
20383         case ISD::ZERO_EXTEND:
20384         case ISD::ANY_EXTEND:
20385           break;
20386         }
20387
20388       if (!ExpectingFlags) {
20389         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20390         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20391
20392         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20393           X86::CondCode tmp = cc0;
20394           cc0 = cc1;
20395           cc1 = tmp;
20396         }
20397
20398         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
20399             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20400           // FIXME: need symbolic constants for these magic numbers.
20401           // See X86ATTInstPrinter.cpp:printSSECC().
20402           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20403           if (Subtarget->hasAVX512()) {
20404             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20405                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
20406             if (N->getValueType(0) != MVT::i1)
20407               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20408                                  FSetCC);
20409             return FSetCC;
20410           }
20411           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20412                                               CMP00.getValueType(), CMP00, CMP01,
20413                                               DAG.getConstant(x86cc, MVT::i8));
20414
20415           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20416           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20417
20418           if (is64BitFP && !Subtarget->is64Bit()) {
20419             // On a 32-bit target, we cannot bitcast the 64-bit float to a
20420             // 64-bit integer, since that's not a legal type. Since
20421             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20422             // bits, but can do this little dance to extract the lowest 32 bits
20423             // and work with those going forward.
20424             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20425                                            OnesOrZeroesF);
20426             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20427                                            Vector64);
20428             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20429                                         Vector32, DAG.getIntPtrConstant(0));
20430             IntVT = MVT::i32;
20431           }
20432
20433           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20434           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20435                                       DAG.getConstant(1, IntVT));
20436           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20437           return OneBitOfTruth;
20438         }
20439       }
20440     }
20441   }
20442   return SDValue();
20443 }
20444
20445 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20446 /// so it can be folded inside ANDNP.
20447 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20448   EVT VT = N->getValueType(0);
20449
20450   // Match direct AllOnes for 128 and 256-bit vectors
20451   if (ISD::isBuildVectorAllOnes(N))
20452     return true;
20453
20454   // Look through a bit convert.
20455   if (N->getOpcode() == ISD::BITCAST)
20456     N = N->getOperand(0).getNode();
20457
20458   // Sometimes the operand may come from a insert_subvector building a 256-bit
20459   // allones vector
20460   if (VT.is256BitVector() &&
20461       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20462     SDValue V1 = N->getOperand(0);
20463     SDValue V2 = N->getOperand(1);
20464
20465     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20466         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20467         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20468         ISD::isBuildVectorAllOnes(V2.getNode()))
20469       return true;
20470   }
20471
20472   return false;
20473 }
20474
20475 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20476 // register. In most cases we actually compare or select YMM-sized registers
20477 // and mixing the two types creates horrible code. This method optimizes
20478 // some of the transition sequences.
20479 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20480                                  TargetLowering::DAGCombinerInfo &DCI,
20481                                  const X86Subtarget *Subtarget) {
20482   EVT VT = N->getValueType(0);
20483   if (!VT.is256BitVector())
20484     return SDValue();
20485
20486   assert((N->getOpcode() == ISD::ANY_EXTEND ||
20487           N->getOpcode() == ISD::ZERO_EXTEND ||
20488           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20489
20490   SDValue Narrow = N->getOperand(0);
20491   EVT NarrowVT = Narrow->getValueType(0);
20492   if (!NarrowVT.is128BitVector())
20493     return SDValue();
20494
20495   if (Narrow->getOpcode() != ISD::XOR &&
20496       Narrow->getOpcode() != ISD::AND &&
20497       Narrow->getOpcode() != ISD::OR)
20498     return SDValue();
20499
20500   SDValue N0  = Narrow->getOperand(0);
20501   SDValue N1  = Narrow->getOperand(1);
20502   SDLoc DL(Narrow);
20503
20504   // The Left side has to be a trunc.
20505   if (N0.getOpcode() != ISD::TRUNCATE)
20506     return SDValue();
20507
20508   // The type of the truncated inputs.
20509   EVT WideVT = N0->getOperand(0)->getValueType(0);
20510   if (WideVT != VT)
20511     return SDValue();
20512
20513   // The right side has to be a 'trunc' or a constant vector.
20514   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20515   ConstantSDNode *RHSConstSplat = nullptr;
20516   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
20517     RHSConstSplat = RHSBV->getConstantSplatNode();
20518   if (!RHSTrunc && !RHSConstSplat)
20519     return SDValue();
20520
20521   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20522
20523   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20524     return SDValue();
20525
20526   // Set N0 and N1 to hold the inputs to the new wide operation.
20527   N0 = N0->getOperand(0);
20528   if (RHSConstSplat) {
20529     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20530                      SDValue(RHSConstSplat, 0));
20531     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20532     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20533   } else if (RHSTrunc) {
20534     N1 = N1->getOperand(0);
20535   }
20536
20537   // Generate the wide operation.
20538   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20539   unsigned Opcode = N->getOpcode();
20540   switch (Opcode) {
20541   case ISD::ANY_EXTEND:
20542     return Op;
20543   case ISD::ZERO_EXTEND: {
20544     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20545     APInt Mask = APInt::getAllOnesValue(InBits);
20546     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20547     return DAG.getNode(ISD::AND, DL, VT,
20548                        Op, DAG.getConstant(Mask, VT));
20549   }
20550   case ISD::SIGN_EXTEND:
20551     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20552                        Op, DAG.getValueType(NarrowVT));
20553   default:
20554     llvm_unreachable("Unexpected opcode");
20555   }
20556 }
20557
20558 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20559                                  TargetLowering::DAGCombinerInfo &DCI,
20560                                  const X86Subtarget *Subtarget) {
20561   EVT VT = N->getValueType(0);
20562   if (DCI.isBeforeLegalizeOps())
20563     return SDValue();
20564
20565   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20566   if (R.getNode())
20567     return R;
20568
20569   // Create BEXTR instructions
20570   // BEXTR is ((X >> imm) & (2**size-1))
20571   if (VT == MVT::i32 || VT == MVT::i64) {
20572     SDValue N0 = N->getOperand(0);
20573     SDValue N1 = N->getOperand(1);
20574     SDLoc DL(N);
20575
20576     // Check for BEXTR.
20577     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20578         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20579       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20580       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20581       if (MaskNode && ShiftNode) {
20582         uint64_t Mask = MaskNode->getZExtValue();
20583         uint64_t Shift = ShiftNode->getZExtValue();
20584         if (isMask_64(Mask)) {
20585           uint64_t MaskSize = CountPopulation_64(Mask);
20586           if (Shift + MaskSize <= VT.getSizeInBits())
20587             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20588                                DAG.getConstant(Shift | (MaskSize << 8), VT));
20589         }
20590       }
20591     } // BEXTR
20592
20593     return SDValue();
20594   }
20595
20596   // Want to form ANDNP nodes:
20597   // 1) In the hopes of then easily combining them with OR and AND nodes
20598   //    to form PBLEND/PSIGN.
20599   // 2) To match ANDN packed intrinsics
20600   if (VT != MVT::v2i64 && VT != MVT::v4i64)
20601     return SDValue();
20602
20603   SDValue N0 = N->getOperand(0);
20604   SDValue N1 = N->getOperand(1);
20605   SDLoc DL(N);
20606
20607   // Check LHS for vnot
20608   if (N0.getOpcode() == ISD::XOR &&
20609       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20610       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20611     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20612
20613   // Check RHS for vnot
20614   if (N1.getOpcode() == ISD::XOR &&
20615       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20616       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20617     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20618
20619   return SDValue();
20620 }
20621
20622 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20623                                 TargetLowering::DAGCombinerInfo &DCI,
20624                                 const X86Subtarget *Subtarget) {
20625   if (DCI.isBeforeLegalizeOps())
20626     return SDValue();
20627
20628   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20629   if (R.getNode())
20630     return R;
20631
20632   SDValue N0 = N->getOperand(0);
20633   SDValue N1 = N->getOperand(1);
20634   EVT VT = N->getValueType(0);
20635
20636   // look for psign/blend
20637   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20638     if (!Subtarget->hasSSSE3() ||
20639         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20640       return SDValue();
20641
20642     // Canonicalize pandn to RHS
20643     if (N0.getOpcode() == X86ISD::ANDNP)
20644       std::swap(N0, N1);
20645     // or (and (m, y), (pandn m, x))
20646     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20647       SDValue Mask = N1.getOperand(0);
20648       SDValue X    = N1.getOperand(1);
20649       SDValue Y;
20650       if (N0.getOperand(0) == Mask)
20651         Y = N0.getOperand(1);
20652       if (N0.getOperand(1) == Mask)
20653         Y = N0.getOperand(0);
20654
20655       // Check to see if the mask appeared in both the AND and ANDNP and
20656       if (!Y.getNode())
20657         return SDValue();
20658
20659       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20660       // Look through mask bitcast.
20661       if (Mask.getOpcode() == ISD::BITCAST)
20662         Mask = Mask.getOperand(0);
20663       if (X.getOpcode() == ISD::BITCAST)
20664         X = X.getOperand(0);
20665       if (Y.getOpcode() == ISD::BITCAST)
20666         Y = Y.getOperand(0);
20667
20668       EVT MaskVT = Mask.getValueType();
20669
20670       // Validate that the Mask operand is a vector sra node.
20671       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20672       // there is no psrai.b
20673       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20674       unsigned SraAmt = ~0;
20675       if (Mask.getOpcode() == ISD::SRA) {
20676         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
20677           if (auto *AmtConst = AmtBV->getConstantSplatNode())
20678             SraAmt = AmtConst->getZExtValue();
20679       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20680         SDValue SraC = Mask.getOperand(1);
20681         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
20682       }
20683       if ((SraAmt + 1) != EltBits)
20684         return SDValue();
20685
20686       SDLoc DL(N);
20687
20688       // Now we know we at least have a plendvb with the mask val.  See if
20689       // we can form a psignb/w/d.
20690       // psign = x.type == y.type == mask.type && y = sub(0, x);
20691       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20692           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20693           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20694         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20695                "Unsupported VT for PSIGN");
20696         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20697         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20698       }
20699       // PBLENDVB only available on SSE 4.1
20700       if (!Subtarget->hasSSE41())
20701         return SDValue();
20702
20703       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20704
20705       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20706       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20707       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20708       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20709       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20710     }
20711   }
20712
20713   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20714     return SDValue();
20715
20716   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20717   MachineFunction &MF = DAG.getMachineFunction();
20718   bool OptForSize = MF.getFunction()->getAttributes().
20719     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20720
20721   // SHLD/SHRD instructions have lower register pressure, but on some
20722   // platforms they have higher latency than the equivalent
20723   // series of shifts/or that would otherwise be generated.
20724   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20725   // have higher latencies and we are not optimizing for size.
20726   if (!OptForSize && Subtarget->isSHLDSlow())
20727     return SDValue();
20728
20729   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20730     std::swap(N0, N1);
20731   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20732     return SDValue();
20733   if (!N0.hasOneUse() || !N1.hasOneUse())
20734     return SDValue();
20735
20736   SDValue ShAmt0 = N0.getOperand(1);
20737   if (ShAmt0.getValueType() != MVT::i8)
20738     return SDValue();
20739   SDValue ShAmt1 = N1.getOperand(1);
20740   if (ShAmt1.getValueType() != MVT::i8)
20741     return SDValue();
20742   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20743     ShAmt0 = ShAmt0.getOperand(0);
20744   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20745     ShAmt1 = ShAmt1.getOperand(0);
20746
20747   SDLoc DL(N);
20748   unsigned Opc = X86ISD::SHLD;
20749   SDValue Op0 = N0.getOperand(0);
20750   SDValue Op1 = N1.getOperand(0);
20751   if (ShAmt0.getOpcode() == ISD::SUB) {
20752     Opc = X86ISD::SHRD;
20753     std::swap(Op0, Op1);
20754     std::swap(ShAmt0, ShAmt1);
20755   }
20756
20757   unsigned Bits = VT.getSizeInBits();
20758   if (ShAmt1.getOpcode() == ISD::SUB) {
20759     SDValue Sum = ShAmt1.getOperand(0);
20760     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
20761       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
20762       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
20763         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
20764       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
20765         return DAG.getNode(Opc, DL, VT,
20766                            Op0, Op1,
20767                            DAG.getNode(ISD::TRUNCATE, DL,
20768                                        MVT::i8, ShAmt0));
20769     }
20770   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
20771     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
20772     if (ShAmt0C &&
20773         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
20774       return DAG.getNode(Opc, DL, VT,
20775                          N0.getOperand(0), N1.getOperand(0),
20776                          DAG.getNode(ISD::TRUNCATE, DL,
20777                                        MVT::i8, ShAmt0));
20778   }
20779
20780   return SDValue();
20781 }
20782
20783 // Generate NEG and CMOV for integer abs.
20784 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
20785   EVT VT = N->getValueType(0);
20786
20787   // Since X86 does not have CMOV for 8-bit integer, we don't convert
20788   // 8-bit integer abs to NEG and CMOV.
20789   if (VT.isInteger() && VT.getSizeInBits() == 8)
20790     return SDValue();
20791
20792   SDValue N0 = N->getOperand(0);
20793   SDValue N1 = N->getOperand(1);
20794   SDLoc DL(N);
20795
20796   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
20797   // and change it to SUB and CMOV.
20798   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
20799       N0.getOpcode() == ISD::ADD &&
20800       N0.getOperand(1) == N1 &&
20801       N1.getOpcode() == ISD::SRA &&
20802       N1.getOperand(0) == N0.getOperand(0))
20803     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
20804       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
20805         // Generate SUB & CMOV.
20806         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
20807                                   DAG.getConstant(0, VT), N0.getOperand(0));
20808
20809         SDValue Ops[] = { N0.getOperand(0), Neg,
20810                           DAG.getConstant(X86::COND_GE, MVT::i8),
20811                           SDValue(Neg.getNode(), 1) };
20812         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
20813       }
20814   return SDValue();
20815 }
20816
20817 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20818 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20819                                  TargetLowering::DAGCombinerInfo &DCI,
20820                                  const X86Subtarget *Subtarget) {
20821   if (DCI.isBeforeLegalizeOps())
20822     return SDValue();
20823
20824   if (Subtarget->hasCMov()) {
20825     SDValue RV = performIntegerAbsCombine(N, DAG);
20826     if (RV.getNode())
20827       return RV;
20828   }
20829
20830   return SDValue();
20831 }
20832
20833 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20834 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20835                                   TargetLowering::DAGCombinerInfo &DCI,
20836                                   const X86Subtarget *Subtarget) {
20837   LoadSDNode *Ld = cast<LoadSDNode>(N);
20838   EVT RegVT = Ld->getValueType(0);
20839   EVT MemVT = Ld->getMemoryVT();
20840   SDLoc dl(Ld);
20841   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20842   unsigned RegSz = RegVT.getSizeInBits();
20843
20844   // On Sandybridge unaligned 256bit loads are inefficient.
20845   ISD::LoadExtType Ext = Ld->getExtensionType();
20846   unsigned Alignment = Ld->getAlignment();
20847   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20848   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20849       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20850     unsigned NumElems = RegVT.getVectorNumElements();
20851     if (NumElems < 2)
20852       return SDValue();
20853
20854     SDValue Ptr = Ld->getBasePtr();
20855     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20856
20857     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20858                                   NumElems/2);
20859     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20860                                 Ld->getPointerInfo(), Ld->isVolatile(),
20861                                 Ld->isNonTemporal(), Ld->isInvariant(),
20862                                 Alignment);
20863     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20864     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20865                                 Ld->getPointerInfo(), Ld->isVolatile(),
20866                                 Ld->isNonTemporal(), Ld->isInvariant(),
20867                                 std::min(16U, Alignment));
20868     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20869                              Load1.getValue(1),
20870                              Load2.getValue(1));
20871
20872     SDValue NewVec = DAG.getUNDEF(RegVT);
20873     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20874     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20875     return DCI.CombineTo(N, NewVec, TF, true);
20876   }
20877
20878   // If this is a vector EXT Load then attempt to optimize it using a
20879   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20880   // expansion is still better than scalar code.
20881   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20882   // emit a shuffle and a arithmetic shift.
20883   // TODO: It is possible to support ZExt by zeroing the undef values
20884   // during the shuffle phase or after the shuffle.
20885   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20886       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20887     assert(MemVT != RegVT && "Cannot extend to the same type");
20888     assert(MemVT.isVector() && "Must load a vector from memory");
20889
20890     unsigned NumElems = RegVT.getVectorNumElements();
20891     unsigned MemSz = MemVT.getSizeInBits();
20892     assert(RegSz > MemSz && "Register size must be greater than the mem size");
20893
20894     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20895       return SDValue();
20896
20897     // All sizes must be a power of two.
20898     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20899       return SDValue();
20900
20901     // Attempt to load the original value using scalar loads.
20902     // Find the largest scalar type that divides the total loaded size.
20903     MVT SclrLoadTy = MVT::i8;
20904     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20905          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20906       MVT Tp = (MVT::SimpleValueType)tp;
20907       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20908         SclrLoadTy = Tp;
20909       }
20910     }
20911
20912     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20913     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20914         (64 <= MemSz))
20915       SclrLoadTy = MVT::f64;
20916
20917     // Calculate the number of scalar loads that we need to perform
20918     // in order to load our vector from memory.
20919     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20920     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20921       return SDValue();
20922
20923     unsigned loadRegZize = RegSz;
20924     if (Ext == ISD::SEXTLOAD && RegSz == 256)
20925       loadRegZize /= 2;
20926
20927     // Represent our vector as a sequence of elements which are the
20928     // largest scalar that we can load.
20929     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20930       loadRegZize/SclrLoadTy.getSizeInBits());
20931
20932     // Represent the data using the same element type that is stored in
20933     // memory. In practice, we ''widen'' MemVT.
20934     EVT WideVecVT =
20935           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20936                        loadRegZize/MemVT.getScalarType().getSizeInBits());
20937
20938     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20939       "Invalid vector type");
20940
20941     // We can't shuffle using an illegal type.
20942     if (!TLI.isTypeLegal(WideVecVT))
20943       return SDValue();
20944
20945     SmallVector<SDValue, 8> Chains;
20946     SDValue Ptr = Ld->getBasePtr();
20947     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20948                                         TLI.getPointerTy());
20949     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20950
20951     for (unsigned i = 0; i < NumLoads; ++i) {
20952       // Perform a single load.
20953       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20954                                        Ptr, Ld->getPointerInfo(),
20955                                        Ld->isVolatile(), Ld->isNonTemporal(),
20956                                        Ld->isInvariant(), Ld->getAlignment());
20957       Chains.push_back(ScalarLoad.getValue(1));
20958       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20959       // another round of DAGCombining.
20960       if (i == 0)
20961         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20962       else
20963         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20964                           ScalarLoad, DAG.getIntPtrConstant(i));
20965
20966       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20967     }
20968
20969     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20970
20971     // Bitcast the loaded value to a vector of the original element type, in
20972     // the size of the target vector type.
20973     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20974     unsigned SizeRatio = RegSz/MemSz;
20975
20976     if (Ext == ISD::SEXTLOAD) {
20977       // If we have SSE4.1 we can directly emit a VSEXT node.
20978       if (Subtarget->hasSSE41()) {
20979         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20980         return DCI.CombineTo(N, Sext, TF, true);
20981       }
20982
20983       // Otherwise we'll shuffle the small elements in the high bits of the
20984       // larger type and perform an arithmetic shift. If the shift is not legal
20985       // it's better to scalarize.
20986       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20987         return SDValue();
20988
20989       // Redistribute the loaded elements into the different locations.
20990       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20991       for (unsigned i = 0; i != NumElems; ++i)
20992         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20993
20994       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20995                                            DAG.getUNDEF(WideVecVT),
20996                                            &ShuffleVec[0]);
20997
20998       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20999
21000       // Build the arithmetic shift.
21001       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
21002                      MemVT.getVectorElementType().getSizeInBits();
21003       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
21004                           DAG.getConstant(Amt, RegVT));
21005
21006       return DCI.CombineTo(N, Shuff, TF, true);
21007     }
21008
21009     // Redistribute the loaded elements into the different locations.
21010     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21011     for (unsigned i = 0; i != NumElems; ++i)
21012       ShuffleVec[i*SizeRatio] = i;
21013
21014     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21015                                          DAG.getUNDEF(WideVecVT),
21016                                          &ShuffleVec[0]);
21017
21018     // Bitcast to the requested type.
21019     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21020     // Replace the original load with the new sequence
21021     // and return the new chain.
21022     return DCI.CombineTo(N, Shuff, TF, true);
21023   }
21024
21025   return SDValue();
21026 }
21027
21028 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21029 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21030                                    const X86Subtarget *Subtarget) {
21031   StoreSDNode *St = cast<StoreSDNode>(N);
21032   EVT VT = St->getValue().getValueType();
21033   EVT StVT = St->getMemoryVT();
21034   SDLoc dl(St);
21035   SDValue StoredVal = St->getOperand(1);
21036   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21037
21038   // If we are saving a concatenation of two XMM registers, perform two stores.
21039   // On Sandy Bridge, 256-bit memory operations are executed by two
21040   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21041   // memory  operation.
21042   unsigned Alignment = St->getAlignment();
21043   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21044   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21045       StVT == VT && !IsAligned) {
21046     unsigned NumElems = VT.getVectorNumElements();
21047     if (NumElems < 2)
21048       return SDValue();
21049
21050     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21051     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21052
21053     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21054     SDValue Ptr0 = St->getBasePtr();
21055     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21056
21057     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21058                                 St->getPointerInfo(), St->isVolatile(),
21059                                 St->isNonTemporal(), Alignment);
21060     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21061                                 St->getPointerInfo(), St->isVolatile(),
21062                                 St->isNonTemporal(),
21063                                 std::min(16U, Alignment));
21064     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21065   }
21066
21067   // Optimize trunc store (of multiple scalars) to shuffle and store.
21068   // First, pack all of the elements in one place. Next, store to memory
21069   // in fewer chunks.
21070   if (St->isTruncatingStore() && VT.isVector()) {
21071     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21072     unsigned NumElems = VT.getVectorNumElements();
21073     assert(StVT != VT && "Cannot truncate to the same type");
21074     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21075     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21076
21077     // From, To sizes and ElemCount must be pow of two
21078     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21079     // We are going to use the original vector elt for storing.
21080     // Accumulated smaller vector elements must be a multiple of the store size.
21081     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21082
21083     unsigned SizeRatio  = FromSz / ToSz;
21084
21085     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21086
21087     // Create a type on which we perform the shuffle
21088     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21089             StVT.getScalarType(), NumElems*SizeRatio);
21090
21091     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21092
21093     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21094     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21095     for (unsigned i = 0; i != NumElems; ++i)
21096       ShuffleVec[i] = i * SizeRatio;
21097
21098     // Can't shuffle using an illegal type.
21099     if (!TLI.isTypeLegal(WideVecVT))
21100       return SDValue();
21101
21102     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21103                                          DAG.getUNDEF(WideVecVT),
21104                                          &ShuffleVec[0]);
21105     // At this point all of the data is stored at the bottom of the
21106     // register. We now need to save it to mem.
21107
21108     // Find the largest store unit
21109     MVT StoreType = MVT::i8;
21110     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21111          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21112       MVT Tp = (MVT::SimpleValueType)tp;
21113       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21114         StoreType = Tp;
21115     }
21116
21117     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21118     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21119         (64 <= NumElems * ToSz))
21120       StoreType = MVT::f64;
21121
21122     // Bitcast the original vector into a vector of store-size units
21123     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21124             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21125     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21126     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21127     SmallVector<SDValue, 8> Chains;
21128     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21129                                         TLI.getPointerTy());
21130     SDValue Ptr = St->getBasePtr();
21131
21132     // Perform one or more big stores into memory.
21133     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21134       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21135                                    StoreType, ShuffWide,
21136                                    DAG.getIntPtrConstant(i));
21137       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21138                                 St->getPointerInfo(), St->isVolatile(),
21139                                 St->isNonTemporal(), St->getAlignment());
21140       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21141       Chains.push_back(Ch);
21142     }
21143
21144     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21145   }
21146
21147   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21148   // the FP state in cases where an emms may be missing.
21149   // A preferable solution to the general problem is to figure out the right
21150   // places to insert EMMS.  This qualifies as a quick hack.
21151
21152   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21153   if (VT.getSizeInBits() != 64)
21154     return SDValue();
21155
21156   const Function *F = DAG.getMachineFunction().getFunction();
21157   bool NoImplicitFloatOps = F->getAttributes().
21158     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21159   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21160                      && Subtarget->hasSSE2();
21161   if ((VT.isVector() ||
21162        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21163       isa<LoadSDNode>(St->getValue()) &&
21164       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21165       St->getChain().hasOneUse() && !St->isVolatile()) {
21166     SDNode* LdVal = St->getValue().getNode();
21167     LoadSDNode *Ld = nullptr;
21168     int TokenFactorIndex = -1;
21169     SmallVector<SDValue, 8> Ops;
21170     SDNode* ChainVal = St->getChain().getNode();
21171     // Must be a store of a load.  We currently handle two cases:  the load
21172     // is a direct child, and it's under an intervening TokenFactor.  It is
21173     // possible to dig deeper under nested TokenFactors.
21174     if (ChainVal == LdVal)
21175       Ld = cast<LoadSDNode>(St->getChain());
21176     else if (St->getValue().hasOneUse() &&
21177              ChainVal->getOpcode() == ISD::TokenFactor) {
21178       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21179         if (ChainVal->getOperand(i).getNode() == LdVal) {
21180           TokenFactorIndex = i;
21181           Ld = cast<LoadSDNode>(St->getValue());
21182         } else
21183           Ops.push_back(ChainVal->getOperand(i));
21184       }
21185     }
21186
21187     if (!Ld || !ISD::isNormalLoad(Ld))
21188       return SDValue();
21189
21190     // If this is not the MMX case, i.e. we are just turning i64 load/store
21191     // into f64 load/store, avoid the transformation if there are multiple
21192     // uses of the loaded value.
21193     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21194       return SDValue();
21195
21196     SDLoc LdDL(Ld);
21197     SDLoc StDL(N);
21198     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21199     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21200     // pair instead.
21201     if (Subtarget->is64Bit() || F64IsLegal) {
21202       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21203       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21204                                   Ld->getPointerInfo(), Ld->isVolatile(),
21205                                   Ld->isNonTemporal(), Ld->isInvariant(),
21206                                   Ld->getAlignment());
21207       SDValue NewChain = NewLd.getValue(1);
21208       if (TokenFactorIndex != -1) {
21209         Ops.push_back(NewChain);
21210         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21211       }
21212       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21213                           St->getPointerInfo(),
21214                           St->isVolatile(), St->isNonTemporal(),
21215                           St->getAlignment());
21216     }
21217
21218     // Otherwise, lower to two pairs of 32-bit loads / stores.
21219     SDValue LoAddr = Ld->getBasePtr();
21220     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21221                                  DAG.getConstant(4, MVT::i32));
21222
21223     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21224                                Ld->getPointerInfo(),
21225                                Ld->isVolatile(), Ld->isNonTemporal(),
21226                                Ld->isInvariant(), Ld->getAlignment());
21227     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21228                                Ld->getPointerInfo().getWithOffset(4),
21229                                Ld->isVolatile(), Ld->isNonTemporal(),
21230                                Ld->isInvariant(),
21231                                MinAlign(Ld->getAlignment(), 4));
21232
21233     SDValue NewChain = LoLd.getValue(1);
21234     if (TokenFactorIndex != -1) {
21235       Ops.push_back(LoLd);
21236       Ops.push_back(HiLd);
21237       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21238     }
21239
21240     LoAddr = St->getBasePtr();
21241     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21242                          DAG.getConstant(4, MVT::i32));
21243
21244     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21245                                 St->getPointerInfo(),
21246                                 St->isVolatile(), St->isNonTemporal(),
21247                                 St->getAlignment());
21248     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21249                                 St->getPointerInfo().getWithOffset(4),
21250                                 St->isVolatile(),
21251                                 St->isNonTemporal(),
21252                                 MinAlign(St->getAlignment(), 4));
21253     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21254   }
21255   return SDValue();
21256 }
21257
21258 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21259 /// and return the operands for the horizontal operation in LHS and RHS.  A
21260 /// horizontal operation performs the binary operation on successive elements
21261 /// of its first operand, then on successive elements of its second operand,
21262 /// returning the resulting values in a vector.  For example, if
21263 ///   A = < float a0, float a1, float a2, float a3 >
21264 /// and
21265 ///   B = < float b0, float b1, float b2, float b3 >
21266 /// then the result of doing a horizontal operation on A and B is
21267 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21268 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21269 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21270 /// set to A, RHS to B, and the routine returns 'true'.
21271 /// Note that the binary operation should have the property that if one of the
21272 /// operands is UNDEF then the result is UNDEF.
21273 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21274   // Look for the following pattern: if
21275   //   A = < float a0, float a1, float a2, float a3 >
21276   //   B = < float b0, float b1, float b2, float b3 >
21277   // and
21278   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21279   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21280   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21281   // which is A horizontal-op B.
21282
21283   // At least one of the operands should be a vector shuffle.
21284   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21285       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21286     return false;
21287
21288   MVT VT = LHS.getSimpleValueType();
21289
21290   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21291          "Unsupported vector type for horizontal add/sub");
21292
21293   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21294   // operate independently on 128-bit lanes.
21295   unsigned NumElts = VT.getVectorNumElements();
21296   unsigned NumLanes = VT.getSizeInBits()/128;
21297   unsigned NumLaneElts = NumElts / NumLanes;
21298   assert((NumLaneElts % 2 == 0) &&
21299          "Vector type should have an even number of elements in each lane");
21300   unsigned HalfLaneElts = NumLaneElts/2;
21301
21302   // View LHS in the form
21303   //   LHS = VECTOR_SHUFFLE A, B, LMask
21304   // If LHS is not a shuffle then pretend it is the shuffle
21305   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21306   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21307   // type VT.
21308   SDValue A, B;
21309   SmallVector<int, 16> LMask(NumElts);
21310   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21311     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21312       A = LHS.getOperand(0);
21313     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21314       B = LHS.getOperand(1);
21315     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21316     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21317   } else {
21318     if (LHS.getOpcode() != ISD::UNDEF)
21319       A = LHS;
21320     for (unsigned i = 0; i != NumElts; ++i)
21321       LMask[i] = i;
21322   }
21323
21324   // Likewise, view RHS in the form
21325   //   RHS = VECTOR_SHUFFLE C, D, RMask
21326   SDValue C, D;
21327   SmallVector<int, 16> RMask(NumElts);
21328   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21329     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21330       C = RHS.getOperand(0);
21331     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21332       D = RHS.getOperand(1);
21333     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21334     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21335   } else {
21336     if (RHS.getOpcode() != ISD::UNDEF)
21337       C = RHS;
21338     for (unsigned i = 0; i != NumElts; ++i)
21339       RMask[i] = i;
21340   }
21341
21342   // Check that the shuffles are both shuffling the same vectors.
21343   if (!(A == C && B == D) && !(A == D && B == C))
21344     return false;
21345
21346   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21347   if (!A.getNode() && !B.getNode())
21348     return false;
21349
21350   // If A and B occur in reverse order in RHS, then "swap" them (which means
21351   // rewriting the mask).
21352   if (A != C)
21353     CommuteVectorShuffleMask(RMask, NumElts);
21354
21355   // At this point LHS and RHS are equivalent to
21356   //   LHS = VECTOR_SHUFFLE A, B, LMask
21357   //   RHS = VECTOR_SHUFFLE A, B, RMask
21358   // Check that the masks correspond to performing a horizontal operation.
21359   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21360     for (unsigned i = 0; i != NumLaneElts; ++i) {
21361       int LIdx = LMask[i+l], RIdx = RMask[i+l];
21362
21363       // Ignore any UNDEF components.
21364       if (LIdx < 0 || RIdx < 0 ||
21365           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21366           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21367         continue;
21368
21369       // Check that successive elements are being operated on.  If not, this is
21370       // not a horizontal operation.
21371       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21372       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21373       if (!(LIdx == Index && RIdx == Index + 1) &&
21374           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21375         return false;
21376     }
21377   }
21378
21379   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21380   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21381   return true;
21382 }
21383
21384 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21385 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21386                                   const X86Subtarget *Subtarget) {
21387   EVT VT = N->getValueType(0);
21388   SDValue LHS = N->getOperand(0);
21389   SDValue RHS = N->getOperand(1);
21390
21391   // Try to synthesize horizontal adds from adds of shuffles.
21392   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21393        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21394       isHorizontalBinOp(LHS, RHS, true))
21395     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21396   return SDValue();
21397 }
21398
21399 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21400 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21401                                   const X86Subtarget *Subtarget) {
21402   EVT VT = N->getValueType(0);
21403   SDValue LHS = N->getOperand(0);
21404   SDValue RHS = N->getOperand(1);
21405
21406   // Try to synthesize horizontal subs from subs of shuffles.
21407   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21408        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21409       isHorizontalBinOp(LHS, RHS, false))
21410     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21411   return SDValue();
21412 }
21413
21414 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21415 /// X86ISD::FXOR nodes.
21416 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21417   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21418   // F[X]OR(0.0, x) -> x
21419   // F[X]OR(x, 0.0) -> x
21420   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21421     if (C->getValueAPF().isPosZero())
21422       return N->getOperand(1);
21423   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21424     if (C->getValueAPF().isPosZero())
21425       return N->getOperand(0);
21426   return SDValue();
21427 }
21428
21429 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21430 /// X86ISD::FMAX nodes.
21431 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21432   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21433
21434   // Only perform optimizations if UnsafeMath is used.
21435   if (!DAG.getTarget().Options.UnsafeFPMath)
21436     return SDValue();
21437
21438   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21439   // into FMINC and FMAXC, which are Commutative operations.
21440   unsigned NewOp = 0;
21441   switch (N->getOpcode()) {
21442     default: llvm_unreachable("unknown opcode");
21443     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
21444     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
21445   }
21446
21447   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21448                      N->getOperand(0), N->getOperand(1));
21449 }
21450
21451 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21452 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21453   // FAND(0.0, x) -> 0.0
21454   // FAND(x, 0.0) -> 0.0
21455   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21456     if (C->getValueAPF().isPosZero())
21457       return N->getOperand(0);
21458   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21459     if (C->getValueAPF().isPosZero())
21460       return N->getOperand(1);
21461   return SDValue();
21462 }
21463
21464 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21465 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21466   // FANDN(x, 0.0) -> 0.0
21467   // FANDN(0.0, x) -> x
21468   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21469     if (C->getValueAPF().isPosZero())
21470       return N->getOperand(1);
21471   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21472     if (C->getValueAPF().isPosZero())
21473       return N->getOperand(1);
21474   return SDValue();
21475 }
21476
21477 static SDValue PerformBTCombine(SDNode *N,
21478                                 SelectionDAG &DAG,
21479                                 TargetLowering::DAGCombinerInfo &DCI) {
21480   // BT ignores high bits in the bit index operand.
21481   SDValue Op1 = N->getOperand(1);
21482   if (Op1.hasOneUse()) {
21483     unsigned BitWidth = Op1.getValueSizeInBits();
21484     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21485     APInt KnownZero, KnownOne;
21486     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21487                                           !DCI.isBeforeLegalizeOps());
21488     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21489     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21490         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21491       DCI.CommitTargetLoweringOpt(TLO);
21492   }
21493   return SDValue();
21494 }
21495
21496 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21497   SDValue Op = N->getOperand(0);
21498   if (Op.getOpcode() == ISD::BITCAST)
21499     Op = Op.getOperand(0);
21500   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21501   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21502       VT.getVectorElementType().getSizeInBits() ==
21503       OpVT.getVectorElementType().getSizeInBits()) {
21504     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21505   }
21506   return SDValue();
21507 }
21508
21509 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21510                                                const X86Subtarget *Subtarget) {
21511   EVT VT = N->getValueType(0);
21512   if (!VT.isVector())
21513     return SDValue();
21514
21515   SDValue N0 = N->getOperand(0);
21516   SDValue N1 = N->getOperand(1);
21517   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21518   SDLoc dl(N);
21519
21520   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21521   // both SSE and AVX2 since there is no sign-extended shift right
21522   // operation on a vector with 64-bit elements.
21523   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21524   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21525   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21526       N0.getOpcode() == ISD::SIGN_EXTEND)) {
21527     SDValue N00 = N0.getOperand(0);
21528
21529     // EXTLOAD has a better solution on AVX2,
21530     // it may be replaced with X86ISD::VSEXT node.
21531     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21532       if (!ISD::isNormalLoad(N00.getNode()))
21533         return SDValue();
21534
21535     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21536         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21537                                   N00, N1);
21538       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21539     }
21540   }
21541   return SDValue();
21542 }
21543
21544 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21545                                   TargetLowering::DAGCombinerInfo &DCI,
21546                                   const X86Subtarget *Subtarget) {
21547   if (!DCI.isBeforeLegalizeOps())
21548     return SDValue();
21549
21550   if (!Subtarget->hasFp256())
21551     return SDValue();
21552
21553   EVT VT = N->getValueType(0);
21554   if (VT.isVector() && VT.getSizeInBits() == 256) {
21555     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21556     if (R.getNode())
21557       return R;
21558   }
21559
21560   return SDValue();
21561 }
21562
21563 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21564                                  const X86Subtarget* Subtarget) {
21565   SDLoc dl(N);
21566   EVT VT = N->getValueType(0);
21567
21568   // Let legalize expand this if it isn't a legal type yet.
21569   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21570     return SDValue();
21571
21572   EVT ScalarVT = VT.getScalarType();
21573   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21574       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21575     return SDValue();
21576
21577   SDValue A = N->getOperand(0);
21578   SDValue B = N->getOperand(1);
21579   SDValue C = N->getOperand(2);
21580
21581   bool NegA = (A.getOpcode() == ISD::FNEG);
21582   bool NegB = (B.getOpcode() == ISD::FNEG);
21583   bool NegC = (C.getOpcode() == ISD::FNEG);
21584
21585   // Negative multiplication when NegA xor NegB
21586   bool NegMul = (NegA != NegB);
21587   if (NegA)
21588     A = A.getOperand(0);
21589   if (NegB)
21590     B = B.getOperand(0);
21591   if (NegC)
21592     C = C.getOperand(0);
21593
21594   unsigned Opcode;
21595   if (!NegMul)
21596     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21597   else
21598     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21599
21600   return DAG.getNode(Opcode, dl, VT, A, B, C);
21601 }
21602
21603 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21604                                   TargetLowering::DAGCombinerInfo &DCI,
21605                                   const X86Subtarget *Subtarget) {
21606   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
21607   //           (and (i32 x86isd::setcc_carry), 1)
21608   // This eliminates the zext. This transformation is necessary because
21609   // ISD::SETCC is always legalized to i8.
21610   SDLoc dl(N);
21611   SDValue N0 = N->getOperand(0);
21612   EVT VT = N->getValueType(0);
21613
21614   if (N0.getOpcode() == ISD::AND &&
21615       N0.hasOneUse() &&
21616       N0.getOperand(0).hasOneUse()) {
21617     SDValue N00 = N0.getOperand(0);
21618     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21619       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21620       if (!C || C->getZExtValue() != 1)
21621         return SDValue();
21622       return DAG.getNode(ISD::AND, dl, VT,
21623                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21624                                      N00.getOperand(0), N00.getOperand(1)),
21625                          DAG.getConstant(1, VT));
21626     }
21627   }
21628
21629   if (N0.getOpcode() == ISD::TRUNCATE &&
21630       N0.hasOneUse() &&
21631       N0.getOperand(0).hasOneUse()) {
21632     SDValue N00 = N0.getOperand(0);
21633     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21634       return DAG.getNode(ISD::AND, dl, VT,
21635                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21636                                      N00.getOperand(0), N00.getOperand(1)),
21637                          DAG.getConstant(1, VT));
21638     }
21639   }
21640   if (VT.is256BitVector()) {
21641     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21642     if (R.getNode())
21643       return R;
21644   }
21645
21646   return SDValue();
21647 }
21648
21649 // Optimize x == -y --> x+y == 0
21650 //          x != -y --> x+y != 0
21651 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21652                                       const X86Subtarget* Subtarget) {
21653   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21654   SDValue LHS = N->getOperand(0);
21655   SDValue RHS = N->getOperand(1);
21656   EVT VT = N->getValueType(0);
21657   SDLoc DL(N);
21658
21659   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21660     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21661       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21662         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21663                                    LHS.getValueType(), RHS, LHS.getOperand(1));
21664         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21665                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21666       }
21667   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21668     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21669       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21670         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21671                                    RHS.getValueType(), LHS, RHS.getOperand(1));
21672         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21673                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21674       }
21675
21676   if (VT.getScalarType() == MVT::i1) {
21677     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21678       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21679     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21680     if (!IsSEXT0 && !IsVZero0)
21681       return SDValue();
21682     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21683       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21684     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21685
21686     if (!IsSEXT1 && !IsVZero1)
21687       return SDValue();
21688
21689     if (IsSEXT0 && IsVZero1) {
21690       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21691       if (CC == ISD::SETEQ)
21692         return DAG.getNOT(DL, LHS.getOperand(0), VT);
21693       return LHS.getOperand(0);
21694     }
21695     if (IsSEXT1 && IsVZero0) {
21696       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21697       if (CC == ISD::SETEQ)
21698         return DAG.getNOT(DL, RHS.getOperand(0), VT);
21699       return RHS.getOperand(0);
21700     }
21701   }
21702
21703   return SDValue();
21704 }
21705
21706 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21707                                       const X86Subtarget *Subtarget) {
21708   SDLoc dl(N);
21709   MVT VT = N->getOperand(1)->getSimpleValueType(0);
21710   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21711          "X86insertps is only defined for v4x32");
21712
21713   SDValue Ld = N->getOperand(1);
21714   if (MayFoldLoad(Ld)) {
21715     // Extract the countS bits from the immediate so we can get the proper
21716     // address when narrowing the vector load to a specific element.
21717     // When the second source op is a memory address, interps doesn't use
21718     // countS and just gets an f32 from that address.
21719     unsigned DestIndex =
21720         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21721     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21722   } else
21723     return SDValue();
21724
21725   // Create this as a scalar to vector to match the instruction pattern.
21726   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21727   // countS bits are ignored when loading from memory on insertps, which
21728   // means we don't need to explicitly set them to 0.
21729   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21730                      LoadScalarToVector, N->getOperand(2));
21731 }
21732
21733 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21734 // as "sbb reg,reg", since it can be extended without zext and produces
21735 // an all-ones bit which is more useful than 0/1 in some cases.
21736 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21737                                MVT VT) {
21738   if (VT == MVT::i8)
21739     return DAG.getNode(ISD::AND, DL, VT,
21740                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21741                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21742                        DAG.getConstant(1, VT));
21743   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21744   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21745                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21746                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21747 }
21748
21749 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21750 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21751                                    TargetLowering::DAGCombinerInfo &DCI,
21752                                    const X86Subtarget *Subtarget) {
21753   SDLoc DL(N);
21754   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21755   SDValue EFLAGS = N->getOperand(1);
21756
21757   if (CC == X86::COND_A) {
21758     // Try to convert COND_A into COND_B in an attempt to facilitate
21759     // materializing "setb reg".
21760     //
21761     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21762     // cannot take an immediate as its first operand.
21763     //
21764     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21765         EFLAGS.getValueType().isInteger() &&
21766         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21767       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21768                                    EFLAGS.getNode()->getVTList(),
21769                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21770       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21771       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21772     }
21773   }
21774
21775   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21776   // a zext and produces an all-ones bit which is more useful than 0/1 in some
21777   // cases.
21778   if (CC == X86::COND_B)
21779     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21780
21781   SDValue Flags;
21782
21783   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21784   if (Flags.getNode()) {
21785     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21786     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21787   }
21788
21789   return SDValue();
21790 }
21791
21792 // Optimize branch condition evaluation.
21793 //
21794 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21795                                     TargetLowering::DAGCombinerInfo &DCI,
21796                                     const X86Subtarget *Subtarget) {
21797   SDLoc DL(N);
21798   SDValue Chain = N->getOperand(0);
21799   SDValue Dest = N->getOperand(1);
21800   SDValue EFLAGS = N->getOperand(3);
21801   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21802
21803   SDValue Flags;
21804
21805   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21806   if (Flags.getNode()) {
21807     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21808     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21809                        Flags);
21810   }
21811
21812   return SDValue();
21813 }
21814
21815 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
21816                                                          SelectionDAG &DAG) {
21817   // Take advantage of vector comparisons producing 0 or -1 in each lane to
21818   // optimize away operation when it's from a constant.
21819   //
21820   // The general transformation is:
21821   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
21822   //       AND(VECTOR_CMP(x,y), constant2)
21823   //    constant2 = UNARYOP(constant)
21824
21825   // Early exit if this isn't a vector operation, the operand of the
21826   // unary operation isn't a bitwise AND, or if the sizes of the operations
21827   // aren't the same.
21828   EVT VT = N->getValueType(0);
21829   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
21830       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
21831       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
21832     return SDValue();
21833
21834   // Now check that the other operand of the AND is a constant. We could
21835   // make the transformation for non-constant splats as well, but it's unclear
21836   // that would be a benefit as it would not eliminate any operations, just
21837   // perform one more step in scalar code before moving to the vector unit.
21838   if (BuildVectorSDNode *BV =
21839           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
21840     // Bail out if the vector isn't a constant.
21841     if (!BV->isConstant())
21842       return SDValue();
21843
21844     // Everything checks out. Build up the new and improved node.
21845     SDLoc DL(N);
21846     EVT IntVT = BV->getValueType(0);
21847     // Create a new constant of the appropriate type for the transformed
21848     // DAG.
21849     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
21850     // The AND node needs bitcasts to/from an integer vector type around it.
21851     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
21852     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
21853                                  N->getOperand(0)->getOperand(0), MaskConst);
21854     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
21855     return Res;
21856   }
21857
21858   return SDValue();
21859 }
21860
21861 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21862                                         const X86TargetLowering *XTLI) {
21863   // First try to optimize away the conversion entirely when it's
21864   // conditionally from a constant. Vectors only.
21865   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
21866   if (Res != SDValue())
21867     return Res;
21868
21869   // Now move on to more general possibilities.
21870   SDValue Op0 = N->getOperand(0);
21871   EVT InVT = Op0->getValueType(0);
21872
21873   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21874   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21875     SDLoc dl(N);
21876     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21877     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21878     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21879   }
21880
21881   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21882   // a 32-bit target where SSE doesn't support i64->FP operations.
21883   if (Op0.getOpcode() == ISD::LOAD) {
21884     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21885     EVT VT = Ld->getValueType(0);
21886     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21887         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21888         !XTLI->getSubtarget()->is64Bit() &&
21889         VT == MVT::i64) {
21890       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21891                                           Ld->getChain(), Op0, DAG);
21892       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21893       return FILDChain;
21894     }
21895   }
21896   return SDValue();
21897 }
21898
21899 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21900 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21901                                  X86TargetLowering::DAGCombinerInfo &DCI) {
21902   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21903   // the result is either zero or one (depending on the input carry bit).
21904   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21905   if (X86::isZeroNode(N->getOperand(0)) &&
21906       X86::isZeroNode(N->getOperand(1)) &&
21907       // We don't have a good way to replace an EFLAGS use, so only do this when
21908       // dead right now.
21909       SDValue(N, 1).use_empty()) {
21910     SDLoc DL(N);
21911     EVT VT = N->getValueType(0);
21912     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21913     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21914                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21915                                            DAG.getConstant(X86::COND_B,MVT::i8),
21916                                            N->getOperand(2)),
21917                                DAG.getConstant(1, VT));
21918     return DCI.CombineTo(N, Res1, CarryOut);
21919   }
21920
21921   return SDValue();
21922 }
21923
21924 // fold (add Y, (sete  X, 0)) -> adc  0, Y
21925 //      (add Y, (setne X, 0)) -> sbb -1, Y
21926 //      (sub (sete  X, 0), Y) -> sbb  0, Y
21927 //      (sub (setne X, 0), Y) -> adc -1, Y
21928 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21929   SDLoc DL(N);
21930
21931   // Look through ZExts.
21932   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21933   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21934     return SDValue();
21935
21936   SDValue SetCC = Ext.getOperand(0);
21937   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21938     return SDValue();
21939
21940   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21941   if (CC != X86::COND_E && CC != X86::COND_NE)
21942     return SDValue();
21943
21944   SDValue Cmp = SetCC.getOperand(1);
21945   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21946       !X86::isZeroNode(Cmp.getOperand(1)) ||
21947       !Cmp.getOperand(0).getValueType().isInteger())
21948     return SDValue();
21949
21950   SDValue CmpOp0 = Cmp.getOperand(0);
21951   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21952                                DAG.getConstant(1, CmpOp0.getValueType()));
21953
21954   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21955   if (CC == X86::COND_NE)
21956     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21957                        DL, OtherVal.getValueType(), OtherVal,
21958                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21959   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21960                      DL, OtherVal.getValueType(), OtherVal,
21961                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
21962 }
21963
21964 /// PerformADDCombine - Do target-specific dag combines on integer adds.
21965 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
21966                                  const X86Subtarget *Subtarget) {
21967   EVT VT = N->getValueType(0);
21968   SDValue Op0 = N->getOperand(0);
21969   SDValue Op1 = N->getOperand(1);
21970
21971   // Try to synthesize horizontal adds from adds of shuffles.
21972   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21973        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21974       isHorizontalBinOp(Op0, Op1, true))
21975     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
21976
21977   return OptimizeConditionalInDecrement(N, DAG);
21978 }
21979
21980 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
21981                                  const X86Subtarget *Subtarget) {
21982   SDValue Op0 = N->getOperand(0);
21983   SDValue Op1 = N->getOperand(1);
21984
21985   // X86 can't encode an immediate LHS of a sub. See if we can push the
21986   // negation into a preceding instruction.
21987   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
21988     // If the RHS of the sub is a XOR with one use and a constant, invert the
21989     // immediate. Then add one to the LHS of the sub so we can turn
21990     // X-Y -> X+~Y+1, saving one register.
21991     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
21992         isa<ConstantSDNode>(Op1.getOperand(1))) {
21993       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
21994       EVT VT = Op0.getValueType();
21995       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
21996                                    Op1.getOperand(0),
21997                                    DAG.getConstant(~XorC, VT));
21998       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
21999                          DAG.getConstant(C->getAPIntValue()+1, VT));
22000     }
22001   }
22002
22003   // Try to synthesize horizontal adds from adds of shuffles.
22004   EVT VT = N->getValueType(0);
22005   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22006        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22007       isHorizontalBinOp(Op0, Op1, true))
22008     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22009
22010   return OptimizeConditionalInDecrement(N, DAG);
22011 }
22012
22013 /// performVZEXTCombine - Performs build vector combines
22014 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22015                                         TargetLowering::DAGCombinerInfo &DCI,
22016                                         const X86Subtarget *Subtarget) {
22017   // (vzext (bitcast (vzext (x)) -> (vzext x)
22018   SDValue In = N->getOperand(0);
22019   while (In.getOpcode() == ISD::BITCAST)
22020     In = In.getOperand(0);
22021
22022   if (In.getOpcode() != X86ISD::VZEXT)
22023     return SDValue();
22024
22025   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22026                      In.getOperand(0));
22027 }
22028
22029 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22030                                              DAGCombinerInfo &DCI) const {
22031   SelectionDAG &DAG = DCI.DAG;
22032   switch (N->getOpcode()) {
22033   default: break;
22034   case ISD::EXTRACT_VECTOR_ELT:
22035     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22036   case ISD::VSELECT:
22037   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22038   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22039   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22040   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22041   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22042   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22043   case ISD::SHL:
22044   case ISD::SRA:
22045   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22046   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22047   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22048   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22049   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22050   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22051   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22052   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22053   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22054   case X86ISD::FXOR:
22055   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22056   case X86ISD::FMIN:
22057   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22058   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22059   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22060   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22061   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22062   case ISD::ANY_EXTEND:
22063   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22064   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22065   case ISD::SIGN_EXTEND_INREG:
22066     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22067   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22068   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22069   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22070   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22071   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22072   case X86ISD::SHUFP:       // Handle all target specific shuffles
22073   case X86ISD::PALIGNR:
22074   case X86ISD::UNPCKH:
22075   case X86ISD::UNPCKL:
22076   case X86ISD::MOVHLPS:
22077   case X86ISD::MOVLHPS:
22078   case X86ISD::PSHUFD:
22079   case X86ISD::PSHUFHW:
22080   case X86ISD::PSHUFLW:
22081   case X86ISD::MOVSS:
22082   case X86ISD::MOVSD:
22083   case X86ISD::VPERMILP:
22084   case X86ISD::VPERM2X128:
22085   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22086   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22087   case ISD::INTRINSIC_WO_CHAIN:
22088     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22089   case X86ISD::INSERTPS:
22090     return PerformINSERTPSCombine(N, DAG, Subtarget);
22091   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22092   }
22093
22094   return SDValue();
22095 }
22096
22097 /// isTypeDesirableForOp - Return true if the target has native support for
22098 /// the specified value type and it is 'desirable' to use the type for the
22099 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22100 /// instruction encodings are longer and some i16 instructions are slow.
22101 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22102   if (!isTypeLegal(VT))
22103     return false;
22104   if (VT != MVT::i16)
22105     return true;
22106
22107   switch (Opc) {
22108   default:
22109     return true;
22110   case ISD::LOAD:
22111   case ISD::SIGN_EXTEND:
22112   case ISD::ZERO_EXTEND:
22113   case ISD::ANY_EXTEND:
22114   case ISD::SHL:
22115   case ISD::SRL:
22116   case ISD::SUB:
22117   case ISD::ADD:
22118   case ISD::MUL:
22119   case ISD::AND:
22120   case ISD::OR:
22121   case ISD::XOR:
22122     return false;
22123   }
22124 }
22125
22126 /// IsDesirableToPromoteOp - This method query the target whether it is
22127 /// beneficial for dag combiner to promote the specified node. If true, it
22128 /// should return the desired promotion type by reference.
22129 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22130   EVT VT = Op.getValueType();
22131   if (VT != MVT::i16)
22132     return false;
22133
22134   bool Promote = false;
22135   bool Commute = false;
22136   switch (Op.getOpcode()) {
22137   default: break;
22138   case ISD::LOAD: {
22139     LoadSDNode *LD = cast<LoadSDNode>(Op);
22140     // If the non-extending load has a single use and it's not live out, then it
22141     // might be folded.
22142     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22143                                                      Op.hasOneUse()*/) {
22144       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22145              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22146         // The only case where we'd want to promote LOAD (rather then it being
22147         // promoted as an operand is when it's only use is liveout.
22148         if (UI->getOpcode() != ISD::CopyToReg)
22149           return false;
22150       }
22151     }
22152     Promote = true;
22153     break;
22154   }
22155   case ISD::SIGN_EXTEND:
22156   case ISD::ZERO_EXTEND:
22157   case ISD::ANY_EXTEND:
22158     Promote = true;
22159     break;
22160   case ISD::SHL:
22161   case ISD::SRL: {
22162     SDValue N0 = Op.getOperand(0);
22163     // Look out for (store (shl (load), x)).
22164     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22165       return false;
22166     Promote = true;
22167     break;
22168   }
22169   case ISD::ADD:
22170   case ISD::MUL:
22171   case ISD::AND:
22172   case ISD::OR:
22173   case ISD::XOR:
22174     Commute = true;
22175     // fallthrough
22176   case ISD::SUB: {
22177     SDValue N0 = Op.getOperand(0);
22178     SDValue N1 = Op.getOperand(1);
22179     if (!Commute && MayFoldLoad(N1))
22180       return false;
22181     // Avoid disabling potential load folding opportunities.
22182     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22183       return false;
22184     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22185       return false;
22186     Promote = true;
22187   }
22188   }
22189
22190   PVT = MVT::i32;
22191   return Promote;
22192 }
22193
22194 //===----------------------------------------------------------------------===//
22195 //                           X86 Inline Assembly Support
22196 //===----------------------------------------------------------------------===//
22197
22198 namespace {
22199   // Helper to match a string separated by whitespace.
22200   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22201     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22202
22203     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22204       StringRef piece(*args[i]);
22205       if (!s.startswith(piece)) // Check if the piece matches.
22206         return false;
22207
22208       s = s.substr(piece.size());
22209       StringRef::size_type pos = s.find_first_not_of(" \t");
22210       if (pos == 0) // We matched a prefix.
22211         return false;
22212
22213       s = s.substr(pos);
22214     }
22215
22216     return s.empty();
22217   }
22218   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22219 }
22220
22221 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22222
22223   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22224     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22225         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22226         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22227
22228       if (AsmPieces.size() == 3)
22229         return true;
22230       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22231         return true;
22232     }
22233   }
22234   return false;
22235 }
22236
22237 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22238   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22239
22240   std::string AsmStr = IA->getAsmString();
22241
22242   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22243   if (!Ty || Ty->getBitWidth() % 16 != 0)
22244     return false;
22245
22246   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22247   SmallVector<StringRef, 4> AsmPieces;
22248   SplitString(AsmStr, AsmPieces, ";\n");
22249
22250   switch (AsmPieces.size()) {
22251   default: return false;
22252   case 1:
22253     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22254     // we will turn this bswap into something that will be lowered to logical
22255     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22256     // lower so don't worry about this.
22257     // bswap $0
22258     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22259         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22260         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22261         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22262         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22263         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22264       // No need to check constraints, nothing other than the equivalent of
22265       // "=r,0" would be valid here.
22266       return IntrinsicLowering::LowerToByteSwap(CI);
22267     }
22268
22269     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22270     if (CI->getType()->isIntegerTy(16) &&
22271         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22272         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22273          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22274       AsmPieces.clear();
22275       const std::string &ConstraintsStr = IA->getConstraintString();
22276       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22277       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22278       if (clobbersFlagRegisters(AsmPieces))
22279         return IntrinsicLowering::LowerToByteSwap(CI);
22280     }
22281     break;
22282   case 3:
22283     if (CI->getType()->isIntegerTy(32) &&
22284         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22285         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22286         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22287         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22288       AsmPieces.clear();
22289       const std::string &ConstraintsStr = IA->getConstraintString();
22290       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22291       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22292       if (clobbersFlagRegisters(AsmPieces))
22293         return IntrinsicLowering::LowerToByteSwap(CI);
22294     }
22295
22296     if (CI->getType()->isIntegerTy(64)) {
22297       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22298       if (Constraints.size() >= 2 &&
22299           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22300           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22301         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22302         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22303             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22304             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22305           return IntrinsicLowering::LowerToByteSwap(CI);
22306       }
22307     }
22308     break;
22309   }
22310   return false;
22311 }
22312
22313 /// getConstraintType - Given a constraint letter, return the type of
22314 /// constraint it is for this target.
22315 X86TargetLowering::ConstraintType
22316 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22317   if (Constraint.size() == 1) {
22318     switch (Constraint[0]) {
22319     case 'R':
22320     case 'q':
22321     case 'Q':
22322     case 'f':
22323     case 't':
22324     case 'u':
22325     case 'y':
22326     case 'x':
22327     case 'Y':
22328     case 'l':
22329       return C_RegisterClass;
22330     case 'a':
22331     case 'b':
22332     case 'c':
22333     case 'd':
22334     case 'S':
22335     case 'D':
22336     case 'A':
22337       return C_Register;
22338     case 'I':
22339     case 'J':
22340     case 'K':
22341     case 'L':
22342     case 'M':
22343     case 'N':
22344     case 'G':
22345     case 'C':
22346     case 'e':
22347     case 'Z':
22348       return C_Other;
22349     default:
22350       break;
22351     }
22352   }
22353   return TargetLowering::getConstraintType(Constraint);
22354 }
22355
22356 /// Examine constraint type and operand type and determine a weight value.
22357 /// This object must already have been set up with the operand type
22358 /// and the current alternative constraint selected.
22359 TargetLowering::ConstraintWeight
22360   X86TargetLowering::getSingleConstraintMatchWeight(
22361     AsmOperandInfo &info, const char *constraint) const {
22362   ConstraintWeight weight = CW_Invalid;
22363   Value *CallOperandVal = info.CallOperandVal;
22364     // If we don't have a value, we can't do a match,
22365     // but allow it at the lowest weight.
22366   if (!CallOperandVal)
22367     return CW_Default;
22368   Type *type = CallOperandVal->getType();
22369   // Look at the constraint type.
22370   switch (*constraint) {
22371   default:
22372     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22373   case 'R':
22374   case 'q':
22375   case 'Q':
22376   case 'a':
22377   case 'b':
22378   case 'c':
22379   case 'd':
22380   case 'S':
22381   case 'D':
22382   case 'A':
22383     if (CallOperandVal->getType()->isIntegerTy())
22384       weight = CW_SpecificReg;
22385     break;
22386   case 'f':
22387   case 't':
22388   case 'u':
22389     if (type->isFloatingPointTy())
22390       weight = CW_SpecificReg;
22391     break;
22392   case 'y':
22393     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22394       weight = CW_SpecificReg;
22395     break;
22396   case 'x':
22397   case 'Y':
22398     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22399         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22400       weight = CW_Register;
22401     break;
22402   case 'I':
22403     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22404       if (C->getZExtValue() <= 31)
22405         weight = CW_Constant;
22406     }
22407     break;
22408   case 'J':
22409     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22410       if (C->getZExtValue() <= 63)
22411         weight = CW_Constant;
22412     }
22413     break;
22414   case 'K':
22415     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22416       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22417         weight = CW_Constant;
22418     }
22419     break;
22420   case 'L':
22421     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22422       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22423         weight = CW_Constant;
22424     }
22425     break;
22426   case 'M':
22427     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22428       if (C->getZExtValue() <= 3)
22429         weight = CW_Constant;
22430     }
22431     break;
22432   case 'N':
22433     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22434       if (C->getZExtValue() <= 0xff)
22435         weight = CW_Constant;
22436     }
22437     break;
22438   case 'G':
22439   case 'C':
22440     if (dyn_cast<ConstantFP>(CallOperandVal)) {
22441       weight = CW_Constant;
22442     }
22443     break;
22444   case 'e':
22445     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22446       if ((C->getSExtValue() >= -0x80000000LL) &&
22447           (C->getSExtValue() <= 0x7fffffffLL))
22448         weight = CW_Constant;
22449     }
22450     break;
22451   case 'Z':
22452     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22453       if (C->getZExtValue() <= 0xffffffff)
22454         weight = CW_Constant;
22455     }
22456     break;
22457   }
22458   return weight;
22459 }
22460
22461 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22462 /// with another that has more specific requirements based on the type of the
22463 /// corresponding operand.
22464 const char *X86TargetLowering::
22465 LowerXConstraint(EVT ConstraintVT) const {
22466   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22467   // 'f' like normal targets.
22468   if (ConstraintVT.isFloatingPoint()) {
22469     if (Subtarget->hasSSE2())
22470       return "Y";
22471     if (Subtarget->hasSSE1())
22472       return "x";
22473   }
22474
22475   return TargetLowering::LowerXConstraint(ConstraintVT);
22476 }
22477
22478 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22479 /// vector.  If it is invalid, don't add anything to Ops.
22480 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22481                                                      std::string &Constraint,
22482                                                      std::vector<SDValue>&Ops,
22483                                                      SelectionDAG &DAG) const {
22484   SDValue Result;
22485
22486   // Only support length 1 constraints for now.
22487   if (Constraint.length() > 1) return;
22488
22489   char ConstraintLetter = Constraint[0];
22490   switch (ConstraintLetter) {
22491   default: break;
22492   case 'I':
22493     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22494       if (C->getZExtValue() <= 31) {
22495         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22496         break;
22497       }
22498     }
22499     return;
22500   case 'J':
22501     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22502       if (C->getZExtValue() <= 63) {
22503         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22504         break;
22505       }
22506     }
22507     return;
22508   case 'K':
22509     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22510       if (isInt<8>(C->getSExtValue())) {
22511         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22512         break;
22513       }
22514     }
22515     return;
22516   case 'N':
22517     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22518       if (C->getZExtValue() <= 255) {
22519         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22520         break;
22521       }
22522     }
22523     return;
22524   case 'e': {
22525     // 32-bit signed value
22526     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22527       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22528                                            C->getSExtValue())) {
22529         // Widen to 64 bits here to get it sign extended.
22530         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22531         break;
22532       }
22533     // FIXME gcc accepts some relocatable values here too, but only in certain
22534     // memory models; it's complicated.
22535     }
22536     return;
22537   }
22538   case 'Z': {
22539     // 32-bit unsigned value
22540     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22541       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22542                                            C->getZExtValue())) {
22543         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22544         break;
22545       }
22546     }
22547     // FIXME gcc accepts some relocatable values here too, but only in certain
22548     // memory models; it's complicated.
22549     return;
22550   }
22551   case 'i': {
22552     // Literal immediates are always ok.
22553     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22554       // Widen to 64 bits here to get it sign extended.
22555       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22556       break;
22557     }
22558
22559     // In any sort of PIC mode addresses need to be computed at runtime by
22560     // adding in a register or some sort of table lookup.  These can't
22561     // be used as immediates.
22562     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22563       return;
22564
22565     // If we are in non-pic codegen mode, we allow the address of a global (with
22566     // an optional displacement) to be used with 'i'.
22567     GlobalAddressSDNode *GA = nullptr;
22568     int64_t Offset = 0;
22569
22570     // Match either (GA), (GA+C), (GA+C1+C2), etc.
22571     while (1) {
22572       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22573         Offset += GA->getOffset();
22574         break;
22575       } else if (Op.getOpcode() == ISD::ADD) {
22576         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22577           Offset += C->getZExtValue();
22578           Op = Op.getOperand(0);
22579           continue;
22580         }
22581       } else if (Op.getOpcode() == ISD::SUB) {
22582         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22583           Offset += -C->getZExtValue();
22584           Op = Op.getOperand(0);
22585           continue;
22586         }
22587       }
22588
22589       // Otherwise, this isn't something we can handle, reject it.
22590       return;
22591     }
22592
22593     const GlobalValue *GV = GA->getGlobal();
22594     // If we require an extra load to get this address, as in PIC mode, we
22595     // can't accept it.
22596     if (isGlobalStubReference(
22597             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22598       return;
22599
22600     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22601                                         GA->getValueType(0), Offset);
22602     break;
22603   }
22604   }
22605
22606   if (Result.getNode()) {
22607     Ops.push_back(Result);
22608     return;
22609   }
22610   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22611 }
22612
22613 std::pair<unsigned, const TargetRegisterClass*>
22614 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22615                                                 MVT VT) const {
22616   // First, see if this is a constraint that directly corresponds to an LLVM
22617   // register class.
22618   if (Constraint.size() == 1) {
22619     // GCC Constraint Letters
22620     switch (Constraint[0]) {
22621     default: break;
22622       // TODO: Slight differences here in allocation order and leaving
22623       // RIP in the class. Do they matter any more here than they do
22624       // in the normal allocation?
22625     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22626       if (Subtarget->is64Bit()) {
22627         if (VT == MVT::i32 || VT == MVT::f32)
22628           return std::make_pair(0U, &X86::GR32RegClass);
22629         if (VT == MVT::i16)
22630           return std::make_pair(0U, &X86::GR16RegClass);
22631         if (VT == MVT::i8 || VT == MVT::i1)
22632           return std::make_pair(0U, &X86::GR8RegClass);
22633         if (VT == MVT::i64 || VT == MVT::f64)
22634           return std::make_pair(0U, &X86::GR64RegClass);
22635         break;
22636       }
22637       // 32-bit fallthrough
22638     case 'Q':   // Q_REGS
22639       if (VT == MVT::i32 || VT == MVT::f32)
22640         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22641       if (VT == MVT::i16)
22642         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22643       if (VT == MVT::i8 || VT == MVT::i1)
22644         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22645       if (VT == MVT::i64)
22646         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22647       break;
22648     case 'r':   // GENERAL_REGS
22649     case 'l':   // INDEX_REGS
22650       if (VT == MVT::i8 || VT == MVT::i1)
22651         return std::make_pair(0U, &X86::GR8RegClass);
22652       if (VT == MVT::i16)
22653         return std::make_pair(0U, &X86::GR16RegClass);
22654       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22655         return std::make_pair(0U, &X86::GR32RegClass);
22656       return std::make_pair(0U, &X86::GR64RegClass);
22657     case 'R':   // LEGACY_REGS
22658       if (VT == MVT::i8 || VT == MVT::i1)
22659         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22660       if (VT == MVT::i16)
22661         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22662       if (VT == MVT::i32 || !Subtarget->is64Bit())
22663         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22664       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22665     case 'f':  // FP Stack registers.
22666       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22667       // value to the correct fpstack register class.
22668       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22669         return std::make_pair(0U, &X86::RFP32RegClass);
22670       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22671         return std::make_pair(0U, &X86::RFP64RegClass);
22672       return std::make_pair(0U, &X86::RFP80RegClass);
22673     case 'y':   // MMX_REGS if MMX allowed.
22674       if (!Subtarget->hasMMX()) break;
22675       return std::make_pair(0U, &X86::VR64RegClass);
22676     case 'Y':   // SSE_REGS if SSE2 allowed
22677       if (!Subtarget->hasSSE2()) break;
22678       // FALL THROUGH.
22679     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22680       if (!Subtarget->hasSSE1()) break;
22681
22682       switch (VT.SimpleTy) {
22683       default: break;
22684       // Scalar SSE types.
22685       case MVT::f32:
22686       case MVT::i32:
22687         return std::make_pair(0U, &X86::FR32RegClass);
22688       case MVT::f64:
22689       case MVT::i64:
22690         return std::make_pair(0U, &X86::FR64RegClass);
22691       // Vector types.
22692       case MVT::v16i8:
22693       case MVT::v8i16:
22694       case MVT::v4i32:
22695       case MVT::v2i64:
22696       case MVT::v4f32:
22697       case MVT::v2f64:
22698         return std::make_pair(0U, &X86::VR128RegClass);
22699       // AVX types.
22700       case MVT::v32i8:
22701       case MVT::v16i16:
22702       case MVT::v8i32:
22703       case MVT::v4i64:
22704       case MVT::v8f32:
22705       case MVT::v4f64:
22706         return std::make_pair(0U, &X86::VR256RegClass);
22707       case MVT::v8f64:
22708       case MVT::v16f32:
22709       case MVT::v16i32:
22710       case MVT::v8i64:
22711         return std::make_pair(0U, &X86::VR512RegClass);
22712       }
22713       break;
22714     }
22715   }
22716
22717   // Use the default implementation in TargetLowering to convert the register
22718   // constraint into a member of a register class.
22719   std::pair<unsigned, const TargetRegisterClass*> Res;
22720   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22721
22722   // Not found as a standard register?
22723   if (!Res.second) {
22724     // Map st(0) -> st(7) -> ST0
22725     if (Constraint.size() == 7 && Constraint[0] == '{' &&
22726         tolower(Constraint[1]) == 's' &&
22727         tolower(Constraint[2]) == 't' &&
22728         Constraint[3] == '(' &&
22729         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22730         Constraint[5] == ')' &&
22731         Constraint[6] == '}') {
22732
22733       Res.first = X86::ST0+Constraint[4]-'0';
22734       Res.second = &X86::RFP80RegClass;
22735       return Res;
22736     }
22737
22738     // GCC allows "st(0)" to be called just plain "st".
22739     if (StringRef("{st}").equals_lower(Constraint)) {
22740       Res.first = X86::ST0;
22741       Res.second = &X86::RFP80RegClass;
22742       return Res;
22743     }
22744
22745     // flags -> EFLAGS
22746     if (StringRef("{flags}").equals_lower(Constraint)) {
22747       Res.first = X86::EFLAGS;
22748       Res.second = &X86::CCRRegClass;
22749       return Res;
22750     }
22751
22752     // 'A' means EAX + EDX.
22753     if (Constraint == "A") {
22754       Res.first = X86::EAX;
22755       Res.second = &X86::GR32_ADRegClass;
22756       return Res;
22757     }
22758     return Res;
22759   }
22760
22761   // Otherwise, check to see if this is a register class of the wrong value
22762   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22763   // turn into {ax},{dx}.
22764   if (Res.second->hasType(VT))
22765     return Res;   // Correct type already, nothing to do.
22766
22767   // All of the single-register GCC register classes map their values onto
22768   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
22769   // really want an 8-bit or 32-bit register, map to the appropriate register
22770   // class and return the appropriate register.
22771   if (Res.second == &X86::GR16RegClass) {
22772     if (VT == MVT::i8 || VT == MVT::i1) {
22773       unsigned DestReg = 0;
22774       switch (Res.first) {
22775       default: break;
22776       case X86::AX: DestReg = X86::AL; break;
22777       case X86::DX: DestReg = X86::DL; break;
22778       case X86::CX: DestReg = X86::CL; break;
22779       case X86::BX: DestReg = X86::BL; break;
22780       }
22781       if (DestReg) {
22782         Res.first = DestReg;
22783         Res.second = &X86::GR8RegClass;
22784       }
22785     } else if (VT == MVT::i32 || VT == MVT::f32) {
22786       unsigned DestReg = 0;
22787       switch (Res.first) {
22788       default: break;
22789       case X86::AX: DestReg = X86::EAX; break;
22790       case X86::DX: DestReg = X86::EDX; break;
22791       case X86::CX: DestReg = X86::ECX; break;
22792       case X86::BX: DestReg = X86::EBX; break;
22793       case X86::SI: DestReg = X86::ESI; break;
22794       case X86::DI: DestReg = X86::EDI; break;
22795       case X86::BP: DestReg = X86::EBP; break;
22796       case X86::SP: DestReg = X86::ESP; break;
22797       }
22798       if (DestReg) {
22799         Res.first = DestReg;
22800         Res.second = &X86::GR32RegClass;
22801       }
22802     } else if (VT == MVT::i64 || VT == MVT::f64) {
22803       unsigned DestReg = 0;
22804       switch (Res.first) {
22805       default: break;
22806       case X86::AX: DestReg = X86::RAX; break;
22807       case X86::DX: DestReg = X86::RDX; break;
22808       case X86::CX: DestReg = X86::RCX; break;
22809       case X86::BX: DestReg = X86::RBX; break;
22810       case X86::SI: DestReg = X86::RSI; break;
22811       case X86::DI: DestReg = X86::RDI; break;
22812       case X86::BP: DestReg = X86::RBP; break;
22813       case X86::SP: DestReg = X86::RSP; break;
22814       }
22815       if (DestReg) {
22816         Res.first = DestReg;
22817         Res.second = &X86::GR64RegClass;
22818       }
22819     }
22820   } else if (Res.second == &X86::FR32RegClass ||
22821              Res.second == &X86::FR64RegClass ||
22822              Res.second == &X86::VR128RegClass ||
22823              Res.second == &X86::VR256RegClass ||
22824              Res.second == &X86::FR32XRegClass ||
22825              Res.second == &X86::FR64XRegClass ||
22826              Res.second == &X86::VR128XRegClass ||
22827              Res.second == &X86::VR256XRegClass ||
22828              Res.second == &X86::VR512RegClass) {
22829     // Handle references to XMM physical registers that got mapped into the
22830     // wrong class.  This can happen with constraints like {xmm0} where the
22831     // target independent register mapper will just pick the first match it can
22832     // find, ignoring the required type.
22833
22834     if (VT == MVT::f32 || VT == MVT::i32)
22835       Res.second = &X86::FR32RegClass;
22836     else if (VT == MVT::f64 || VT == MVT::i64)
22837       Res.second = &X86::FR64RegClass;
22838     else if (X86::VR128RegClass.hasType(VT))
22839       Res.second = &X86::VR128RegClass;
22840     else if (X86::VR256RegClass.hasType(VT))
22841       Res.second = &X86::VR256RegClass;
22842     else if (X86::VR512RegClass.hasType(VT))
22843       Res.second = &X86::VR512RegClass;
22844   }
22845
22846   return Res;
22847 }
22848
22849 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22850                                             Type *Ty) const {
22851   // Scaling factors are not free at all.
22852   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22853   // will take 2 allocations in the out of order engine instead of 1
22854   // for plain addressing mode, i.e. inst (reg1).
22855   // E.g.,
22856   // vaddps (%rsi,%drx), %ymm0, %ymm1
22857   // Requires two allocations (one for the load, one for the computation)
22858   // whereas:
22859   // vaddps (%rsi), %ymm0, %ymm1
22860   // Requires just 1 allocation, i.e., freeing allocations for other operations
22861   // and having less micro operations to execute.
22862   //
22863   // For some X86 architectures, this is even worse because for instance for
22864   // stores, the complex addressing mode forces the instruction to use the
22865   // "load" ports instead of the dedicated "store" port.
22866   // E.g., on Haswell:
22867   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22868   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
22869   if (isLegalAddressingMode(AM, Ty))
22870     // Scale represents reg2 * scale, thus account for 1
22871     // as soon as we use a second register.
22872     return AM.Scale != 0;
22873   return -1;
22874 }
22875
22876 bool X86TargetLowering::isTargetFTOL() const {
22877   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
22878 }