9cb9e6abbefa4147825279d79a4c918e027e1cf2
[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       TM.getSubtarget<X86Subtarget>().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, getPointerTy(), Custom);
663
664   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
665     // f32 and f64 use SSE.
666     // Set up the FP register classes.
667     addRegisterClass(MVT::f32, &X86::FR32RegClass);
668     addRegisterClass(MVT::f64, &X86::FR64RegClass);
669
670     // Use ANDPD to simulate FABS.
671     setOperationAction(ISD::FABS , MVT::f64, Custom);
672     setOperationAction(ISD::FABS , MVT::f32, Custom);
673
674     // Use XORP to simulate FNEG.
675     setOperationAction(ISD::FNEG , MVT::f64, Custom);
676     setOperationAction(ISD::FNEG , MVT::f32, Custom);
677
678     // Use ANDPD and ORPD to simulate FCOPYSIGN.
679     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
680     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
681
682     // Lower this to FGETSIGNx86 plus an AND.
683     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
684     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
685
686     // We don't support sin/cos/fmod
687     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
688     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
689     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
690     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
691     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
692     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
693
694     // Expand FP immediates into loads from the stack, except for the special
695     // cases we handle.
696     addLegalFPImmediate(APFloat(+0.0)); // xorpd
697     addLegalFPImmediate(APFloat(+0.0f)); // xorps
698   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
699     // Use SSE for f32, x87 for f64.
700     // Set up the FP register classes.
701     addRegisterClass(MVT::f32, &X86::FR32RegClass);
702     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
703
704     // Use ANDPS to simulate FABS.
705     setOperationAction(ISD::FABS , MVT::f32, Custom);
706
707     // Use XORP to simulate FNEG.
708     setOperationAction(ISD::FNEG , MVT::f32, Custom);
709
710     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
711
712     // Use ANDPS and ORPS to simulate FCOPYSIGN.
713     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
714     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
715
716     // We don't support sin/cos/fmod
717     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
718     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
719     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
720
721     // Special cases we handle for FP constants.
722     addLegalFPImmediate(APFloat(+0.0f)); // xorps
723     addLegalFPImmediate(APFloat(+0.0)); // FLD0
724     addLegalFPImmediate(APFloat(+1.0)); // FLD1
725     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
726     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
727
728     if (!TM.Options.UnsafeFPMath) {
729       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
730       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
731       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
732     }
733   } else if (!TM.Options.UseSoftFloat) {
734     // f32 and f64 in x87.
735     // Set up the FP register classes.
736     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
737     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
738
739     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
740     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
741     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
743
744     if (!TM.Options.UnsafeFPMath) {
745       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
746       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
747       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
749       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
751     }
752     addLegalFPImmediate(APFloat(+0.0)); // FLD0
753     addLegalFPImmediate(APFloat(+1.0)); // FLD1
754     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
755     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
756     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
757     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
758     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
759     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
760   }
761
762   // We don't support FMA.
763   setOperationAction(ISD::FMA, MVT::f64, Expand);
764   setOperationAction(ISD::FMA, MVT::f32, Expand);
765
766   // Long double always uses X87.
767   if (!TM.Options.UseSoftFloat) {
768     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
769     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
770     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
771     {
772       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
773       addLegalFPImmediate(TmpFlt);  // FLD0
774       TmpFlt.changeSign();
775       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
776
777       bool ignored;
778       APFloat TmpFlt2(+1.0);
779       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
780                       &ignored);
781       addLegalFPImmediate(TmpFlt2);  // FLD1
782       TmpFlt2.changeSign();
783       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
784     }
785
786     if (!TM.Options.UnsafeFPMath) {
787       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
788       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
789       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
790     }
791
792     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
793     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
794     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
795     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
796     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
797     setOperationAction(ISD::FMA, MVT::f80, Expand);
798   }
799
800   // Always use a library call for pow.
801   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
802   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
804
805   setOperationAction(ISD::FLOG, MVT::f80, Expand);
806   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
808   setOperationAction(ISD::FEXP, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
810
811   // First set operation action for all vector types to either promote
812   // (for widening) or expand (for scalarization). Then we will selectively
813   // turn on ones that can be effectively codegen'd.
814   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
815            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
816     MVT VT = (MVT::SimpleValueType)i;
817     setOperationAction(ISD::ADD , VT, Expand);
818     setOperationAction(ISD::SUB , VT, Expand);
819     setOperationAction(ISD::FADD, VT, Expand);
820     setOperationAction(ISD::FNEG, VT, Expand);
821     setOperationAction(ISD::FSUB, VT, Expand);
822     setOperationAction(ISD::MUL , VT, Expand);
823     setOperationAction(ISD::FMUL, VT, Expand);
824     setOperationAction(ISD::SDIV, VT, Expand);
825     setOperationAction(ISD::UDIV, VT, Expand);
826     setOperationAction(ISD::FDIV, VT, Expand);
827     setOperationAction(ISD::SREM, VT, Expand);
828     setOperationAction(ISD::UREM, VT, Expand);
829     setOperationAction(ISD::LOAD, VT, Expand);
830     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
831     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
832     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
833     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
834     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::FABS, VT, Expand);
836     setOperationAction(ISD::FSIN, VT, Expand);
837     setOperationAction(ISD::FSINCOS, VT, Expand);
838     setOperationAction(ISD::FCOS, VT, Expand);
839     setOperationAction(ISD::FSINCOS, VT, Expand);
840     setOperationAction(ISD::FREM, VT, Expand);
841     setOperationAction(ISD::FMA,  VT, Expand);
842     setOperationAction(ISD::FPOWI, VT, Expand);
843     setOperationAction(ISD::FSQRT, VT, Expand);
844     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
845     setOperationAction(ISD::FFLOOR, VT, Expand);
846     setOperationAction(ISD::FCEIL, VT, Expand);
847     setOperationAction(ISD::FTRUNC, VT, Expand);
848     setOperationAction(ISD::FRINT, VT, Expand);
849     setOperationAction(ISD::FNEARBYINT, VT, Expand);
850     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
851     setOperationAction(ISD::MULHS, VT, Expand);
852     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
853     setOperationAction(ISD::MULHU, VT, Expand);
854     setOperationAction(ISD::SDIVREM, VT, Expand);
855     setOperationAction(ISD::UDIVREM, VT, Expand);
856     setOperationAction(ISD::FPOW, VT, Expand);
857     setOperationAction(ISD::CTPOP, VT, Expand);
858     setOperationAction(ISD::CTTZ, VT, Expand);
859     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
860     setOperationAction(ISD::CTLZ, VT, Expand);
861     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
862     setOperationAction(ISD::SHL, VT, Expand);
863     setOperationAction(ISD::SRA, VT, Expand);
864     setOperationAction(ISD::SRL, VT, Expand);
865     setOperationAction(ISD::ROTL, VT, Expand);
866     setOperationAction(ISD::ROTR, VT, Expand);
867     setOperationAction(ISD::BSWAP, VT, Expand);
868     setOperationAction(ISD::SETCC, VT, Expand);
869     setOperationAction(ISD::FLOG, VT, Expand);
870     setOperationAction(ISD::FLOG2, VT, Expand);
871     setOperationAction(ISD::FLOG10, VT, Expand);
872     setOperationAction(ISD::FEXP, VT, Expand);
873     setOperationAction(ISD::FEXP2, VT, Expand);
874     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
875     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
876     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
877     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
879     setOperationAction(ISD::TRUNCATE, VT, Expand);
880     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
881     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
882     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
883     setOperationAction(ISD::VSELECT, VT, Expand);
884     setOperationAction(ISD::SELECT_CC, VT, Expand);
885     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
886              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
887       setTruncStoreAction(VT,
888                           (MVT::SimpleValueType)InnerVT, Expand);
889     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
890     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
891
892     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
893     // we have to deal with them whether we ask for Expansion or not. Setting
894     // Expand causes its own optimisation problems though, so leave them legal.
895     if (VT.getVectorElementType() == MVT::i1)
896       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
897   }
898
899   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
900   // with -msoft-float, disable use of MMX as well.
901   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
902     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
903     // No operations on x86mmx supported, everything uses intrinsics.
904   }
905
906   // MMX-sized vectors (other than x86mmx) are expected to be expanded
907   // into smaller operations.
908   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
909   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
910   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
912   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
913   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
914   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
915   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
916   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
917   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
918   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
919   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
920   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
921   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
922   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
923   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
924   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
928   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
929   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
930   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
931   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
933   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
937
938   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
939     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
940
941     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
942     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
946     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
947     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
948     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
949     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
950     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
951     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
952     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
953   }
954
955   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
956     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
957
958     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
959     // registers cannot be used even for integer operations.
960     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
961     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
962     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
963     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
964
965     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
966     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
967     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
968     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
969     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
970     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
971     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
972     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
974     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
975     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
976     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
977     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
978     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
979     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
980     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
981     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
985     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
986     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
987
988     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
989     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
992
993     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
998
999     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1000     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1001       MVT VT = (MVT::SimpleValueType)i;
1002       // Do not attempt to custom lower non-power-of-2 vectors
1003       if (!isPowerOf2_32(VT.getVectorNumElements()))
1004         continue;
1005       // Do not attempt to custom lower non-128-bit vectors
1006       if (!VT.is128BitVector())
1007         continue;
1008       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1009       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1010       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1011     }
1012
1013     // We support custom legalizing of sext and anyext loads for specific
1014     // memory vector types which we can load as a scalar (or sequence of
1015     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1016     // loads these must work with a single scalar load.
1017     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1018     if (Subtarget->is64Bit()) {
1019       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1020       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1021     }
1022     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1028
1029     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1030     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1031     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1032     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1033     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1034     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1035
1036     if (Subtarget->is64Bit()) {
1037       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1038       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1039     }
1040
1041     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1042     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1043       MVT VT = (MVT::SimpleValueType)i;
1044
1045       // Do not attempt to promote non-128-bit vectors
1046       if (!VT.is128BitVector())
1047         continue;
1048
1049       setOperationAction(ISD::AND,    VT, Promote);
1050       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1051       setOperationAction(ISD::OR,     VT, Promote);
1052       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1053       setOperationAction(ISD::XOR,    VT, Promote);
1054       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1055       setOperationAction(ISD::LOAD,   VT, Promote);
1056       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1057       setOperationAction(ISD::SELECT, VT, Promote);
1058       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1059     }
1060
1061     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1062
1063     // Custom lower v2i64 and v2f64 selects.
1064     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1065     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1066     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1067     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1068
1069     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1070     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1071
1072     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1074     // As there is no 64-bit GPR available, we need build a special custom
1075     // sequence to convert from v2i32 to v2f32.
1076     if (!Subtarget->is64Bit())
1077       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1078
1079     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1080     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1081
1082     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1083
1084     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1085     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1086     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1087   }
1088
1089   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1090     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1091     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1092     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1093     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1094     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1095     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1096     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1097     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1098     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1099     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1100
1101     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1102     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1103     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1104     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1105     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1106     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1107     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1108     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1109     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1110     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1111
1112     // FIXME: Do we need to handle scalar-to-vector here?
1113     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1114
1115     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1116     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1119     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1120     // There is no BLENDI for byte vectors. We don't need to custom lower
1121     // some vselects for now.
1122     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1123
1124     // SSE41 brings specific instructions for doing vector sign extend even in
1125     // cases where we don't have SRA.
1126     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1128     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1129
1130     // i8 and i16 vectors are custom because the source register and source
1131     // source memory operand types are not the same width.  f32 vectors are
1132     // custom since the immediate controlling the insert encodes additional
1133     // information.
1134     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1138
1139     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1143
1144     // FIXME: these should be Legal, but that's only for the case where
1145     // the index is constant.  For now custom expand to deal with that.
1146     if (Subtarget->is64Bit()) {
1147       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1148       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1149     }
1150   }
1151
1152   if (Subtarget->hasSSE2()) {
1153     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1154     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1155
1156     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1157     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1158
1159     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1160     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1161
1162     // In the customized shift lowering, the legal cases in AVX2 will be
1163     // recognized.
1164     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1165     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1166
1167     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1168     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1169
1170     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1171   }
1172
1173   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1174     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1175     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1176     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1177     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1179     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1180
1181     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1182     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1183     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1184
1185     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1186     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1190     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1191     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1192     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1193     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1194     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1195     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1196     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1197
1198     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1199     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1203     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1204     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1205     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1206     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1207     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1208     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1209     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1210
1211     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1212     // even though v8i16 is a legal type.
1213     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1214     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1215     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1216
1217     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1218     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1219     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1220
1221     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1222     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1223
1224     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1225
1226     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1227     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1228
1229     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1230     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1231
1232     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1233     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1234
1235     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1236     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1238     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1239
1240     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1241     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1242     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1243
1244     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1245     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1247     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1248
1249     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1251     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1252     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1254     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1255     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1257     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1258     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1260     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1261
1262     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1263       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1264       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1266       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1267       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1268       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1269     }
1270
1271     if (Subtarget->hasInt256()) {
1272       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1273       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1275       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1276
1277       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1278       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1280       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1281
1282       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1283       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1284       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1285       // Don't lower v32i8 because there is no 128-bit byte mul
1286
1287       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1288       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1289       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1290       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1291
1292       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1293       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1294     } else {
1295       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1296       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1298       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1299
1300       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1301       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1303       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1304
1305       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1306       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1307       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1308       // Don't lower v32i8 because there is no 128-bit byte mul
1309     }
1310
1311     // In the customized shift lowering, the legal cases in AVX2 will be
1312     // recognized.
1313     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1314     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1315
1316     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1317     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1318
1319     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1320
1321     // Custom lower several nodes for 256-bit types.
1322     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1323              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1324       MVT VT = (MVT::SimpleValueType)i;
1325
1326       // Extract subvector is special because the value type
1327       // (result) is 128-bit but the source is 256-bit wide.
1328       if (VT.is128BitVector())
1329         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1330
1331       // Do not attempt to custom lower other non-256-bit vectors
1332       if (!VT.is256BitVector())
1333         continue;
1334
1335       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1336       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1337       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1338       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1339       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1340       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1341       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1342     }
1343
1344     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1345     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1346       MVT VT = (MVT::SimpleValueType)i;
1347
1348       // Do not attempt to promote non-256-bit vectors
1349       if (!VT.is256BitVector())
1350         continue;
1351
1352       setOperationAction(ISD::AND,    VT, Promote);
1353       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1354       setOperationAction(ISD::OR,     VT, Promote);
1355       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1356       setOperationAction(ISD::XOR,    VT, Promote);
1357       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1358       setOperationAction(ISD::LOAD,   VT, Promote);
1359       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1360       setOperationAction(ISD::SELECT, VT, Promote);
1361       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1362     }
1363   }
1364
1365   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1366     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1367     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1368     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1369     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1370
1371     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1372     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1373     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1374
1375     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1376     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1377     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1378     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1379     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1380     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1381     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1385     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1386
1387     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1388     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1391     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1392     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1393
1394     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1395     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1398     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1399     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1400     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1401     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1402
1403     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1404     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1405     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1406     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1407     if (Subtarget->is64Bit()) {
1408       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1409       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1410       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1411       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1412     }
1413     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1414     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1416     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1417     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1418     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1421     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1422     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1423
1424     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1425     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1430     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1432     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1437
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1444
1445     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1446     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1447
1448     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1449
1450     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1452     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1454     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1459
1460     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1461     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1462
1463     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1464     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1465
1466     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1467
1468     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1469     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1470
1471     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1472     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1473
1474     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1475     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1476
1477     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1478     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1479     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1480     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1481     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1482     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1483
1484     if (Subtarget->hasCDI()) {
1485       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1486       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1487     }
1488
1489     // Custom lower several nodes.
1490     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1491              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1492       MVT VT = (MVT::SimpleValueType)i;
1493
1494       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1495       // Extract subvector is special because the value type
1496       // (result) is 256/128-bit but the source is 512-bit wide.
1497       if (VT.is128BitVector() || VT.is256BitVector())
1498         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1499
1500       if (VT.getVectorElementType() == MVT::i1)
1501         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1502
1503       // Do not attempt to custom lower other non-512-bit vectors
1504       if (!VT.is512BitVector())
1505         continue;
1506
1507       if ( EltSize >= 32) {
1508         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1509         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1510         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1511         setOperationAction(ISD::VSELECT,             VT, Legal);
1512         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1513         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1514         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1515       }
1516     }
1517     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1518       MVT VT = (MVT::SimpleValueType)i;
1519
1520       // Do not attempt to promote non-256-bit vectors
1521       if (!VT.is512BitVector())
1522         continue;
1523
1524       setOperationAction(ISD::SELECT, VT, Promote);
1525       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1526     }
1527   }// has  AVX-512
1528
1529   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1530     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1531     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1532   }
1533
1534   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1535   // of this type with custom code.
1536   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1537            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1538     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1539                        Custom);
1540   }
1541
1542   // We want to custom lower some of our intrinsics.
1543   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1544   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1545   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1546   if (!Subtarget->is64Bit())
1547     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1548
1549   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1550   // handle type legalization for these operations here.
1551   //
1552   // FIXME: We really should do custom legalization for addition and
1553   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1554   // than generic legalization for 64-bit multiplication-with-overflow, though.
1555   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1556     // Add/Sub/Mul with overflow operations are custom lowered.
1557     MVT VT = IntVTs[i];
1558     setOperationAction(ISD::SADDO, VT, Custom);
1559     setOperationAction(ISD::UADDO, VT, Custom);
1560     setOperationAction(ISD::SSUBO, VT, Custom);
1561     setOperationAction(ISD::USUBO, VT, Custom);
1562     setOperationAction(ISD::SMULO, VT, Custom);
1563     setOperationAction(ISD::UMULO, VT, Custom);
1564   }
1565
1566   // There are no 8-bit 3-address imul/mul instructions
1567   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1568   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1569
1570   if (!Subtarget->is64Bit()) {
1571     // These libcalls are not available in 32-bit.
1572     setLibcallName(RTLIB::SHL_I128, nullptr);
1573     setLibcallName(RTLIB::SRL_I128, nullptr);
1574     setLibcallName(RTLIB::SRA_I128, nullptr);
1575   }
1576
1577   // Combine sin / cos into one node or libcall if possible.
1578   if (Subtarget->hasSinCos()) {
1579     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1580     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1581     if (Subtarget->isTargetDarwin()) {
1582       // For MacOSX, we don't want to the normal expansion of a libcall to
1583       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1584       // traffic.
1585       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1586       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1587     }
1588   }
1589
1590   if (Subtarget->isTargetWin64()) {
1591     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1592     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1593     setOperationAction(ISD::SREM, MVT::i128, Custom);
1594     setOperationAction(ISD::UREM, MVT::i128, Custom);
1595     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1596     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1597   }
1598
1599   // We have target-specific dag combine patterns for the following nodes:
1600   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1601   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1602   setTargetDAGCombine(ISD::VSELECT);
1603   setTargetDAGCombine(ISD::SELECT);
1604   setTargetDAGCombine(ISD::SHL);
1605   setTargetDAGCombine(ISD::SRA);
1606   setTargetDAGCombine(ISD::SRL);
1607   setTargetDAGCombine(ISD::OR);
1608   setTargetDAGCombine(ISD::AND);
1609   setTargetDAGCombine(ISD::ADD);
1610   setTargetDAGCombine(ISD::FADD);
1611   setTargetDAGCombine(ISD::FSUB);
1612   setTargetDAGCombine(ISD::FMA);
1613   setTargetDAGCombine(ISD::SUB);
1614   setTargetDAGCombine(ISD::LOAD);
1615   setTargetDAGCombine(ISD::STORE);
1616   setTargetDAGCombine(ISD::ZERO_EXTEND);
1617   setTargetDAGCombine(ISD::ANY_EXTEND);
1618   setTargetDAGCombine(ISD::SIGN_EXTEND);
1619   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1620   setTargetDAGCombine(ISD::TRUNCATE);
1621   setTargetDAGCombine(ISD::SINT_TO_FP);
1622   setTargetDAGCombine(ISD::SETCC);
1623   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1624   setTargetDAGCombine(ISD::BUILD_VECTOR);
1625   if (Subtarget->is64Bit())
1626     setTargetDAGCombine(ISD::MUL);
1627   setTargetDAGCombine(ISD::XOR);
1628
1629   computeRegisterProperties();
1630
1631   // On Darwin, -Os means optimize for size without hurting performance,
1632   // do not reduce the limit.
1633   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1634   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1635   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1636   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1637   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1638   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1639   setPrefLoopAlignment(4); // 2^4 bytes.
1640
1641   // Predictable cmov don't hurt on atom because it's in-order.
1642   PredictableSelectIsExpensive = !Subtarget->isAtom();
1643
1644   setPrefFunctionAlignment(4); // 2^4 bytes.
1645 }
1646
1647 // This has so far only been implemented for 64-bit MachO.
1648 bool X86TargetLowering::useLoadStackGuardNode() const {
1649   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1650          Subtarget->is64Bit();
1651 }
1652
1653 TargetLoweringBase::LegalizeTypeAction
1654 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1655   if (ExperimentalVectorWideningLegalization &&
1656       VT.getVectorNumElements() != 1 &&
1657       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1658     return TypeWidenVector;
1659
1660   return TargetLoweringBase::getPreferredVectorAction(VT);
1661 }
1662
1663 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1664   if (!VT.isVector())
1665     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1666
1667   if (Subtarget->hasAVX512())
1668     switch(VT.getVectorNumElements()) {
1669     case  8: return MVT::v8i1;
1670     case 16: return MVT::v16i1;
1671   }
1672
1673   return VT.changeVectorElementTypeToInteger();
1674 }
1675
1676 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1677 /// the desired ByVal argument alignment.
1678 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1679   if (MaxAlign == 16)
1680     return;
1681   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1682     if (VTy->getBitWidth() == 128)
1683       MaxAlign = 16;
1684   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1685     unsigned EltAlign = 0;
1686     getMaxByValAlign(ATy->getElementType(), EltAlign);
1687     if (EltAlign > MaxAlign)
1688       MaxAlign = EltAlign;
1689   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1690     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1691       unsigned EltAlign = 0;
1692       getMaxByValAlign(STy->getElementType(i), EltAlign);
1693       if (EltAlign > MaxAlign)
1694         MaxAlign = EltAlign;
1695       if (MaxAlign == 16)
1696         break;
1697     }
1698   }
1699 }
1700
1701 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1702 /// function arguments in the caller parameter area. For X86, aggregates
1703 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1704 /// are at 4-byte boundaries.
1705 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1706   if (Subtarget->is64Bit()) {
1707     // Max of 8 and alignment of type.
1708     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1709     if (TyAlign > 8)
1710       return TyAlign;
1711     return 8;
1712   }
1713
1714   unsigned Align = 4;
1715   if (Subtarget->hasSSE1())
1716     getMaxByValAlign(Ty, Align);
1717   return Align;
1718 }
1719
1720 /// getOptimalMemOpType - Returns the target specific optimal type for load
1721 /// and store operations as a result of memset, memcpy, and memmove
1722 /// lowering. If DstAlign is zero that means it's safe to destination
1723 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1724 /// means there isn't a need to check it against alignment requirement,
1725 /// probably because the source does not need to be loaded. If 'IsMemset' is
1726 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1727 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1728 /// source is constant so it does not need to be loaded.
1729 /// It returns EVT::Other if the type should be determined using generic
1730 /// target-independent logic.
1731 EVT
1732 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1733                                        unsigned DstAlign, unsigned SrcAlign,
1734                                        bool IsMemset, bool ZeroMemset,
1735                                        bool MemcpyStrSrc,
1736                                        MachineFunction &MF) const {
1737   const Function *F = MF.getFunction();
1738   if ((!IsMemset || ZeroMemset) &&
1739       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1740                                        Attribute::NoImplicitFloat)) {
1741     if (Size >= 16 &&
1742         (Subtarget->isUnalignedMemAccessFast() ||
1743          ((DstAlign == 0 || DstAlign >= 16) &&
1744           (SrcAlign == 0 || SrcAlign >= 16)))) {
1745       if (Size >= 32) {
1746         if (Subtarget->hasInt256())
1747           return MVT::v8i32;
1748         if (Subtarget->hasFp256())
1749           return MVT::v8f32;
1750       }
1751       if (Subtarget->hasSSE2())
1752         return MVT::v4i32;
1753       if (Subtarget->hasSSE1())
1754         return MVT::v4f32;
1755     } else if (!MemcpyStrSrc && Size >= 8 &&
1756                !Subtarget->is64Bit() &&
1757                Subtarget->hasSSE2()) {
1758       // Do not use f64 to lower memcpy if source is string constant. It's
1759       // better to use i32 to avoid the loads.
1760       return MVT::f64;
1761     }
1762   }
1763   if (Subtarget->is64Bit() && Size >= 8)
1764     return MVT::i64;
1765   return MVT::i32;
1766 }
1767
1768 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1769   if (VT == MVT::f32)
1770     return X86ScalarSSEf32;
1771   else if (VT == MVT::f64)
1772     return X86ScalarSSEf64;
1773   return true;
1774 }
1775
1776 bool
1777 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1778                                                   unsigned,
1779                                                   unsigned,
1780                                                   bool *Fast) const {
1781   if (Fast)
1782     *Fast = Subtarget->isUnalignedMemAccessFast();
1783   return true;
1784 }
1785
1786 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1787 /// current function.  The returned value is a member of the
1788 /// MachineJumpTableInfo::JTEntryKind enum.
1789 unsigned X86TargetLowering::getJumpTableEncoding() const {
1790   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1791   // symbol.
1792   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1793       Subtarget->isPICStyleGOT())
1794     return MachineJumpTableInfo::EK_Custom32;
1795
1796   // Otherwise, use the normal jump table encoding heuristics.
1797   return TargetLowering::getJumpTableEncoding();
1798 }
1799
1800 const MCExpr *
1801 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1802                                              const MachineBasicBlock *MBB,
1803                                              unsigned uid,MCContext &Ctx) const{
1804   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1805          Subtarget->isPICStyleGOT());
1806   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1807   // entries.
1808   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1809                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1810 }
1811
1812 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1813 /// jumptable.
1814 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1815                                                     SelectionDAG &DAG) const {
1816   if (!Subtarget->is64Bit())
1817     // This doesn't have SDLoc associated with it, but is not really the
1818     // same as a Register.
1819     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1820   return Table;
1821 }
1822
1823 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1824 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1825 /// MCExpr.
1826 const MCExpr *X86TargetLowering::
1827 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1828                              MCContext &Ctx) const {
1829   // X86-64 uses RIP relative addressing based on the jump table label.
1830   if (Subtarget->isPICStyleRIPRel())
1831     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1832
1833   // Otherwise, the reference is relative to the PIC base.
1834   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1835 }
1836
1837 // FIXME: Why this routine is here? Move to RegInfo!
1838 std::pair<const TargetRegisterClass*, uint8_t>
1839 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1840   const TargetRegisterClass *RRC = nullptr;
1841   uint8_t Cost = 1;
1842   switch (VT.SimpleTy) {
1843   default:
1844     return TargetLowering::findRepresentativeClass(VT);
1845   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1846     RRC = Subtarget->is64Bit() ?
1847       (const TargetRegisterClass*)&X86::GR64RegClass :
1848       (const TargetRegisterClass*)&X86::GR32RegClass;
1849     break;
1850   case MVT::x86mmx:
1851     RRC = &X86::VR64RegClass;
1852     break;
1853   case MVT::f32: case MVT::f64:
1854   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1855   case MVT::v4f32: case MVT::v2f64:
1856   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1857   case MVT::v4f64:
1858     RRC = &X86::VR128RegClass;
1859     break;
1860   }
1861   return std::make_pair(RRC, Cost);
1862 }
1863
1864 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1865                                                unsigned &Offset) const {
1866   if (!Subtarget->isTargetLinux())
1867     return false;
1868
1869   if (Subtarget->is64Bit()) {
1870     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1871     Offset = 0x28;
1872     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1873       AddressSpace = 256;
1874     else
1875       AddressSpace = 257;
1876   } else {
1877     // %gs:0x14 on i386
1878     Offset = 0x14;
1879     AddressSpace = 256;
1880   }
1881   return true;
1882 }
1883
1884 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1885                                             unsigned DestAS) const {
1886   assert(SrcAS != DestAS && "Expected different address spaces!");
1887
1888   return SrcAS < 256 && DestAS < 256;
1889 }
1890
1891 //===----------------------------------------------------------------------===//
1892 //               Return Value Calling Convention Implementation
1893 //===----------------------------------------------------------------------===//
1894
1895 #include "X86GenCallingConv.inc"
1896
1897 bool
1898 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1899                                   MachineFunction &MF, bool isVarArg,
1900                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1901                         LLVMContext &Context) const {
1902   SmallVector<CCValAssign, 16> RVLocs;
1903   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1904   return CCInfo.CheckReturn(Outs, RetCC_X86);
1905 }
1906
1907 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1908   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1909   return ScratchRegs;
1910 }
1911
1912 SDValue
1913 X86TargetLowering::LowerReturn(SDValue Chain,
1914                                CallingConv::ID CallConv, bool isVarArg,
1915                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1916                                const SmallVectorImpl<SDValue> &OutVals,
1917                                SDLoc dl, SelectionDAG &DAG) const {
1918   MachineFunction &MF = DAG.getMachineFunction();
1919   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1920
1921   SmallVector<CCValAssign, 16> RVLocs;
1922   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1923   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1924
1925   SDValue Flag;
1926   SmallVector<SDValue, 6> RetOps;
1927   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1928   // Operand #1 = Bytes To Pop
1929   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1930                    MVT::i16));
1931
1932   // Copy the result values into the output registers.
1933   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1934     CCValAssign &VA = RVLocs[i];
1935     assert(VA.isRegLoc() && "Can only return in registers!");
1936     SDValue ValToCopy = OutVals[i];
1937     EVT ValVT = ValToCopy.getValueType();
1938
1939     // Promote values to the appropriate types
1940     if (VA.getLocInfo() == CCValAssign::SExt)
1941       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1942     else if (VA.getLocInfo() == CCValAssign::ZExt)
1943       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1944     else if (VA.getLocInfo() == CCValAssign::AExt)
1945       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1946     else if (VA.getLocInfo() == CCValAssign::BCvt)
1947       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1948
1949     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1950            "Unexpected FP-extend for return value.");  
1951
1952     // If this is x86-64, and we disabled SSE, we can't return FP values,
1953     // or SSE or MMX vectors.
1954     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1955          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1956           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1957       report_fatal_error("SSE register return with SSE disabled");
1958     }
1959     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1960     // llvm-gcc has never done it right and no one has noticed, so this
1961     // should be OK for now.
1962     if (ValVT == MVT::f64 &&
1963         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1964       report_fatal_error("SSE2 register return with SSE2 disabled");
1965
1966     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1967     // the RET instruction and handled by the FP Stackifier.
1968     if (VA.getLocReg() == X86::FP0 ||
1969         VA.getLocReg() == X86::FP1) {
1970       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1971       // change the value to the FP stack register class.
1972       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1973         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1974       RetOps.push_back(ValToCopy);
1975       // Don't emit a copytoreg.
1976       continue;
1977     }
1978
1979     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1980     // which is returned in RAX / RDX.
1981     if (Subtarget->is64Bit()) {
1982       if (ValVT == MVT::x86mmx) {
1983         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1984           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1985           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1986                                   ValToCopy);
1987           // If we don't have SSE2 available, convert to v4f32 so the generated
1988           // register is legal.
1989           if (!Subtarget->hasSSE2())
1990             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1991         }
1992       }
1993     }
1994
1995     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1996     Flag = Chain.getValue(1);
1997     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1998   }
1999
2000   // The x86-64 ABIs require that for returning structs by value we copy
2001   // the sret argument into %rax/%eax (depending on ABI) for the return.
2002   // Win32 requires us to put the sret argument to %eax as well.
2003   // We saved the argument into a virtual register in the entry block,
2004   // so now we copy the value out and into %rax/%eax.
2005   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2006       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2007     MachineFunction &MF = DAG.getMachineFunction();
2008     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2009     unsigned Reg = FuncInfo->getSRetReturnReg();
2010     assert(Reg &&
2011            "SRetReturnReg should have been set in LowerFormalArguments().");
2012     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2013
2014     unsigned RetValReg
2015         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2016           X86::RAX : X86::EAX;
2017     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2018     Flag = Chain.getValue(1);
2019
2020     // RAX/EAX now acts like a return value.
2021     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2022   }
2023
2024   RetOps[0] = Chain;  // Update chain.
2025
2026   // Add the flag if we have it.
2027   if (Flag.getNode())
2028     RetOps.push_back(Flag);
2029
2030   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2031 }
2032
2033 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2034   if (N->getNumValues() != 1)
2035     return false;
2036   if (!N->hasNUsesOfValue(1, 0))
2037     return false;
2038
2039   SDValue TCChain = Chain;
2040   SDNode *Copy = *N->use_begin();
2041   if (Copy->getOpcode() == ISD::CopyToReg) {
2042     // If the copy has a glue operand, we conservatively assume it isn't safe to
2043     // perform a tail call.
2044     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2045       return false;
2046     TCChain = Copy->getOperand(0);
2047   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2048     return false;
2049
2050   bool HasRet = false;
2051   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2052        UI != UE; ++UI) {
2053     if (UI->getOpcode() != X86ISD::RET_FLAG)
2054       return false;
2055     // If we are returning more than one value, we can definitely
2056     // not make a tail call see PR19530
2057     if (UI->getNumOperands() > 4)
2058       return false;
2059     if (UI->getNumOperands() == 4 &&
2060         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2061       return false;
2062     HasRet = true;
2063   }
2064
2065   if (!HasRet)
2066     return false;
2067
2068   Chain = TCChain;
2069   return true;
2070 }
2071
2072 EVT
2073 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2074                                             ISD::NodeType ExtendKind) const {
2075   MVT ReturnMVT;
2076   // TODO: Is this also valid on 32-bit?
2077   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2078     ReturnMVT = MVT::i8;
2079   else
2080     ReturnMVT = MVT::i32;
2081
2082   EVT MinVT = getRegisterType(Context, ReturnMVT);
2083   return VT.bitsLT(MinVT) ? MinVT : VT;
2084 }
2085
2086 /// LowerCallResult - Lower the result values of a call into the
2087 /// appropriate copies out of appropriate physical registers.
2088 ///
2089 SDValue
2090 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2091                                    CallingConv::ID CallConv, bool isVarArg,
2092                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2093                                    SDLoc dl, SelectionDAG &DAG,
2094                                    SmallVectorImpl<SDValue> &InVals) const {
2095
2096   // Assign locations to each value returned by this call.
2097   SmallVector<CCValAssign, 16> RVLocs;
2098   bool Is64Bit = Subtarget->is64Bit();
2099   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2100                  *DAG.getContext());
2101   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2102
2103   // Copy all of the result registers out of their specified physreg.
2104   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2105     CCValAssign &VA = RVLocs[i];
2106     EVT CopyVT = VA.getValVT();
2107
2108     // If this is x86-64, and we disabled SSE, we can't return FP values
2109     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2110         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2111       report_fatal_error("SSE register return with SSE disabled");
2112     }
2113
2114     // If we prefer to use the value in xmm registers, copy it out as f80 and
2115     // use a truncate to move it from fp stack reg to xmm reg.
2116     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2117         isScalarFPTypeInSSEReg(VA.getValVT()))
2118       CopyVT = MVT::f80;
2119
2120     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2121                                CopyVT, InFlag).getValue(1);
2122     SDValue Val = Chain.getValue(0);
2123
2124     if (CopyVT != VA.getValVT())
2125       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2126                         // This truncation won't change the value.
2127                         DAG.getIntPtrConstant(1));
2128
2129     InFlag = Chain.getValue(2);
2130     InVals.push_back(Val);
2131   }
2132
2133   return Chain;
2134 }
2135
2136 //===----------------------------------------------------------------------===//
2137 //                C & StdCall & Fast Calling Convention implementation
2138 //===----------------------------------------------------------------------===//
2139 //  StdCall calling convention seems to be standard for many Windows' API
2140 //  routines and around. It differs from C calling convention just a little:
2141 //  callee should clean up the stack, not caller. Symbols should be also
2142 //  decorated in some fancy way :) It doesn't support any vector arguments.
2143 //  For info on fast calling convention see Fast Calling Convention (tail call)
2144 //  implementation LowerX86_32FastCCCallTo.
2145
2146 /// CallIsStructReturn - Determines whether a call uses struct return
2147 /// semantics.
2148 enum StructReturnType {
2149   NotStructReturn,
2150   RegStructReturn,
2151   StackStructReturn
2152 };
2153 static StructReturnType
2154 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2155   if (Outs.empty())
2156     return NotStructReturn;
2157
2158   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2159   if (!Flags.isSRet())
2160     return NotStructReturn;
2161   if (Flags.isInReg())
2162     return RegStructReturn;
2163   return StackStructReturn;
2164 }
2165
2166 /// ArgsAreStructReturn - Determines whether a function uses struct
2167 /// return semantics.
2168 static StructReturnType
2169 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2170   if (Ins.empty())
2171     return NotStructReturn;
2172
2173   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2174   if (!Flags.isSRet())
2175     return NotStructReturn;
2176   if (Flags.isInReg())
2177     return RegStructReturn;
2178   return StackStructReturn;
2179 }
2180
2181 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2182 /// by "Src" to address "Dst" with size and alignment information specified by
2183 /// the specific parameter attribute. The copy will be passed as a byval
2184 /// function parameter.
2185 static SDValue
2186 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2187                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2188                           SDLoc dl) {
2189   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2190
2191   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2192                        /*isVolatile*/false, /*AlwaysInline=*/true,
2193                        MachinePointerInfo(), MachinePointerInfo());
2194 }
2195
2196 /// IsTailCallConvention - Return true if the calling convention is one that
2197 /// supports tail call optimization.
2198 static bool IsTailCallConvention(CallingConv::ID CC) {
2199   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2200           CC == CallingConv::HiPE);
2201 }
2202
2203 /// \brief Return true if the calling convention is a C calling convention.
2204 static bool IsCCallConvention(CallingConv::ID CC) {
2205   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2206           CC == CallingConv::X86_64_SysV);
2207 }
2208
2209 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2210   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2211     return false;
2212
2213   CallSite CS(CI);
2214   CallingConv::ID CalleeCC = CS.getCallingConv();
2215   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2216     return false;
2217
2218   return true;
2219 }
2220
2221 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2222 /// a tailcall target by changing its ABI.
2223 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2224                                    bool GuaranteedTailCallOpt) {
2225   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2226 }
2227
2228 SDValue
2229 X86TargetLowering::LowerMemArgument(SDValue Chain,
2230                                     CallingConv::ID CallConv,
2231                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2232                                     SDLoc dl, SelectionDAG &DAG,
2233                                     const CCValAssign &VA,
2234                                     MachineFrameInfo *MFI,
2235                                     unsigned i) const {
2236   // Create the nodes corresponding to a load from this parameter slot.
2237   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2238   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2239       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2240   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2241   EVT ValVT;
2242
2243   // If value is passed by pointer we have address passed instead of the value
2244   // itself.
2245   if (VA.getLocInfo() == CCValAssign::Indirect)
2246     ValVT = VA.getLocVT();
2247   else
2248     ValVT = VA.getValVT();
2249
2250   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2251   // changed with more analysis.
2252   // In case of tail call optimization mark all arguments mutable. Since they
2253   // could be overwritten by lowering of arguments in case of a tail call.
2254   if (Flags.isByVal()) {
2255     unsigned Bytes = Flags.getByValSize();
2256     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2257     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2258     return DAG.getFrameIndex(FI, getPointerTy());
2259   } else {
2260     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2261                                     VA.getLocMemOffset(), isImmutable);
2262     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2263     return DAG.getLoad(ValVT, dl, Chain, FIN,
2264                        MachinePointerInfo::getFixedStack(FI),
2265                        false, false, false, 0);
2266   }
2267 }
2268
2269 SDValue
2270 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2271                                         CallingConv::ID CallConv,
2272                                         bool isVarArg,
2273                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2274                                         SDLoc dl,
2275                                         SelectionDAG &DAG,
2276                                         SmallVectorImpl<SDValue> &InVals)
2277                                           const {
2278   MachineFunction &MF = DAG.getMachineFunction();
2279   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2280
2281   const Function* Fn = MF.getFunction();
2282   if (Fn->hasExternalLinkage() &&
2283       Subtarget->isTargetCygMing() &&
2284       Fn->getName() == "main")
2285     FuncInfo->setForceFramePointer(true);
2286
2287   MachineFrameInfo *MFI = MF.getFrameInfo();
2288   bool Is64Bit = Subtarget->is64Bit();
2289   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2290
2291   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2292          "Var args not supported with calling convention fastcc, ghc or hipe");
2293
2294   // Assign locations to all of the incoming arguments.
2295   SmallVector<CCValAssign, 16> ArgLocs;
2296   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2297
2298   // Allocate shadow area for Win64
2299   if (IsWin64)
2300     CCInfo.AllocateStack(32, 8);
2301
2302   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2303
2304   unsigned LastVal = ~0U;
2305   SDValue ArgValue;
2306   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2307     CCValAssign &VA = ArgLocs[i];
2308     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2309     // places.
2310     assert(VA.getValNo() != LastVal &&
2311            "Don't support value assigned to multiple locs yet");
2312     (void)LastVal;
2313     LastVal = VA.getValNo();
2314
2315     if (VA.isRegLoc()) {
2316       EVT RegVT = VA.getLocVT();
2317       const TargetRegisterClass *RC;
2318       if (RegVT == MVT::i32)
2319         RC = &X86::GR32RegClass;
2320       else if (Is64Bit && RegVT == MVT::i64)
2321         RC = &X86::GR64RegClass;
2322       else if (RegVT == MVT::f32)
2323         RC = &X86::FR32RegClass;
2324       else if (RegVT == MVT::f64)
2325         RC = &X86::FR64RegClass;
2326       else if (RegVT.is512BitVector())
2327         RC = &X86::VR512RegClass;
2328       else if (RegVT.is256BitVector())
2329         RC = &X86::VR256RegClass;
2330       else if (RegVT.is128BitVector())
2331         RC = &X86::VR128RegClass;
2332       else if (RegVT == MVT::x86mmx)
2333         RC = &X86::VR64RegClass;
2334       else if (RegVT == MVT::i1)
2335         RC = &X86::VK1RegClass;
2336       else if (RegVT == MVT::v8i1)
2337         RC = &X86::VK8RegClass;
2338       else if (RegVT == MVT::v16i1)
2339         RC = &X86::VK16RegClass;
2340       else if (RegVT == MVT::v32i1)
2341         RC = &X86::VK32RegClass;
2342       else if (RegVT == MVT::v64i1)
2343         RC = &X86::VK64RegClass;
2344       else
2345         llvm_unreachable("Unknown argument type!");
2346
2347       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2348       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2349
2350       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2351       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2352       // right size.
2353       if (VA.getLocInfo() == CCValAssign::SExt)
2354         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2355                                DAG.getValueType(VA.getValVT()));
2356       else if (VA.getLocInfo() == CCValAssign::ZExt)
2357         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2358                                DAG.getValueType(VA.getValVT()));
2359       else if (VA.getLocInfo() == CCValAssign::BCvt)
2360         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2361
2362       if (VA.isExtInLoc()) {
2363         // Handle MMX values passed in XMM regs.
2364         if (RegVT.isVector())
2365           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2366         else
2367           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2368       }
2369     } else {
2370       assert(VA.isMemLoc());
2371       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2372     }
2373
2374     // If value is passed via pointer - do a load.
2375     if (VA.getLocInfo() == CCValAssign::Indirect)
2376       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2377                              MachinePointerInfo(), false, false, false, 0);
2378
2379     InVals.push_back(ArgValue);
2380   }
2381
2382   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2383     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2384       // The x86-64 ABIs require that for returning structs by value we copy
2385       // the sret argument into %rax/%eax (depending on ABI) for the return.
2386       // Win32 requires us to put the sret argument to %eax as well.
2387       // Save the argument into a virtual register so that we can access it
2388       // from the return points.
2389       if (Ins[i].Flags.isSRet()) {
2390         unsigned Reg = FuncInfo->getSRetReturnReg();
2391         if (!Reg) {
2392           MVT PtrTy = getPointerTy();
2393           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2394           FuncInfo->setSRetReturnReg(Reg);
2395         }
2396         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2397         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2398         break;
2399       }
2400     }
2401   }
2402
2403   unsigned StackSize = CCInfo.getNextStackOffset();
2404   // Align stack specially for tail calls.
2405   if (FuncIsMadeTailCallSafe(CallConv,
2406                              MF.getTarget().Options.GuaranteedTailCallOpt))
2407     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2408
2409   // If the function takes variable number of arguments, make a frame index for
2410   // the start of the first vararg value... for expansion of llvm.va_start.
2411   if (isVarArg) {
2412     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2413                     CallConv != CallingConv::X86_ThisCall)) {
2414       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2415     }
2416     if (Is64Bit) {
2417       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2418
2419       // FIXME: We should really autogenerate these arrays
2420       static const MCPhysReg GPR64ArgRegsWin64[] = {
2421         X86::RCX, X86::RDX, X86::R8,  X86::R9
2422       };
2423       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2424         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2425       };
2426       static const MCPhysReg XMMArgRegs64Bit[] = {
2427         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2428         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2429       };
2430       const MCPhysReg *GPR64ArgRegs;
2431       unsigned NumXMMRegs = 0;
2432
2433       if (IsWin64) {
2434         // The XMM registers which might contain var arg parameters are shadowed
2435         // in their paired GPR.  So we only need to save the GPR to their home
2436         // slots.
2437         TotalNumIntRegs = 4;
2438         GPR64ArgRegs = GPR64ArgRegsWin64;
2439       } else {
2440         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2441         GPR64ArgRegs = GPR64ArgRegs64Bit;
2442
2443         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2444                                                 TotalNumXMMRegs);
2445       }
2446       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2447                                                        TotalNumIntRegs);
2448
2449       bool NoImplicitFloatOps = Fn->getAttributes().
2450         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2451       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2452              "SSE register cannot be used when SSE is disabled!");
2453       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2454                NoImplicitFloatOps) &&
2455              "SSE register cannot be used when SSE is disabled!");
2456       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2457           !Subtarget->hasSSE1())
2458         // Kernel mode asks for SSE to be disabled, so don't push them
2459         // on the stack.
2460         TotalNumXMMRegs = 0;
2461
2462       if (IsWin64) {
2463         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2464         // Get to the caller-allocated home save location.  Add 8 to account
2465         // for the return address.
2466         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2467         FuncInfo->setRegSaveFrameIndex(
2468           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2469         // Fixup to set vararg frame on shadow area (4 x i64).
2470         if (NumIntRegs < 4)
2471           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2472       } else {
2473         // For X86-64, if there are vararg parameters that are passed via
2474         // registers, then we must store them to their spots on the stack so
2475         // they may be loaded by deferencing the result of va_next.
2476         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2477         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2478         FuncInfo->setRegSaveFrameIndex(
2479           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2480                                false));
2481       }
2482
2483       // Store the integer parameter registers.
2484       SmallVector<SDValue, 8> MemOps;
2485       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2486                                         getPointerTy());
2487       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2488       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2489         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2490                                   DAG.getIntPtrConstant(Offset));
2491         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2492                                      &X86::GR64RegClass);
2493         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2494         SDValue Store =
2495           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2496                        MachinePointerInfo::getFixedStack(
2497                          FuncInfo->getRegSaveFrameIndex(), Offset),
2498                        false, false, 0);
2499         MemOps.push_back(Store);
2500         Offset += 8;
2501       }
2502
2503       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2504         // Now store the XMM (fp + vector) parameter registers.
2505         SmallVector<SDValue, 12> SaveXMMOps;
2506         SaveXMMOps.push_back(Chain);
2507
2508         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2509         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2510         SaveXMMOps.push_back(ALVal);
2511
2512         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2513                                FuncInfo->getRegSaveFrameIndex()));
2514         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2515                                FuncInfo->getVarArgsFPOffset()));
2516
2517         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2518           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2519                                        &X86::VR128RegClass);
2520           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2521           SaveXMMOps.push_back(Val);
2522         }
2523         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2524                                      MVT::Other, SaveXMMOps));
2525       }
2526
2527       if (!MemOps.empty())
2528         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2529     }
2530   }
2531
2532   // Some CCs need callee pop.
2533   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2534                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2535     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2536   } else {
2537     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2538     // If this is an sret function, the return should pop the hidden pointer.
2539     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2540         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2541         argsAreStructReturn(Ins) == StackStructReturn)
2542       FuncInfo->setBytesToPopOnReturn(4);
2543   }
2544
2545   if (!Is64Bit) {
2546     // RegSaveFrameIndex is X86-64 only.
2547     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2548     if (CallConv == CallingConv::X86_FastCall ||
2549         CallConv == CallingConv::X86_ThisCall)
2550       // fastcc functions can't have varargs.
2551       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2552   }
2553
2554   FuncInfo->setArgumentStackSize(StackSize);
2555
2556   return Chain;
2557 }
2558
2559 SDValue
2560 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2561                                     SDValue StackPtr, SDValue Arg,
2562                                     SDLoc dl, SelectionDAG &DAG,
2563                                     const CCValAssign &VA,
2564                                     ISD::ArgFlagsTy Flags) const {
2565   unsigned LocMemOffset = VA.getLocMemOffset();
2566   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2567   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2568   if (Flags.isByVal())
2569     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2570
2571   return DAG.getStore(Chain, dl, Arg, PtrOff,
2572                       MachinePointerInfo::getStack(LocMemOffset),
2573                       false, false, 0);
2574 }
2575
2576 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2577 /// optimization is performed and it is required.
2578 SDValue
2579 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2580                                            SDValue &OutRetAddr, SDValue Chain,
2581                                            bool IsTailCall, bool Is64Bit,
2582                                            int FPDiff, SDLoc dl) const {
2583   // Adjust the Return address stack slot.
2584   EVT VT = getPointerTy();
2585   OutRetAddr = getReturnAddressFrameIndex(DAG);
2586
2587   // Load the "old" Return address.
2588   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2589                            false, false, false, 0);
2590   return SDValue(OutRetAddr.getNode(), 1);
2591 }
2592
2593 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2594 /// optimization is performed and it is required (FPDiff!=0).
2595 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2596                                         SDValue Chain, SDValue RetAddrFrIdx,
2597                                         EVT PtrVT, unsigned SlotSize,
2598                                         int FPDiff, SDLoc dl) {
2599   // Store the return address to the appropriate stack slot.
2600   if (!FPDiff) return Chain;
2601   // Calculate the new stack slot for the return address.
2602   int NewReturnAddrFI =
2603     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2604                                          false);
2605   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2606   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2607                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2608                        false, false, 0);
2609   return Chain;
2610 }
2611
2612 SDValue
2613 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2614                              SmallVectorImpl<SDValue> &InVals) const {
2615   SelectionDAG &DAG                     = CLI.DAG;
2616   SDLoc &dl                             = CLI.DL;
2617   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2618   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2619   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2620   SDValue Chain                         = CLI.Chain;
2621   SDValue Callee                        = CLI.Callee;
2622   CallingConv::ID CallConv              = CLI.CallConv;
2623   bool &isTailCall                      = CLI.IsTailCall;
2624   bool isVarArg                         = CLI.IsVarArg;
2625
2626   MachineFunction &MF = DAG.getMachineFunction();
2627   bool Is64Bit        = Subtarget->is64Bit();
2628   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2629   StructReturnType SR = callIsStructReturn(Outs);
2630   bool IsSibcall      = false;
2631
2632   if (MF.getTarget().Options.DisableTailCalls)
2633     isTailCall = false;
2634
2635   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2636   if (IsMustTail) {
2637     // Force this to be a tail call.  The verifier rules are enough to ensure
2638     // that we can lower this successfully without moving the return address
2639     // around.
2640     isTailCall = true;
2641   } else if (isTailCall) {
2642     // Check if it's really possible to do a tail call.
2643     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2644                     isVarArg, SR != NotStructReturn,
2645                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2646                     Outs, OutVals, Ins, DAG);
2647
2648     // Sibcalls are automatically detected tailcalls which do not require
2649     // ABI changes.
2650     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2651       IsSibcall = true;
2652
2653     if (isTailCall)
2654       ++NumTailCalls;
2655   }
2656
2657   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2658          "Var args not supported with calling convention fastcc, ghc or hipe");
2659
2660   // Analyze operands of the call, assigning locations to each operand.
2661   SmallVector<CCValAssign, 16> ArgLocs;
2662   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2663
2664   // Allocate shadow area for Win64
2665   if (IsWin64)
2666     CCInfo.AllocateStack(32, 8);
2667
2668   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2669
2670   // Get a count of how many bytes are to be pushed on the stack.
2671   unsigned NumBytes = CCInfo.getNextStackOffset();
2672   if (IsSibcall)
2673     // This is a sibcall. The memory operands are available in caller's
2674     // own caller's stack.
2675     NumBytes = 0;
2676   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2677            IsTailCallConvention(CallConv))
2678     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2679
2680   int FPDiff = 0;
2681   if (isTailCall && !IsSibcall && !IsMustTail) {
2682     // Lower arguments at fp - stackoffset + fpdiff.
2683     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2684     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2685
2686     FPDiff = NumBytesCallerPushed - NumBytes;
2687
2688     // Set the delta of movement of the returnaddr stackslot.
2689     // But only set if delta is greater than previous delta.
2690     if (FPDiff < X86Info->getTCReturnAddrDelta())
2691       X86Info->setTCReturnAddrDelta(FPDiff);
2692   }
2693
2694   unsigned NumBytesToPush = NumBytes;
2695   unsigned NumBytesToPop = NumBytes;
2696
2697   // If we have an inalloca argument, all stack space has already been allocated
2698   // for us and be right at the top of the stack.  We don't support multiple
2699   // arguments passed in memory when using inalloca.
2700   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2701     NumBytesToPush = 0;
2702     if (!ArgLocs.back().isMemLoc())
2703       report_fatal_error("cannot use inalloca attribute on a register "
2704                          "parameter");
2705     if (ArgLocs.back().getLocMemOffset() != 0)
2706       report_fatal_error("any parameter with the inalloca attribute must be "
2707                          "the only memory argument");
2708   }
2709
2710   if (!IsSibcall)
2711     Chain = DAG.getCALLSEQ_START(
2712         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2713
2714   SDValue RetAddrFrIdx;
2715   // Load return address for tail calls.
2716   if (isTailCall && FPDiff)
2717     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2718                                     Is64Bit, FPDiff, dl);
2719
2720   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2721   SmallVector<SDValue, 8> MemOpChains;
2722   SDValue StackPtr;
2723
2724   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2725   // of tail call optimization arguments are handle later.
2726   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2727       DAG.getSubtarget().getRegisterInfo());
2728   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2729     // Skip inalloca arguments, they have already been written.
2730     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2731     if (Flags.isInAlloca())
2732       continue;
2733
2734     CCValAssign &VA = ArgLocs[i];
2735     EVT RegVT = VA.getLocVT();
2736     SDValue Arg = OutVals[i];
2737     bool isByVal = Flags.isByVal();
2738
2739     // Promote the value if needed.
2740     switch (VA.getLocInfo()) {
2741     default: llvm_unreachable("Unknown loc info!");
2742     case CCValAssign::Full: break;
2743     case CCValAssign::SExt:
2744       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2745       break;
2746     case CCValAssign::ZExt:
2747       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2748       break;
2749     case CCValAssign::AExt:
2750       if (RegVT.is128BitVector()) {
2751         // Special case: passing MMX values in XMM registers.
2752         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2753         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2754         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2755       } else
2756         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2757       break;
2758     case CCValAssign::BCvt:
2759       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2760       break;
2761     case CCValAssign::Indirect: {
2762       // Store the argument.
2763       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2764       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2765       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2766                            MachinePointerInfo::getFixedStack(FI),
2767                            false, false, 0);
2768       Arg = SpillSlot;
2769       break;
2770     }
2771     }
2772
2773     if (VA.isRegLoc()) {
2774       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2775       if (isVarArg && IsWin64) {
2776         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2777         // shadow reg if callee is a varargs function.
2778         unsigned ShadowReg = 0;
2779         switch (VA.getLocReg()) {
2780         case X86::XMM0: ShadowReg = X86::RCX; break;
2781         case X86::XMM1: ShadowReg = X86::RDX; break;
2782         case X86::XMM2: ShadowReg = X86::R8; break;
2783         case X86::XMM3: ShadowReg = X86::R9; break;
2784         }
2785         if (ShadowReg)
2786           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2787       }
2788     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2789       assert(VA.isMemLoc());
2790       if (!StackPtr.getNode())
2791         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2792                                       getPointerTy());
2793       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2794                                              dl, DAG, VA, Flags));
2795     }
2796   }
2797
2798   if (!MemOpChains.empty())
2799     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2800
2801   if (Subtarget->isPICStyleGOT()) {
2802     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2803     // GOT pointer.
2804     if (!isTailCall) {
2805       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2806                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2807     } else {
2808       // If we are tail calling and generating PIC/GOT style code load the
2809       // address of the callee into ECX. The value in ecx is used as target of
2810       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2811       // for tail calls on PIC/GOT architectures. Normally we would just put the
2812       // address of GOT into ebx and then call target@PLT. But for tail calls
2813       // ebx would be restored (since ebx is callee saved) before jumping to the
2814       // target@PLT.
2815
2816       // Note: The actual moving to ECX is done further down.
2817       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2818       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2819           !G->getGlobal()->hasProtectedVisibility())
2820         Callee = LowerGlobalAddress(Callee, DAG);
2821       else if (isa<ExternalSymbolSDNode>(Callee))
2822         Callee = LowerExternalSymbol(Callee, DAG);
2823     }
2824   }
2825
2826   if (Is64Bit && isVarArg && !IsWin64) {
2827     // From AMD64 ABI document:
2828     // For calls that may call functions that use varargs or stdargs
2829     // (prototype-less calls or calls to functions containing ellipsis (...) in
2830     // the declaration) %al is used as hidden argument to specify the number
2831     // of SSE registers used. The contents of %al do not need to match exactly
2832     // the number of registers, but must be an ubound on the number of SSE
2833     // registers used and is in the range 0 - 8 inclusive.
2834
2835     // Count the number of XMM registers allocated.
2836     static const MCPhysReg XMMArgRegs[] = {
2837       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2838       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2839     };
2840     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2841     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2842            && "SSE registers cannot be used when SSE is disabled");
2843
2844     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2845                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2846   }
2847
2848   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2849   // don't need this because the eligibility check rejects calls that require
2850   // shuffling arguments passed in memory.
2851   if (!IsSibcall && isTailCall) {
2852     // Force all the incoming stack arguments to be loaded from the stack
2853     // before any new outgoing arguments are stored to the stack, because the
2854     // outgoing stack slots may alias the incoming argument stack slots, and
2855     // the alias isn't otherwise explicit. This is slightly more conservative
2856     // than necessary, because it means that each store effectively depends
2857     // on every argument instead of just those arguments it would clobber.
2858     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2859
2860     SmallVector<SDValue, 8> MemOpChains2;
2861     SDValue FIN;
2862     int FI = 0;
2863     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2864       CCValAssign &VA = ArgLocs[i];
2865       if (VA.isRegLoc())
2866         continue;
2867       assert(VA.isMemLoc());
2868       SDValue Arg = OutVals[i];
2869       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2870       // Skip inalloca arguments.  They don't require any work.
2871       if (Flags.isInAlloca())
2872         continue;
2873       // Create frame index.
2874       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2875       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2876       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2877       FIN = DAG.getFrameIndex(FI, getPointerTy());
2878
2879       if (Flags.isByVal()) {
2880         // Copy relative to framepointer.
2881         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2882         if (!StackPtr.getNode())
2883           StackPtr = DAG.getCopyFromReg(Chain, dl,
2884                                         RegInfo->getStackRegister(),
2885                                         getPointerTy());
2886         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2887
2888         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2889                                                          ArgChain,
2890                                                          Flags, DAG, dl));
2891       } else {
2892         // Store relative to framepointer.
2893         MemOpChains2.push_back(
2894           DAG.getStore(ArgChain, dl, Arg, FIN,
2895                        MachinePointerInfo::getFixedStack(FI),
2896                        false, false, 0));
2897       }
2898     }
2899
2900     if (!MemOpChains2.empty())
2901       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2902
2903     // Store the return address to the appropriate stack slot.
2904     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2905                                      getPointerTy(), RegInfo->getSlotSize(),
2906                                      FPDiff, dl);
2907   }
2908
2909   // Build a sequence of copy-to-reg nodes chained together with token chain
2910   // and flag operands which copy the outgoing args into registers.
2911   SDValue InFlag;
2912   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2913     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2914                              RegsToPass[i].second, InFlag);
2915     InFlag = Chain.getValue(1);
2916   }
2917
2918   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2919     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2920     // In the 64-bit large code model, we have to make all calls
2921     // through a register, since the call instruction's 32-bit
2922     // pc-relative offset may not be large enough to hold the whole
2923     // address.
2924   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2925     // If the callee is a GlobalAddress node (quite common, every direct call
2926     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2927     // it.
2928
2929     // We should use extra load for direct calls to dllimported functions in
2930     // non-JIT mode.
2931     const GlobalValue *GV = G->getGlobal();
2932     if (!GV->hasDLLImportStorageClass()) {
2933       unsigned char OpFlags = 0;
2934       bool ExtraLoad = false;
2935       unsigned WrapperKind = ISD::DELETED_NODE;
2936
2937       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2938       // external symbols most go through the PLT in PIC mode.  If the symbol
2939       // has hidden or protected visibility, or if it is static or local, then
2940       // we don't need to use the PLT - we can directly call it.
2941       if (Subtarget->isTargetELF() &&
2942           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2943           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2944         OpFlags = X86II::MO_PLT;
2945       } else if (Subtarget->isPICStyleStubAny() &&
2946                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2947                  (!Subtarget->getTargetTriple().isMacOSX() ||
2948                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2949         // PC-relative references to external symbols should go through $stub,
2950         // unless we're building with the leopard linker or later, which
2951         // automatically synthesizes these stubs.
2952         OpFlags = X86II::MO_DARWIN_STUB;
2953       } else if (Subtarget->isPICStyleRIPRel() &&
2954                  isa<Function>(GV) &&
2955                  cast<Function>(GV)->getAttributes().
2956                    hasAttribute(AttributeSet::FunctionIndex,
2957                                 Attribute::NonLazyBind)) {
2958         // If the function is marked as non-lazy, generate an indirect call
2959         // which loads from the GOT directly. This avoids runtime overhead
2960         // at the cost of eager binding (and one extra byte of encoding).
2961         OpFlags = X86II::MO_GOTPCREL;
2962         WrapperKind = X86ISD::WrapperRIP;
2963         ExtraLoad = true;
2964       }
2965
2966       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2967                                           G->getOffset(), OpFlags);
2968
2969       // Add a wrapper if needed.
2970       if (WrapperKind != ISD::DELETED_NODE)
2971         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2972       // Add extra indirection if needed.
2973       if (ExtraLoad)
2974         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2975                              MachinePointerInfo::getGOT(),
2976                              false, false, false, 0);
2977     }
2978   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2979     unsigned char OpFlags = 0;
2980
2981     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2982     // external symbols should go through the PLT.
2983     if (Subtarget->isTargetELF() &&
2984         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2985       OpFlags = X86II::MO_PLT;
2986     } else if (Subtarget->isPICStyleStubAny() &&
2987                (!Subtarget->getTargetTriple().isMacOSX() ||
2988                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2989       // PC-relative references to external symbols should go through $stub,
2990       // unless we're building with the leopard linker or later, which
2991       // automatically synthesizes these stubs.
2992       OpFlags = X86II::MO_DARWIN_STUB;
2993     }
2994
2995     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2996                                          OpFlags);
2997   }
2998
2999   // Returns a chain & a flag for retval copy to use.
3000   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3001   SmallVector<SDValue, 8> Ops;
3002
3003   if (!IsSibcall && isTailCall) {
3004     Chain = DAG.getCALLSEQ_END(Chain,
3005                                DAG.getIntPtrConstant(NumBytesToPop, true),
3006                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3007     InFlag = Chain.getValue(1);
3008   }
3009
3010   Ops.push_back(Chain);
3011   Ops.push_back(Callee);
3012
3013   if (isTailCall)
3014     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3015
3016   // Add argument registers to the end of the list so that they are known live
3017   // into the call.
3018   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3019     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3020                                   RegsToPass[i].second.getValueType()));
3021
3022   // Add a register mask operand representing the call-preserved registers.
3023   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3024   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3025   assert(Mask && "Missing call preserved mask for calling convention");
3026   Ops.push_back(DAG.getRegisterMask(Mask));
3027
3028   if (InFlag.getNode())
3029     Ops.push_back(InFlag);
3030
3031   if (isTailCall) {
3032     // We used to do:
3033     //// If this is the first return lowered for this function, add the regs
3034     //// to the liveout set for the function.
3035     // This isn't right, although it's probably harmless on x86; liveouts
3036     // should be computed from returns not tail calls.  Consider a void
3037     // function making a tail call to a function returning int.
3038     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3039   }
3040
3041   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3042   InFlag = Chain.getValue(1);
3043
3044   // Create the CALLSEQ_END node.
3045   unsigned NumBytesForCalleeToPop;
3046   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3047                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3048     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3049   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3050            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3051            SR == StackStructReturn)
3052     // If this is a call to a struct-return function, the callee
3053     // pops the hidden struct pointer, so we have to push it back.
3054     // This is common for Darwin/X86, Linux & Mingw32 targets.
3055     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3056     NumBytesForCalleeToPop = 4;
3057   else
3058     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3059
3060   // Returns a flag for retval copy to use.
3061   if (!IsSibcall) {
3062     Chain = DAG.getCALLSEQ_END(Chain,
3063                                DAG.getIntPtrConstant(NumBytesToPop, true),
3064                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3065                                                      true),
3066                                InFlag, dl);
3067     InFlag = Chain.getValue(1);
3068   }
3069
3070   // Handle result values, copying them out of physregs into vregs that we
3071   // return.
3072   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3073                          Ins, dl, DAG, InVals);
3074 }
3075
3076 //===----------------------------------------------------------------------===//
3077 //                Fast Calling Convention (tail call) implementation
3078 //===----------------------------------------------------------------------===//
3079
3080 //  Like std call, callee cleans arguments, convention except that ECX is
3081 //  reserved for storing the tail called function address. Only 2 registers are
3082 //  free for argument passing (inreg). Tail call optimization is performed
3083 //  provided:
3084 //                * tailcallopt is enabled
3085 //                * caller/callee are fastcc
3086 //  On X86_64 architecture with GOT-style position independent code only local
3087 //  (within module) calls are supported at the moment.
3088 //  To keep the stack aligned according to platform abi the function
3089 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3090 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3091 //  If a tail called function callee has more arguments than the caller the
3092 //  caller needs to make sure that there is room to move the RETADDR to. This is
3093 //  achieved by reserving an area the size of the argument delta right after the
3094 //  original RETADDR, but before the saved framepointer or the spilled registers
3095 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3096 //  stack layout:
3097 //    arg1
3098 //    arg2
3099 //    RETADDR
3100 //    [ new RETADDR
3101 //      move area ]
3102 //    (possible EBP)
3103 //    ESI
3104 //    EDI
3105 //    local1 ..
3106
3107 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3108 /// for a 16 byte align requirement.
3109 unsigned
3110 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3111                                                SelectionDAG& DAG) const {
3112   MachineFunction &MF = DAG.getMachineFunction();
3113   const TargetMachine &TM = MF.getTarget();
3114   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3115       TM.getSubtargetImpl()->getRegisterInfo());
3116   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3117   unsigned StackAlignment = TFI.getStackAlignment();
3118   uint64_t AlignMask = StackAlignment - 1;
3119   int64_t Offset = StackSize;
3120   unsigned SlotSize = RegInfo->getSlotSize();
3121   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3122     // Number smaller than 12 so just add the difference.
3123     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3124   } else {
3125     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3126     Offset = ((~AlignMask) & Offset) + StackAlignment +
3127       (StackAlignment-SlotSize);
3128   }
3129   return Offset;
3130 }
3131
3132 /// MatchingStackOffset - Return true if the given stack call argument is
3133 /// already available in the same position (relatively) of the caller's
3134 /// incoming argument stack.
3135 static
3136 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3137                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3138                          const X86InstrInfo *TII) {
3139   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3140   int FI = INT_MAX;
3141   if (Arg.getOpcode() == ISD::CopyFromReg) {
3142     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3143     if (!TargetRegisterInfo::isVirtualRegister(VR))
3144       return false;
3145     MachineInstr *Def = MRI->getVRegDef(VR);
3146     if (!Def)
3147       return false;
3148     if (!Flags.isByVal()) {
3149       if (!TII->isLoadFromStackSlot(Def, FI))
3150         return false;
3151     } else {
3152       unsigned Opcode = Def->getOpcode();
3153       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3154           Def->getOperand(1).isFI()) {
3155         FI = Def->getOperand(1).getIndex();
3156         Bytes = Flags.getByValSize();
3157       } else
3158         return false;
3159     }
3160   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3161     if (Flags.isByVal())
3162       // ByVal argument is passed in as a pointer but it's now being
3163       // dereferenced. e.g.
3164       // define @foo(%struct.X* %A) {
3165       //   tail call @bar(%struct.X* byval %A)
3166       // }
3167       return false;
3168     SDValue Ptr = Ld->getBasePtr();
3169     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3170     if (!FINode)
3171       return false;
3172     FI = FINode->getIndex();
3173   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3174     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3175     FI = FINode->getIndex();
3176     Bytes = Flags.getByValSize();
3177   } else
3178     return false;
3179
3180   assert(FI != INT_MAX);
3181   if (!MFI->isFixedObjectIndex(FI))
3182     return false;
3183   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3184 }
3185
3186 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3187 /// for tail call optimization. Targets which want to do tail call
3188 /// optimization should implement this function.
3189 bool
3190 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3191                                                      CallingConv::ID CalleeCC,
3192                                                      bool isVarArg,
3193                                                      bool isCalleeStructRet,
3194                                                      bool isCallerStructRet,
3195                                                      Type *RetTy,
3196                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3197                                     const SmallVectorImpl<SDValue> &OutVals,
3198                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3199                                                      SelectionDAG &DAG) const {
3200   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3201     return false;
3202
3203   // If -tailcallopt is specified, make fastcc functions tail-callable.
3204   const MachineFunction &MF = DAG.getMachineFunction();
3205   const Function *CallerF = MF.getFunction();
3206
3207   // If the function return type is x86_fp80 and the callee return type is not,
3208   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3209   // perform a tailcall optimization here.
3210   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3211     return false;
3212
3213   CallingConv::ID CallerCC = CallerF->getCallingConv();
3214   bool CCMatch = CallerCC == CalleeCC;
3215   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3216   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3217
3218   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3219     if (IsTailCallConvention(CalleeCC) && CCMatch)
3220       return true;
3221     return false;
3222   }
3223
3224   // Look for obvious safe cases to perform tail call optimization that do not
3225   // require ABI changes. This is what gcc calls sibcall.
3226
3227   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3228   // emit a special epilogue.
3229   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3230       DAG.getSubtarget().getRegisterInfo());
3231   if (RegInfo->needsStackRealignment(MF))
3232     return false;
3233
3234   // Also avoid sibcall optimization if either caller or callee uses struct
3235   // return semantics.
3236   if (isCalleeStructRet || isCallerStructRet)
3237     return false;
3238
3239   // An stdcall/thiscall caller is expected to clean up its arguments; the
3240   // callee isn't going to do that.
3241   // FIXME: this is more restrictive than needed. We could produce a tailcall
3242   // when the stack adjustment matches. For example, with a thiscall that takes
3243   // only one argument.
3244   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3245                    CallerCC == CallingConv::X86_ThisCall))
3246     return false;
3247
3248   // Do not sibcall optimize vararg calls unless all arguments are passed via
3249   // registers.
3250   if (isVarArg && !Outs.empty()) {
3251
3252     // Optimizing for varargs on Win64 is unlikely to be safe without
3253     // additional testing.
3254     if (IsCalleeWin64 || IsCallerWin64)
3255       return false;
3256
3257     SmallVector<CCValAssign, 16> ArgLocs;
3258     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3259                    *DAG.getContext());
3260
3261     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3262     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3263       if (!ArgLocs[i].isRegLoc())
3264         return false;
3265   }
3266
3267   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3268   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3269   // this into a sibcall.
3270   bool Unused = false;
3271   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3272     if (!Ins[i].Used) {
3273       Unused = true;
3274       break;
3275     }
3276   }
3277   if (Unused) {
3278     SmallVector<CCValAssign, 16> RVLocs;
3279     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3280                    *DAG.getContext());
3281     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3282     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3283       CCValAssign &VA = RVLocs[i];
3284       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3285         return false;
3286     }
3287   }
3288
3289   // If the calling conventions do not match, then we'd better make sure the
3290   // results are returned in the same way as what the caller expects.
3291   if (!CCMatch) {
3292     SmallVector<CCValAssign, 16> RVLocs1;
3293     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3294                     *DAG.getContext());
3295     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3296
3297     SmallVector<CCValAssign, 16> RVLocs2;
3298     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3299                     *DAG.getContext());
3300     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3301
3302     if (RVLocs1.size() != RVLocs2.size())
3303       return false;
3304     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3305       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3306         return false;
3307       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3308         return false;
3309       if (RVLocs1[i].isRegLoc()) {
3310         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3311           return false;
3312       } else {
3313         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3314           return false;
3315       }
3316     }
3317   }
3318
3319   // If the callee takes no arguments then go on to check the results of the
3320   // call.
3321   if (!Outs.empty()) {
3322     // Check if stack adjustment is needed. For now, do not do this if any
3323     // argument is passed on the stack.
3324     SmallVector<CCValAssign, 16> ArgLocs;
3325     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3326                    *DAG.getContext());
3327
3328     // Allocate shadow area for Win64
3329     if (IsCalleeWin64)
3330       CCInfo.AllocateStack(32, 8);
3331
3332     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3333     if (CCInfo.getNextStackOffset()) {
3334       MachineFunction &MF = DAG.getMachineFunction();
3335       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3336         return false;
3337
3338       // Check if the arguments are already laid out in the right way as
3339       // the caller's fixed stack objects.
3340       MachineFrameInfo *MFI = MF.getFrameInfo();
3341       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3342       const X86InstrInfo *TII =
3343           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3344       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3345         CCValAssign &VA = ArgLocs[i];
3346         SDValue Arg = OutVals[i];
3347         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3348         if (VA.getLocInfo() == CCValAssign::Indirect)
3349           return false;
3350         if (!VA.isRegLoc()) {
3351           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3352                                    MFI, MRI, TII))
3353             return false;
3354         }
3355       }
3356     }
3357
3358     // If the tailcall address may be in a register, then make sure it's
3359     // possible to register allocate for it. In 32-bit, the call address can
3360     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3361     // callee-saved registers are restored. These happen to be the same
3362     // registers used to pass 'inreg' arguments so watch out for those.
3363     if (!Subtarget->is64Bit() &&
3364         ((!isa<GlobalAddressSDNode>(Callee) &&
3365           !isa<ExternalSymbolSDNode>(Callee)) ||
3366          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3367       unsigned NumInRegs = 0;
3368       // In PIC we need an extra register to formulate the address computation
3369       // for the callee.
3370       unsigned MaxInRegs =
3371         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3372
3373       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3374         CCValAssign &VA = ArgLocs[i];
3375         if (!VA.isRegLoc())
3376           continue;
3377         unsigned Reg = VA.getLocReg();
3378         switch (Reg) {
3379         default: break;
3380         case X86::EAX: case X86::EDX: case X86::ECX:
3381           if (++NumInRegs == MaxInRegs)
3382             return false;
3383           break;
3384         }
3385       }
3386     }
3387   }
3388
3389   return true;
3390 }
3391
3392 FastISel *
3393 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3394                                   const TargetLibraryInfo *libInfo) const {
3395   return X86::createFastISel(funcInfo, libInfo);
3396 }
3397
3398 //===----------------------------------------------------------------------===//
3399 //                           Other Lowering Hooks
3400 //===----------------------------------------------------------------------===//
3401
3402 static bool MayFoldLoad(SDValue Op) {
3403   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3404 }
3405
3406 static bool MayFoldIntoStore(SDValue Op) {
3407   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3408 }
3409
3410 static bool isTargetShuffle(unsigned Opcode) {
3411   switch(Opcode) {
3412   default: return false;
3413   case X86ISD::PSHUFB:
3414   case X86ISD::PSHUFD:
3415   case X86ISD::PSHUFHW:
3416   case X86ISD::PSHUFLW:
3417   case X86ISD::SHUFP:
3418   case X86ISD::PALIGNR:
3419   case X86ISD::MOVLHPS:
3420   case X86ISD::MOVLHPD:
3421   case X86ISD::MOVHLPS:
3422   case X86ISD::MOVLPS:
3423   case X86ISD::MOVLPD:
3424   case X86ISD::MOVSHDUP:
3425   case X86ISD::MOVSLDUP:
3426   case X86ISD::MOVDDUP:
3427   case X86ISD::MOVSS:
3428   case X86ISD::MOVSD:
3429   case X86ISD::UNPCKL:
3430   case X86ISD::UNPCKH:
3431   case X86ISD::VPERMILP:
3432   case X86ISD::VPERM2X128:
3433   case X86ISD::VPERMI:
3434     return true;
3435   }
3436 }
3437
3438 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3439                                     SDValue V1, SelectionDAG &DAG) {
3440   switch(Opc) {
3441   default: llvm_unreachable("Unknown x86 shuffle node");
3442   case X86ISD::MOVSHDUP:
3443   case X86ISD::MOVSLDUP:
3444   case X86ISD::MOVDDUP:
3445     return DAG.getNode(Opc, dl, VT, V1);
3446   }
3447 }
3448
3449 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3450                                     SDValue V1, unsigned TargetMask,
3451                                     SelectionDAG &DAG) {
3452   switch(Opc) {
3453   default: llvm_unreachable("Unknown x86 shuffle node");
3454   case X86ISD::PSHUFD:
3455   case X86ISD::PSHUFHW:
3456   case X86ISD::PSHUFLW:
3457   case X86ISD::VPERMILP:
3458   case X86ISD::VPERMI:
3459     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3460   }
3461 }
3462
3463 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3464                                     SDValue V1, SDValue V2, unsigned TargetMask,
3465                                     SelectionDAG &DAG) {
3466   switch(Opc) {
3467   default: llvm_unreachable("Unknown x86 shuffle node");
3468   case X86ISD::PALIGNR:
3469   case X86ISD::VALIGN:
3470   case X86ISD::SHUFP:
3471   case X86ISD::VPERM2X128:
3472     return DAG.getNode(Opc, dl, VT, V1, V2,
3473                        DAG.getConstant(TargetMask, MVT::i8));
3474   }
3475 }
3476
3477 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3478                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3479   switch(Opc) {
3480   default: llvm_unreachable("Unknown x86 shuffle node");
3481   case X86ISD::MOVLHPS:
3482   case X86ISD::MOVLHPD:
3483   case X86ISD::MOVHLPS:
3484   case X86ISD::MOVLPS:
3485   case X86ISD::MOVLPD:
3486   case X86ISD::MOVSS:
3487   case X86ISD::MOVSD:
3488   case X86ISD::UNPCKL:
3489   case X86ISD::UNPCKH:
3490     return DAG.getNode(Opc, dl, VT, V1, V2);
3491   }
3492 }
3493
3494 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3495   MachineFunction &MF = DAG.getMachineFunction();
3496   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3497       DAG.getSubtarget().getRegisterInfo());
3498   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3499   int ReturnAddrIndex = FuncInfo->getRAIndex();
3500
3501   if (ReturnAddrIndex == 0) {
3502     // Set up a frame object for the return address.
3503     unsigned SlotSize = RegInfo->getSlotSize();
3504     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3505                                                            -(int64_t)SlotSize,
3506                                                            false);
3507     FuncInfo->setRAIndex(ReturnAddrIndex);
3508   }
3509
3510   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3511 }
3512
3513 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3514                                        bool hasSymbolicDisplacement) {
3515   // Offset should fit into 32 bit immediate field.
3516   if (!isInt<32>(Offset))
3517     return false;
3518
3519   // If we don't have a symbolic displacement - we don't have any extra
3520   // restrictions.
3521   if (!hasSymbolicDisplacement)
3522     return true;
3523
3524   // FIXME: Some tweaks might be needed for medium code model.
3525   if (M != CodeModel::Small && M != CodeModel::Kernel)
3526     return false;
3527
3528   // For small code model we assume that latest object is 16MB before end of 31
3529   // bits boundary. We may also accept pretty large negative constants knowing
3530   // that all objects are in the positive half of address space.
3531   if (M == CodeModel::Small && Offset < 16*1024*1024)
3532     return true;
3533
3534   // For kernel code model we know that all object resist in the negative half
3535   // of 32bits address space. We may not accept negative offsets, since they may
3536   // be just off and we may accept pretty large positive ones.
3537   if (M == CodeModel::Kernel && Offset > 0)
3538     return true;
3539
3540   return false;
3541 }
3542
3543 /// isCalleePop - Determines whether the callee is required to pop its
3544 /// own arguments. Callee pop is necessary to support tail calls.
3545 bool X86::isCalleePop(CallingConv::ID CallingConv,
3546                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3547   if (IsVarArg)
3548     return false;
3549
3550   switch (CallingConv) {
3551   default:
3552     return false;
3553   case CallingConv::X86_StdCall:
3554     return !is64Bit;
3555   case CallingConv::X86_FastCall:
3556     return !is64Bit;
3557   case CallingConv::X86_ThisCall:
3558     return !is64Bit;
3559   case CallingConv::Fast:
3560     return TailCallOpt;
3561   case CallingConv::GHC:
3562     return TailCallOpt;
3563   case CallingConv::HiPE:
3564     return TailCallOpt;
3565   }
3566 }
3567
3568 /// \brief Return true if the condition is an unsigned comparison operation.
3569 static bool isX86CCUnsigned(unsigned X86CC) {
3570   switch (X86CC) {
3571   default: llvm_unreachable("Invalid integer condition!");
3572   case X86::COND_E:     return true;
3573   case X86::COND_G:     return false;
3574   case X86::COND_GE:    return false;
3575   case X86::COND_L:     return false;
3576   case X86::COND_LE:    return false;
3577   case X86::COND_NE:    return true;
3578   case X86::COND_B:     return true;
3579   case X86::COND_A:     return true;
3580   case X86::COND_BE:    return true;
3581   case X86::COND_AE:    return true;
3582   }
3583   llvm_unreachable("covered switch fell through?!");
3584 }
3585
3586 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3587 /// specific condition code, returning the condition code and the LHS/RHS of the
3588 /// comparison to make.
3589 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3590                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3591   if (!isFP) {
3592     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3593       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3594         // X > -1   -> X == 0, jump !sign.
3595         RHS = DAG.getConstant(0, RHS.getValueType());
3596         return X86::COND_NS;
3597       }
3598       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3599         // X < 0   -> X == 0, jump on sign.
3600         return X86::COND_S;
3601       }
3602       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3603         // X < 1   -> X <= 0
3604         RHS = DAG.getConstant(0, RHS.getValueType());
3605         return X86::COND_LE;
3606       }
3607     }
3608
3609     switch (SetCCOpcode) {
3610     default: llvm_unreachable("Invalid integer condition!");
3611     case ISD::SETEQ:  return X86::COND_E;
3612     case ISD::SETGT:  return X86::COND_G;
3613     case ISD::SETGE:  return X86::COND_GE;
3614     case ISD::SETLT:  return X86::COND_L;
3615     case ISD::SETLE:  return X86::COND_LE;
3616     case ISD::SETNE:  return X86::COND_NE;
3617     case ISD::SETULT: return X86::COND_B;
3618     case ISD::SETUGT: return X86::COND_A;
3619     case ISD::SETULE: return X86::COND_BE;
3620     case ISD::SETUGE: return X86::COND_AE;
3621     }
3622   }
3623
3624   // First determine if it is required or is profitable to flip the operands.
3625
3626   // If LHS is a foldable load, but RHS is not, flip the condition.
3627   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3628       !ISD::isNON_EXTLoad(RHS.getNode())) {
3629     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3630     std::swap(LHS, RHS);
3631   }
3632
3633   switch (SetCCOpcode) {
3634   default: break;
3635   case ISD::SETOLT:
3636   case ISD::SETOLE:
3637   case ISD::SETUGT:
3638   case ISD::SETUGE:
3639     std::swap(LHS, RHS);
3640     break;
3641   }
3642
3643   // On a floating point condition, the flags are set as follows:
3644   // ZF  PF  CF   op
3645   //  0 | 0 | 0 | X > Y
3646   //  0 | 0 | 1 | X < Y
3647   //  1 | 0 | 0 | X == Y
3648   //  1 | 1 | 1 | unordered
3649   switch (SetCCOpcode) {
3650   default: llvm_unreachable("Condcode should be pre-legalized away");
3651   case ISD::SETUEQ:
3652   case ISD::SETEQ:   return X86::COND_E;
3653   case ISD::SETOLT:              // flipped
3654   case ISD::SETOGT:
3655   case ISD::SETGT:   return X86::COND_A;
3656   case ISD::SETOLE:              // flipped
3657   case ISD::SETOGE:
3658   case ISD::SETGE:   return X86::COND_AE;
3659   case ISD::SETUGT:              // flipped
3660   case ISD::SETULT:
3661   case ISD::SETLT:   return X86::COND_B;
3662   case ISD::SETUGE:              // flipped
3663   case ISD::SETULE:
3664   case ISD::SETLE:   return X86::COND_BE;
3665   case ISD::SETONE:
3666   case ISD::SETNE:   return X86::COND_NE;
3667   case ISD::SETUO:   return X86::COND_P;
3668   case ISD::SETO:    return X86::COND_NP;
3669   case ISD::SETOEQ:
3670   case ISD::SETUNE:  return X86::COND_INVALID;
3671   }
3672 }
3673
3674 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3675 /// code. Current x86 isa includes the following FP cmov instructions:
3676 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3677 static bool hasFPCMov(unsigned X86CC) {
3678   switch (X86CC) {
3679   default:
3680     return false;
3681   case X86::COND_B:
3682   case X86::COND_BE:
3683   case X86::COND_E:
3684   case X86::COND_P:
3685   case X86::COND_A:
3686   case X86::COND_AE:
3687   case X86::COND_NE:
3688   case X86::COND_NP:
3689     return true;
3690   }
3691 }
3692
3693 /// isFPImmLegal - Returns true if the target can instruction select the
3694 /// specified FP immediate natively. If false, the legalizer will
3695 /// materialize the FP immediate as a load from a constant pool.
3696 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3697   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3698     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3699       return true;
3700   }
3701   return false;
3702 }
3703
3704 /// \brief Returns true if it is beneficial to convert a load of a constant
3705 /// to just the constant itself.
3706 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3707                                                           Type *Ty) const {
3708   assert(Ty->isIntegerTy());
3709
3710   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3711   if (BitSize == 0 || BitSize > 64)
3712     return false;
3713   return true;
3714 }
3715
3716 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3717 /// the specified range (L, H].
3718 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3719   return (Val < 0) || (Val >= Low && Val < Hi);
3720 }
3721
3722 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3723 /// specified value.
3724 static bool isUndefOrEqual(int Val, int CmpVal) {
3725   return (Val < 0 || Val == CmpVal);
3726 }
3727
3728 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3729 /// from position Pos and ending in Pos+Size, falls within the specified
3730 /// sequential range (L, L+Pos]. or is undef.
3731 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3732                                        unsigned Pos, unsigned Size, int Low) {
3733   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3734     if (!isUndefOrEqual(Mask[i], Low))
3735       return false;
3736   return true;
3737 }
3738
3739 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3740 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3741 /// the second operand.
3742 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3743   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3744     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3745   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3746     return (Mask[0] < 2 && Mask[1] < 2);
3747   return false;
3748 }
3749
3750 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3751 /// is suitable for input to PSHUFHW.
3752 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3753   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3754     return false;
3755
3756   // Lower quadword copied in order or undef.
3757   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3758     return false;
3759
3760   // Upper quadword shuffled.
3761   for (unsigned i = 4; i != 8; ++i)
3762     if (!isUndefOrInRange(Mask[i], 4, 8))
3763       return false;
3764
3765   if (VT == MVT::v16i16) {
3766     // Lower quadword copied in order or undef.
3767     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3768       return false;
3769
3770     // Upper quadword shuffled.
3771     for (unsigned i = 12; i != 16; ++i)
3772       if (!isUndefOrInRange(Mask[i], 12, 16))
3773         return false;
3774   }
3775
3776   return true;
3777 }
3778
3779 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3780 /// is suitable for input to PSHUFLW.
3781 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3782   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3783     return false;
3784
3785   // Upper quadword copied in order.
3786   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3787     return false;
3788
3789   // Lower quadword shuffled.
3790   for (unsigned i = 0; i != 4; ++i)
3791     if (!isUndefOrInRange(Mask[i], 0, 4))
3792       return false;
3793
3794   if (VT == MVT::v16i16) {
3795     // Upper quadword copied in order.
3796     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3797       return false;
3798
3799     // Lower quadword shuffled.
3800     for (unsigned i = 8; i != 12; ++i)
3801       if (!isUndefOrInRange(Mask[i], 8, 12))
3802         return false;
3803   }
3804
3805   return true;
3806 }
3807
3808 /// \brief Return true if the mask specifies a shuffle of elements that is
3809 /// suitable for input to intralane (palignr) or interlane (valign) vector
3810 /// right-shift.
3811 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3812   unsigned NumElts = VT.getVectorNumElements();
3813   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3814   unsigned NumLaneElts = NumElts/NumLanes;
3815
3816   // Do not handle 64-bit element shuffles with palignr.
3817   if (NumLaneElts == 2)
3818     return false;
3819
3820   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3821     unsigned i;
3822     for (i = 0; i != NumLaneElts; ++i) {
3823       if (Mask[i+l] >= 0)
3824         break;
3825     }
3826
3827     // Lane is all undef, go to next lane
3828     if (i == NumLaneElts)
3829       continue;
3830
3831     int Start = Mask[i+l];
3832
3833     // Make sure its in this lane in one of the sources
3834     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3835         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3836       return false;
3837
3838     // If not lane 0, then we must match lane 0
3839     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3840       return false;
3841
3842     // Correct second source to be contiguous with first source
3843     if (Start >= (int)NumElts)
3844       Start -= NumElts - NumLaneElts;
3845
3846     // Make sure we're shifting in the right direction.
3847     if (Start <= (int)(i+l))
3848       return false;
3849
3850     Start -= i;
3851
3852     // Check the rest of the elements to see if they are consecutive.
3853     for (++i; i != NumLaneElts; ++i) {
3854       int Idx = Mask[i+l];
3855
3856       // Make sure its in this lane
3857       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3858           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3859         return false;
3860
3861       // If not lane 0, then we must match lane 0
3862       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3863         return false;
3864
3865       if (Idx >= (int)NumElts)
3866         Idx -= NumElts - NumLaneElts;
3867
3868       if (!isUndefOrEqual(Idx, Start+i))
3869         return false;
3870
3871     }
3872   }
3873
3874   return true;
3875 }
3876
3877 /// \brief Return true if the node specifies a shuffle of elements that is
3878 /// suitable for input to PALIGNR.
3879 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3880                           const X86Subtarget *Subtarget) {
3881   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3882       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
3883       VT.is512BitVector())
3884     // FIXME: Add AVX512BW.
3885     return false;
3886
3887   return isAlignrMask(Mask, VT, false);
3888 }
3889
3890 /// \brief Return true if the node specifies a shuffle of elements that is
3891 /// suitable for input to VALIGN.
3892 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
3893                           const X86Subtarget *Subtarget) {
3894   // FIXME: Add AVX512VL.
3895   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
3896     return false;
3897   return isAlignrMask(Mask, VT, true);
3898 }
3899
3900 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3901 /// the two vector operands have swapped position.
3902 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3903                                      unsigned NumElems) {
3904   for (unsigned i = 0; i != NumElems; ++i) {
3905     int idx = Mask[i];
3906     if (idx < 0)
3907       continue;
3908     else if (idx < (int)NumElems)
3909       Mask[i] = idx + NumElems;
3910     else
3911       Mask[i] = idx - NumElems;
3912   }
3913 }
3914
3915 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3916 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3917 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3918 /// reverse of what x86 shuffles want.
3919 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3920
3921   unsigned NumElems = VT.getVectorNumElements();
3922   unsigned NumLanes = VT.getSizeInBits()/128;
3923   unsigned NumLaneElems = NumElems/NumLanes;
3924
3925   if (NumLaneElems != 2 && NumLaneElems != 4)
3926     return false;
3927
3928   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3929   bool symetricMaskRequired =
3930     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3931
3932   // VSHUFPSY divides the resulting vector into 4 chunks.
3933   // The sources are also splitted into 4 chunks, and each destination
3934   // chunk must come from a different source chunk.
3935   //
3936   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3937   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3938   //
3939   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3940   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3941   //
3942   // VSHUFPDY divides the resulting vector into 4 chunks.
3943   // The sources are also splitted into 4 chunks, and each destination
3944   // chunk must come from a different source chunk.
3945   //
3946   //  SRC1 =>      X3       X2       X1       X0
3947   //  SRC2 =>      Y3       Y2       Y1       Y0
3948   //
3949   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3950   //
3951   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3952   unsigned HalfLaneElems = NumLaneElems/2;
3953   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3954     for (unsigned i = 0; i != NumLaneElems; ++i) {
3955       int Idx = Mask[i+l];
3956       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3957       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3958         return false;
3959       // For VSHUFPSY, the mask of the second half must be the same as the
3960       // first but with the appropriate offsets. This works in the same way as
3961       // VPERMILPS works with masks.
3962       if (!symetricMaskRequired || Idx < 0)
3963         continue;
3964       if (MaskVal[i] < 0) {
3965         MaskVal[i] = Idx - l;
3966         continue;
3967       }
3968       if ((signed)(Idx - l) != MaskVal[i])
3969         return false;
3970     }
3971   }
3972
3973   return true;
3974 }
3975
3976 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3977 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3978 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3979   if (!VT.is128BitVector())
3980     return false;
3981
3982   unsigned NumElems = VT.getVectorNumElements();
3983
3984   if (NumElems != 4)
3985     return false;
3986
3987   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3988   return isUndefOrEqual(Mask[0], 6) &&
3989          isUndefOrEqual(Mask[1], 7) &&
3990          isUndefOrEqual(Mask[2], 2) &&
3991          isUndefOrEqual(Mask[3], 3);
3992 }
3993
3994 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3995 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3996 /// <2, 3, 2, 3>
3997 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3998   if (!VT.is128BitVector())
3999     return false;
4000
4001   unsigned NumElems = VT.getVectorNumElements();
4002
4003   if (NumElems != 4)
4004     return false;
4005
4006   return isUndefOrEqual(Mask[0], 2) &&
4007          isUndefOrEqual(Mask[1], 3) &&
4008          isUndefOrEqual(Mask[2], 2) &&
4009          isUndefOrEqual(Mask[3], 3);
4010 }
4011
4012 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4013 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4014 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4015   if (!VT.is128BitVector())
4016     return false;
4017
4018   unsigned NumElems = VT.getVectorNumElements();
4019
4020   if (NumElems != 2 && NumElems != 4)
4021     return false;
4022
4023   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4024     if (!isUndefOrEqual(Mask[i], i + NumElems))
4025       return false;
4026
4027   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4028     if (!isUndefOrEqual(Mask[i], i))
4029       return false;
4030
4031   return true;
4032 }
4033
4034 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4035 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4036 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4037   if (!VT.is128BitVector())
4038     return false;
4039
4040   unsigned NumElems = VT.getVectorNumElements();
4041
4042   if (NumElems != 2 && NumElems != 4)
4043     return false;
4044
4045   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4046     if (!isUndefOrEqual(Mask[i], i))
4047       return false;
4048
4049   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4050     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4051       return false;
4052
4053   return true;
4054 }
4055
4056 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4057 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4058 /// i. e: If all but one element come from the same vector.
4059 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4060   // TODO: Deal with AVX's VINSERTPS
4061   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4062     return false;
4063
4064   unsigned CorrectPosV1 = 0;
4065   unsigned CorrectPosV2 = 0;
4066   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4067     if (Mask[i] == -1) {
4068       ++CorrectPosV1;
4069       ++CorrectPosV2;
4070       continue;
4071     }
4072
4073     if (Mask[i] == i)
4074       ++CorrectPosV1;
4075     else if (Mask[i] == i + 4)
4076       ++CorrectPosV2;
4077   }
4078
4079   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4080     // We have 3 elements (undefs count as elements from any vector) from one
4081     // vector, and one from another.
4082     return true;
4083
4084   return false;
4085 }
4086
4087 //
4088 // Some special combinations that can be optimized.
4089 //
4090 static
4091 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4092                                SelectionDAG &DAG) {
4093   MVT VT = SVOp->getSimpleValueType(0);
4094   SDLoc dl(SVOp);
4095
4096   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4097     return SDValue();
4098
4099   ArrayRef<int> Mask = SVOp->getMask();
4100
4101   // These are the special masks that may be optimized.
4102   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4103   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4104   bool MatchEvenMask = true;
4105   bool MatchOddMask  = true;
4106   for (int i=0; i<8; ++i) {
4107     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4108       MatchEvenMask = false;
4109     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4110       MatchOddMask = false;
4111   }
4112
4113   if (!MatchEvenMask && !MatchOddMask)
4114     return SDValue();
4115
4116   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4117
4118   SDValue Op0 = SVOp->getOperand(0);
4119   SDValue Op1 = SVOp->getOperand(1);
4120
4121   if (MatchEvenMask) {
4122     // Shift the second operand right to 32 bits.
4123     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4124     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4125   } else {
4126     // Shift the first operand left to 32 bits.
4127     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4128     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4129   }
4130   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4131   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4132 }
4133
4134 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4135 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4136 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4137                          bool HasInt256, bool V2IsSplat = false) {
4138
4139   assert(VT.getSizeInBits() >= 128 &&
4140          "Unsupported vector type for unpckl");
4141
4142   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4143   unsigned NumLanes;
4144   unsigned NumOf256BitLanes;
4145   unsigned NumElts = VT.getVectorNumElements();
4146   if (VT.is256BitVector()) {
4147     if (NumElts != 4 && NumElts != 8 &&
4148         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4149     return false;
4150     NumLanes = 2;
4151     NumOf256BitLanes = 1;
4152   } else if (VT.is512BitVector()) {
4153     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4154            "Unsupported vector type for unpckh");
4155     NumLanes = 2;
4156     NumOf256BitLanes = 2;
4157   } else {
4158     NumLanes = 1;
4159     NumOf256BitLanes = 1;
4160   }
4161
4162   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4163   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4164
4165   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4166     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4167       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4168         int BitI  = Mask[l256*NumEltsInStride+l+i];
4169         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4170         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4171           return false;
4172         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4173           return false;
4174         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4175           return false;
4176       }
4177     }
4178   }
4179   return true;
4180 }
4181
4182 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4183 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4184 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4185                          bool HasInt256, bool V2IsSplat = false) {
4186   assert(VT.getSizeInBits() >= 128 &&
4187          "Unsupported vector type for unpckh");
4188
4189   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4190   unsigned NumLanes;
4191   unsigned NumOf256BitLanes;
4192   unsigned NumElts = VT.getVectorNumElements();
4193   if (VT.is256BitVector()) {
4194     if (NumElts != 4 && NumElts != 8 &&
4195         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4196     return false;
4197     NumLanes = 2;
4198     NumOf256BitLanes = 1;
4199   } else if (VT.is512BitVector()) {
4200     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4201            "Unsupported vector type for unpckh");
4202     NumLanes = 2;
4203     NumOf256BitLanes = 2;
4204   } else {
4205     NumLanes = 1;
4206     NumOf256BitLanes = 1;
4207   }
4208
4209   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4210   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4211
4212   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4213     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4214       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4215         int BitI  = Mask[l256*NumEltsInStride+l+i];
4216         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4217         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4218           return false;
4219         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4220           return false;
4221         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4222           return false;
4223       }
4224     }
4225   }
4226   return true;
4227 }
4228
4229 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4230 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4231 /// <0, 0, 1, 1>
4232 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4233   unsigned NumElts = VT.getVectorNumElements();
4234   bool Is256BitVec = VT.is256BitVector();
4235
4236   if (VT.is512BitVector())
4237     return false;
4238   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4239          "Unsupported vector type for unpckh");
4240
4241   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4242       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4243     return false;
4244
4245   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4246   // FIXME: Need a better way to get rid of this, there's no latency difference
4247   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4248   // the former later. We should also remove the "_undef" special mask.
4249   if (NumElts == 4 && Is256BitVec)
4250     return false;
4251
4252   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4253   // independently on 128-bit lanes.
4254   unsigned NumLanes = VT.getSizeInBits()/128;
4255   unsigned NumLaneElts = NumElts/NumLanes;
4256
4257   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4258     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4259       int BitI  = Mask[l+i];
4260       int BitI1 = Mask[l+i+1];
4261
4262       if (!isUndefOrEqual(BitI, j))
4263         return false;
4264       if (!isUndefOrEqual(BitI1, j))
4265         return false;
4266     }
4267   }
4268
4269   return true;
4270 }
4271
4272 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4273 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4274 /// <2, 2, 3, 3>
4275 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4276   unsigned NumElts = VT.getVectorNumElements();
4277
4278   if (VT.is512BitVector())
4279     return false;
4280
4281   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4282          "Unsupported vector type for unpckh");
4283
4284   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4285       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4286     return false;
4287
4288   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4289   // independently on 128-bit lanes.
4290   unsigned NumLanes = VT.getSizeInBits()/128;
4291   unsigned NumLaneElts = NumElts/NumLanes;
4292
4293   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4294     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4295       int BitI  = Mask[l+i];
4296       int BitI1 = Mask[l+i+1];
4297       if (!isUndefOrEqual(BitI, j))
4298         return false;
4299       if (!isUndefOrEqual(BitI1, j))
4300         return false;
4301     }
4302   }
4303   return true;
4304 }
4305
4306 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4307 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4308 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4309   if (!VT.is512BitVector())
4310     return false;
4311
4312   unsigned NumElts = VT.getVectorNumElements();
4313   unsigned HalfSize = NumElts/2;
4314   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4315     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4316       *Imm = 1;
4317       return true;
4318     }
4319   }
4320   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4321     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4322       *Imm = 0;
4323       return true;
4324     }
4325   }
4326   return false;
4327 }
4328
4329 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4330 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4331 /// MOVSD, and MOVD, i.e. setting the lowest element.
4332 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4333   if (VT.getVectorElementType().getSizeInBits() < 32)
4334     return false;
4335   if (!VT.is128BitVector())
4336     return false;
4337
4338   unsigned NumElts = VT.getVectorNumElements();
4339
4340   if (!isUndefOrEqual(Mask[0], NumElts))
4341     return false;
4342
4343   for (unsigned i = 1; i != NumElts; ++i)
4344     if (!isUndefOrEqual(Mask[i], i))
4345       return false;
4346
4347   return true;
4348 }
4349
4350 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4351 /// as permutations between 128-bit chunks or halves. As an example: this
4352 /// shuffle bellow:
4353 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4354 /// The first half comes from the second half of V1 and the second half from the
4355 /// the second half of V2.
4356 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4357   if (!HasFp256 || !VT.is256BitVector())
4358     return false;
4359
4360   // The shuffle result is divided into half A and half B. In total the two
4361   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4362   // B must come from C, D, E or F.
4363   unsigned HalfSize = VT.getVectorNumElements()/2;
4364   bool MatchA = false, MatchB = false;
4365
4366   // Check if A comes from one of C, D, E, F.
4367   for (unsigned Half = 0; Half != 4; ++Half) {
4368     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4369       MatchA = true;
4370       break;
4371     }
4372   }
4373
4374   // Check if B comes from one of C, D, E, F.
4375   for (unsigned Half = 0; Half != 4; ++Half) {
4376     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4377       MatchB = true;
4378       break;
4379     }
4380   }
4381
4382   return MatchA && MatchB;
4383 }
4384
4385 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4386 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4387 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4388   MVT VT = SVOp->getSimpleValueType(0);
4389
4390   unsigned HalfSize = VT.getVectorNumElements()/2;
4391
4392   unsigned FstHalf = 0, SndHalf = 0;
4393   for (unsigned i = 0; i < HalfSize; ++i) {
4394     if (SVOp->getMaskElt(i) > 0) {
4395       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4396       break;
4397     }
4398   }
4399   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4400     if (SVOp->getMaskElt(i) > 0) {
4401       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4402       break;
4403     }
4404   }
4405
4406   return (FstHalf | (SndHalf << 4));
4407 }
4408
4409 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4410 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4411   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4412   if (EltSize < 32)
4413     return false;
4414
4415   unsigned NumElts = VT.getVectorNumElements();
4416   Imm8 = 0;
4417   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4418     for (unsigned i = 0; i != NumElts; ++i) {
4419       if (Mask[i] < 0)
4420         continue;
4421       Imm8 |= Mask[i] << (i*2);
4422     }
4423     return true;
4424   }
4425
4426   unsigned LaneSize = 4;
4427   SmallVector<int, 4> MaskVal(LaneSize, -1);
4428
4429   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4430     for (unsigned i = 0; i != LaneSize; ++i) {
4431       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4432         return false;
4433       if (Mask[i+l] < 0)
4434         continue;
4435       if (MaskVal[i] < 0) {
4436         MaskVal[i] = Mask[i+l] - l;
4437         Imm8 |= MaskVal[i] << (i*2);
4438         continue;
4439       }
4440       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4441         return false;
4442     }
4443   }
4444   return true;
4445 }
4446
4447 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4448 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4449 /// Note that VPERMIL mask matching is different depending whether theunderlying
4450 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4451 /// to the same elements of the low, but to the higher half of the source.
4452 /// In VPERMILPD the two lanes could be shuffled independently of each other
4453 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4454 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4455   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4456   if (VT.getSizeInBits() < 256 || EltSize < 32)
4457     return false;
4458   bool symetricMaskRequired = (EltSize == 32);
4459   unsigned NumElts = VT.getVectorNumElements();
4460
4461   unsigned NumLanes = VT.getSizeInBits()/128;
4462   unsigned LaneSize = NumElts/NumLanes;
4463   // 2 or 4 elements in one lane
4464
4465   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4466   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4467     for (unsigned i = 0; i != LaneSize; ++i) {
4468       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4469         return false;
4470       if (symetricMaskRequired) {
4471         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4472           ExpectedMaskVal[i] = Mask[i+l] - l;
4473           continue;
4474         }
4475         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4476           return false;
4477       }
4478     }
4479   }
4480   return true;
4481 }
4482
4483 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4484 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4485 /// element of vector 2 and the other elements to come from vector 1 in order.
4486 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4487                                bool V2IsSplat = false, bool V2IsUndef = false) {
4488   if (!VT.is128BitVector())
4489     return false;
4490
4491   unsigned NumOps = VT.getVectorNumElements();
4492   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4493     return false;
4494
4495   if (!isUndefOrEqual(Mask[0], 0))
4496     return false;
4497
4498   for (unsigned i = 1; i != NumOps; ++i)
4499     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4500           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4501           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4502       return false;
4503
4504   return true;
4505 }
4506
4507 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4508 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4509 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4510 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4511                            const X86Subtarget *Subtarget) {
4512   if (!Subtarget->hasSSE3())
4513     return false;
4514
4515   unsigned NumElems = VT.getVectorNumElements();
4516
4517   if ((VT.is128BitVector() && NumElems != 4) ||
4518       (VT.is256BitVector() && NumElems != 8) ||
4519       (VT.is512BitVector() && NumElems != 16))
4520     return false;
4521
4522   // "i+1" is the value the indexed mask element must have
4523   for (unsigned i = 0; i != NumElems; i += 2)
4524     if (!isUndefOrEqual(Mask[i], i+1) ||
4525         !isUndefOrEqual(Mask[i+1], i+1))
4526       return false;
4527
4528   return true;
4529 }
4530
4531 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4532 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4533 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4534 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4535                            const X86Subtarget *Subtarget) {
4536   if (!Subtarget->hasSSE3())
4537     return false;
4538
4539   unsigned NumElems = VT.getVectorNumElements();
4540
4541   if ((VT.is128BitVector() && NumElems != 4) ||
4542       (VT.is256BitVector() && NumElems != 8) ||
4543       (VT.is512BitVector() && NumElems != 16))
4544     return false;
4545
4546   // "i" is the value the indexed mask element must have
4547   for (unsigned i = 0; i != NumElems; i += 2)
4548     if (!isUndefOrEqual(Mask[i], i) ||
4549         !isUndefOrEqual(Mask[i+1], i))
4550       return false;
4551
4552   return true;
4553 }
4554
4555 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4556 /// specifies a shuffle of elements that is suitable for input to 256-bit
4557 /// version of MOVDDUP.
4558 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4559   if (!HasFp256 || !VT.is256BitVector())
4560     return false;
4561
4562   unsigned NumElts = VT.getVectorNumElements();
4563   if (NumElts != 4)
4564     return false;
4565
4566   for (unsigned i = 0; i != NumElts/2; ++i)
4567     if (!isUndefOrEqual(Mask[i], 0))
4568       return false;
4569   for (unsigned i = NumElts/2; i != NumElts; ++i)
4570     if (!isUndefOrEqual(Mask[i], NumElts/2))
4571       return false;
4572   return true;
4573 }
4574
4575 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4576 /// specifies a shuffle of elements that is suitable for input to 128-bit
4577 /// version of MOVDDUP.
4578 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4579   if (!VT.is128BitVector())
4580     return false;
4581
4582   unsigned e = VT.getVectorNumElements() / 2;
4583   for (unsigned i = 0; i != e; ++i)
4584     if (!isUndefOrEqual(Mask[i], i))
4585       return false;
4586   for (unsigned i = 0; i != e; ++i)
4587     if (!isUndefOrEqual(Mask[e+i], i))
4588       return false;
4589   return true;
4590 }
4591
4592 /// isVEXTRACTIndex - Return true if the specified
4593 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4594 /// suitable for instruction that extract 128 or 256 bit vectors
4595 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4596   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4597   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4598     return false;
4599
4600   // The index should be aligned on a vecWidth-bit boundary.
4601   uint64_t Index =
4602     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4603
4604   MVT VT = N->getSimpleValueType(0);
4605   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4606   bool Result = (Index * ElSize) % vecWidth == 0;
4607
4608   return Result;
4609 }
4610
4611 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4612 /// operand specifies a subvector insert that is suitable for input to
4613 /// insertion of 128 or 256-bit subvectors
4614 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4615   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4616   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4617     return false;
4618   // The index should be aligned on a vecWidth-bit boundary.
4619   uint64_t Index =
4620     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4621
4622   MVT VT = N->getSimpleValueType(0);
4623   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4624   bool Result = (Index * ElSize) % vecWidth == 0;
4625
4626   return Result;
4627 }
4628
4629 bool X86::isVINSERT128Index(SDNode *N) {
4630   return isVINSERTIndex(N, 128);
4631 }
4632
4633 bool X86::isVINSERT256Index(SDNode *N) {
4634   return isVINSERTIndex(N, 256);
4635 }
4636
4637 bool X86::isVEXTRACT128Index(SDNode *N) {
4638   return isVEXTRACTIndex(N, 128);
4639 }
4640
4641 bool X86::isVEXTRACT256Index(SDNode *N) {
4642   return isVEXTRACTIndex(N, 256);
4643 }
4644
4645 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4646 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4647 /// Handles 128-bit and 256-bit.
4648 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4649   MVT VT = N->getSimpleValueType(0);
4650
4651   assert((VT.getSizeInBits() >= 128) &&
4652          "Unsupported vector type for PSHUF/SHUFP");
4653
4654   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4655   // independently on 128-bit lanes.
4656   unsigned NumElts = VT.getVectorNumElements();
4657   unsigned NumLanes = VT.getSizeInBits()/128;
4658   unsigned NumLaneElts = NumElts/NumLanes;
4659
4660   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4661          "Only supports 2, 4 or 8 elements per lane");
4662
4663   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4664   unsigned Mask = 0;
4665   for (unsigned i = 0; i != NumElts; ++i) {
4666     int Elt = N->getMaskElt(i);
4667     if (Elt < 0) continue;
4668     Elt &= NumLaneElts - 1;
4669     unsigned ShAmt = (i << Shift) % 8;
4670     Mask |= Elt << ShAmt;
4671   }
4672
4673   return Mask;
4674 }
4675
4676 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4677 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4678 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4679   MVT VT = N->getSimpleValueType(0);
4680
4681   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4682          "Unsupported vector type for PSHUFHW");
4683
4684   unsigned NumElts = VT.getVectorNumElements();
4685
4686   unsigned Mask = 0;
4687   for (unsigned l = 0; l != NumElts; l += 8) {
4688     // 8 nodes per lane, but we only care about the last 4.
4689     for (unsigned i = 0; i < 4; ++i) {
4690       int Elt = N->getMaskElt(l+i+4);
4691       if (Elt < 0) continue;
4692       Elt &= 0x3; // only 2-bits.
4693       Mask |= Elt << (i * 2);
4694     }
4695   }
4696
4697   return Mask;
4698 }
4699
4700 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4701 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4702 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4703   MVT VT = N->getSimpleValueType(0);
4704
4705   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4706          "Unsupported vector type for PSHUFHW");
4707
4708   unsigned NumElts = VT.getVectorNumElements();
4709
4710   unsigned Mask = 0;
4711   for (unsigned l = 0; l != NumElts; l += 8) {
4712     // 8 nodes per lane, but we only care about the first 4.
4713     for (unsigned i = 0; i < 4; ++i) {
4714       int Elt = N->getMaskElt(l+i);
4715       if (Elt < 0) continue;
4716       Elt &= 0x3; // only 2-bits
4717       Mask |= Elt << (i * 2);
4718     }
4719   }
4720
4721   return Mask;
4722 }
4723
4724 /// \brief Return the appropriate immediate to shuffle the specified
4725 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4726 /// VALIGN (if Interlane is true) instructions.
4727 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4728                                            bool InterLane) {
4729   MVT VT = SVOp->getSimpleValueType(0);
4730   unsigned EltSize = InterLane ? 1 :
4731     VT.getVectorElementType().getSizeInBits() >> 3;
4732
4733   unsigned NumElts = VT.getVectorNumElements();
4734   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4735   unsigned NumLaneElts = NumElts/NumLanes;
4736
4737   int Val = 0;
4738   unsigned i;
4739   for (i = 0; i != NumElts; ++i) {
4740     Val = SVOp->getMaskElt(i);
4741     if (Val >= 0)
4742       break;
4743   }
4744   if (Val >= (int)NumElts)
4745     Val -= NumElts - NumLaneElts;
4746
4747   assert(Val - i > 0 && "PALIGNR imm should be positive");
4748   return (Val - i) * EltSize;
4749 }
4750
4751 /// \brief Return the appropriate immediate to shuffle the specified
4752 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4753 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4754   return getShuffleAlignrImmediate(SVOp, false);
4755 }
4756
4757 /// \brief Return the appropriate immediate to shuffle the specified
4758 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4759 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4760   return getShuffleAlignrImmediate(SVOp, true);
4761 }
4762
4763
4764 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4765   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4766   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4767     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4768
4769   uint64_t Index =
4770     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4771
4772   MVT VecVT = N->getOperand(0).getSimpleValueType();
4773   MVT ElVT = VecVT.getVectorElementType();
4774
4775   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4776   return Index / NumElemsPerChunk;
4777 }
4778
4779 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4780   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4781   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4782     llvm_unreachable("Illegal insert subvector for VINSERT");
4783
4784   uint64_t Index =
4785     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4786
4787   MVT VecVT = N->getSimpleValueType(0);
4788   MVT ElVT = VecVT.getVectorElementType();
4789
4790   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4791   return Index / NumElemsPerChunk;
4792 }
4793
4794 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4795 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4796 /// and VINSERTI128 instructions.
4797 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4798   return getExtractVEXTRACTImmediate(N, 128);
4799 }
4800
4801 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4802 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4803 /// and VINSERTI64x4 instructions.
4804 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4805   return getExtractVEXTRACTImmediate(N, 256);
4806 }
4807
4808 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4809 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4810 /// and VINSERTI128 instructions.
4811 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4812   return getInsertVINSERTImmediate(N, 128);
4813 }
4814
4815 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4816 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4817 /// and VINSERTI64x4 instructions.
4818 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4819   return getInsertVINSERTImmediate(N, 256);
4820 }
4821
4822 /// isZero - Returns true if Elt is a constant integer zero
4823 static bool isZero(SDValue V) {
4824   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4825   return C && C->isNullValue();
4826 }
4827
4828 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4829 /// constant +0.0.
4830 bool X86::isZeroNode(SDValue Elt) {
4831   if (isZero(Elt))
4832     return true;
4833   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4834     return CFP->getValueAPF().isPosZero();
4835   return false;
4836 }
4837
4838 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4839 /// match movhlps. The lower half elements should come from upper half of
4840 /// V1 (and in order), and the upper half elements should come from the upper
4841 /// half of V2 (and in order).
4842 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4843   if (!VT.is128BitVector())
4844     return false;
4845   if (VT.getVectorNumElements() != 4)
4846     return false;
4847   for (unsigned i = 0, e = 2; i != e; ++i)
4848     if (!isUndefOrEqual(Mask[i], i+2))
4849       return false;
4850   for (unsigned i = 2; i != 4; ++i)
4851     if (!isUndefOrEqual(Mask[i], i+4))
4852       return false;
4853   return true;
4854 }
4855
4856 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4857 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4858 /// required.
4859 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4860   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4861     return false;
4862   N = N->getOperand(0).getNode();
4863   if (!ISD::isNON_EXTLoad(N))
4864     return false;
4865   if (LD)
4866     *LD = cast<LoadSDNode>(N);
4867   return true;
4868 }
4869
4870 // Test whether the given value is a vector value which will be legalized
4871 // into a load.
4872 static bool WillBeConstantPoolLoad(SDNode *N) {
4873   if (N->getOpcode() != ISD::BUILD_VECTOR)
4874     return false;
4875
4876   // Check for any non-constant elements.
4877   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4878     switch (N->getOperand(i).getNode()->getOpcode()) {
4879     case ISD::UNDEF:
4880     case ISD::ConstantFP:
4881     case ISD::Constant:
4882       break;
4883     default:
4884       return false;
4885     }
4886
4887   // Vectors of all-zeros and all-ones are materialized with special
4888   // instructions rather than being loaded.
4889   return !ISD::isBuildVectorAllZeros(N) &&
4890          !ISD::isBuildVectorAllOnes(N);
4891 }
4892
4893 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4894 /// match movlp{s|d}. The lower half elements should come from lower half of
4895 /// V1 (and in order), and the upper half elements should come from the upper
4896 /// half of V2 (and in order). And since V1 will become the source of the
4897 /// MOVLP, it must be either a vector load or a scalar load to vector.
4898 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4899                                ArrayRef<int> Mask, MVT VT) {
4900   if (!VT.is128BitVector())
4901     return false;
4902
4903   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4904     return false;
4905   // Is V2 is a vector load, don't do this transformation. We will try to use
4906   // load folding shufps op.
4907   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4908     return false;
4909
4910   unsigned NumElems = VT.getVectorNumElements();
4911
4912   if (NumElems != 2 && NumElems != 4)
4913     return false;
4914   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4915     if (!isUndefOrEqual(Mask[i], i))
4916       return false;
4917   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4918     if (!isUndefOrEqual(Mask[i], i+NumElems))
4919       return false;
4920   return true;
4921 }
4922
4923 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4924 /// to an zero vector.
4925 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4926 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4927   SDValue V1 = N->getOperand(0);
4928   SDValue V2 = N->getOperand(1);
4929   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4930   for (unsigned i = 0; i != NumElems; ++i) {
4931     int Idx = N->getMaskElt(i);
4932     if (Idx >= (int)NumElems) {
4933       unsigned Opc = V2.getOpcode();
4934       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4935         continue;
4936       if (Opc != ISD::BUILD_VECTOR ||
4937           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4938         return false;
4939     } else if (Idx >= 0) {
4940       unsigned Opc = V1.getOpcode();
4941       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4942         continue;
4943       if (Opc != ISD::BUILD_VECTOR ||
4944           !X86::isZeroNode(V1.getOperand(Idx)))
4945         return false;
4946     }
4947   }
4948   return true;
4949 }
4950
4951 /// getZeroVector - Returns a vector of specified type with all zero elements.
4952 ///
4953 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4954                              SelectionDAG &DAG, SDLoc dl) {
4955   assert(VT.isVector() && "Expected a vector type");
4956
4957   // Always build SSE zero vectors as <4 x i32> bitcasted
4958   // to their dest type. This ensures they get CSE'd.
4959   SDValue Vec;
4960   if (VT.is128BitVector()) {  // SSE
4961     if (Subtarget->hasSSE2()) {  // SSE2
4962       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4963       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4964     } else { // SSE1
4965       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4966       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4967     }
4968   } else if (VT.is256BitVector()) { // AVX
4969     if (Subtarget->hasInt256()) { // AVX2
4970       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4971       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4972       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4973     } else {
4974       // 256-bit logic and arithmetic instructions in AVX are all
4975       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4976       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4977       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4978       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4979     }
4980   } else if (VT.is512BitVector()) { // AVX-512
4981       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4982       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4983                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4984       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4985   } else if (VT.getScalarType() == MVT::i1) {
4986     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4987     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4988     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4989     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4990   } else
4991     llvm_unreachable("Unexpected vector type");
4992
4993   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4994 }
4995
4996 /// getOnesVector - Returns a vector of specified type with all bits set.
4997 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4998 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4999 /// Then bitcast to their original type, ensuring they get CSE'd.
5000 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5001                              SDLoc dl) {
5002   assert(VT.isVector() && "Expected a vector type");
5003
5004   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5005   SDValue Vec;
5006   if (VT.is256BitVector()) {
5007     if (HasInt256) { // AVX2
5008       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5009       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5010     } else { // AVX
5011       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5012       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5013     }
5014   } else if (VT.is128BitVector()) {
5015     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5016   } else
5017     llvm_unreachable("Unexpected vector type");
5018
5019   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5020 }
5021
5022 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5023 /// that point to V2 points to its first element.
5024 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5025   for (unsigned i = 0; i != NumElems; ++i) {
5026     if (Mask[i] > (int)NumElems) {
5027       Mask[i] = NumElems;
5028     }
5029   }
5030 }
5031
5032 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5033 /// operation of specified width.
5034 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5035                        SDValue V2) {
5036   unsigned NumElems = VT.getVectorNumElements();
5037   SmallVector<int, 8> Mask;
5038   Mask.push_back(NumElems);
5039   for (unsigned i = 1; i != NumElems; ++i)
5040     Mask.push_back(i);
5041   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5042 }
5043
5044 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5045 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5046                           SDValue V2) {
5047   unsigned NumElems = VT.getVectorNumElements();
5048   SmallVector<int, 8> Mask;
5049   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5050     Mask.push_back(i);
5051     Mask.push_back(i + NumElems);
5052   }
5053   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5054 }
5055
5056 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5057 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5058                           SDValue V2) {
5059   unsigned NumElems = VT.getVectorNumElements();
5060   SmallVector<int, 8> Mask;
5061   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5062     Mask.push_back(i + Half);
5063     Mask.push_back(i + NumElems + Half);
5064   }
5065   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5066 }
5067
5068 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5069 // a generic shuffle instruction because the target has no such instructions.
5070 // Generate shuffles which repeat i16 and i8 several times until they can be
5071 // represented by v4f32 and then be manipulated by target suported shuffles.
5072 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5073   MVT VT = V.getSimpleValueType();
5074   int NumElems = VT.getVectorNumElements();
5075   SDLoc dl(V);
5076
5077   while (NumElems > 4) {
5078     if (EltNo < NumElems/2) {
5079       V = getUnpackl(DAG, dl, VT, V, V);
5080     } else {
5081       V = getUnpackh(DAG, dl, VT, V, V);
5082       EltNo -= NumElems/2;
5083     }
5084     NumElems >>= 1;
5085   }
5086   return V;
5087 }
5088
5089 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5090 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5091   MVT VT = V.getSimpleValueType();
5092   SDLoc dl(V);
5093
5094   if (VT.is128BitVector()) {
5095     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5096     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5097     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5098                              &SplatMask[0]);
5099   } else if (VT.is256BitVector()) {
5100     // To use VPERMILPS to splat scalars, the second half of indicies must
5101     // refer to the higher part, which is a duplication of the lower one,
5102     // because VPERMILPS can only handle in-lane permutations.
5103     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5104                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5105
5106     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5107     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5108                              &SplatMask[0]);
5109   } else
5110     llvm_unreachable("Vector size not supported");
5111
5112   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5113 }
5114
5115 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5116 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5117   MVT SrcVT = SV->getSimpleValueType(0);
5118   SDValue V1 = SV->getOperand(0);
5119   SDLoc dl(SV);
5120
5121   int EltNo = SV->getSplatIndex();
5122   int NumElems = SrcVT.getVectorNumElements();
5123   bool Is256BitVec = SrcVT.is256BitVector();
5124
5125   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5126          "Unknown how to promote splat for type");
5127
5128   // Extract the 128-bit part containing the splat element and update
5129   // the splat element index when it refers to the higher register.
5130   if (Is256BitVec) {
5131     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5132     if (EltNo >= NumElems/2)
5133       EltNo -= NumElems/2;
5134   }
5135
5136   // All i16 and i8 vector types can't be used directly by a generic shuffle
5137   // instruction because the target has no such instruction. Generate shuffles
5138   // which repeat i16 and i8 several times until they fit in i32, and then can
5139   // be manipulated by target suported shuffles.
5140   MVT EltVT = SrcVT.getVectorElementType();
5141   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5142     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5143
5144   // Recreate the 256-bit vector and place the same 128-bit vector
5145   // into the low and high part. This is necessary because we want
5146   // to use VPERM* to shuffle the vectors
5147   if (Is256BitVec) {
5148     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5149   }
5150
5151   return getLegalSplat(DAG, V1, EltNo);
5152 }
5153
5154 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5155 /// vector of zero or undef vector.  This produces a shuffle where the low
5156 /// element of V2 is swizzled into the zero/undef vector, landing at element
5157 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5158 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5159                                            bool IsZero,
5160                                            const X86Subtarget *Subtarget,
5161                                            SelectionDAG &DAG) {
5162   MVT VT = V2.getSimpleValueType();
5163   SDValue V1 = IsZero
5164     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5165   unsigned NumElems = VT.getVectorNumElements();
5166   SmallVector<int, 16> MaskVec;
5167   for (unsigned i = 0; i != NumElems; ++i)
5168     // If this is the insertion idx, put the low elt of V2 here.
5169     MaskVec.push_back(i == Idx ? NumElems : i);
5170   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5171 }
5172
5173 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5174 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5175 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5176 /// shuffles which use a single input multiple times, and in those cases it will
5177 /// adjust the mask to only have indices within that single input.
5178 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5179                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5180   unsigned NumElems = VT.getVectorNumElements();
5181   SDValue ImmN;
5182
5183   IsUnary = false;
5184   bool IsFakeUnary = false;
5185   switch(N->getOpcode()) {
5186   case X86ISD::SHUFP:
5187     ImmN = N->getOperand(N->getNumOperands()-1);
5188     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5189     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5190     break;
5191   case X86ISD::UNPCKH:
5192     DecodeUNPCKHMask(VT, Mask);
5193     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5194     break;
5195   case X86ISD::UNPCKL:
5196     DecodeUNPCKLMask(VT, Mask);
5197     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5198     break;
5199   case X86ISD::MOVHLPS:
5200     DecodeMOVHLPSMask(NumElems, Mask);
5201     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5202     break;
5203   case X86ISD::MOVLHPS:
5204     DecodeMOVLHPSMask(NumElems, Mask);
5205     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5206     break;
5207   case X86ISD::PALIGNR:
5208     ImmN = N->getOperand(N->getNumOperands()-1);
5209     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5210     break;
5211   case X86ISD::PSHUFD:
5212   case X86ISD::VPERMILP:
5213     ImmN = N->getOperand(N->getNumOperands()-1);
5214     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5215     IsUnary = true;
5216     break;
5217   case X86ISD::PSHUFHW:
5218     ImmN = N->getOperand(N->getNumOperands()-1);
5219     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5220     IsUnary = true;
5221     break;
5222   case X86ISD::PSHUFLW:
5223     ImmN = N->getOperand(N->getNumOperands()-1);
5224     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5225     IsUnary = true;
5226     break;
5227   case X86ISD::PSHUFB: {
5228     IsUnary = true;
5229     SDValue MaskNode = N->getOperand(1);
5230     while (MaskNode->getOpcode() == ISD::BITCAST)
5231       MaskNode = MaskNode->getOperand(0);
5232
5233     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5234       // If we have a build-vector, then things are easy.
5235       EVT VT = MaskNode.getValueType();
5236       assert(VT.isVector() &&
5237              "Can't produce a non-vector with a build_vector!");
5238       if (!VT.isInteger())
5239         return false;
5240
5241       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5242
5243       SmallVector<uint64_t, 32> RawMask;
5244       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5245         auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5246         if (!CN)
5247           return false;
5248         APInt MaskElement = CN->getAPIntValue();
5249
5250         // We now have to decode the element which could be any integer size and
5251         // extract each byte of it.
5252         for (int j = 0; j < NumBytesPerElement; ++j) {
5253           // Note that this is x86 and so always little endian: the low byte is
5254           // the first byte of the mask.
5255           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5256           MaskElement = MaskElement.lshr(8);
5257         }
5258       }
5259       DecodePSHUFBMask(RawMask, Mask);
5260       break;
5261     }
5262
5263     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5264     if (!MaskLoad)
5265       return false;
5266
5267     SDValue Ptr = MaskLoad->getBasePtr();
5268     if (Ptr->getOpcode() == X86ISD::Wrapper)
5269       Ptr = Ptr->getOperand(0);
5270
5271     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5272     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5273       return false;
5274
5275     if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5276       // FIXME: Support AVX-512 here.
5277       if (!C->getType()->isVectorTy() ||
5278           (C->getNumElements() != 16 && C->getNumElements() != 32))
5279         return false;
5280
5281       assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5282       DecodePSHUFBMask(C, Mask);
5283       break;
5284     }
5285
5286     return false;
5287   }
5288   case X86ISD::VPERMI:
5289     ImmN = N->getOperand(N->getNumOperands()-1);
5290     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5291     IsUnary = true;
5292     break;
5293   case X86ISD::MOVSS:
5294   case X86ISD::MOVSD: {
5295     // The index 0 always comes from the first element of the second source,
5296     // this is why MOVSS and MOVSD are used in the first place. The other
5297     // elements come from the other positions of the first source vector
5298     Mask.push_back(NumElems);
5299     for (unsigned i = 1; i != NumElems; ++i) {
5300       Mask.push_back(i);
5301     }
5302     break;
5303   }
5304   case X86ISD::VPERM2X128:
5305     ImmN = N->getOperand(N->getNumOperands()-1);
5306     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5307     if (Mask.empty()) return false;
5308     break;
5309   case X86ISD::MOVDDUP:
5310   case X86ISD::MOVLHPD:
5311   case X86ISD::MOVLPD:
5312   case X86ISD::MOVLPS:
5313   case X86ISD::MOVSHDUP:
5314   case X86ISD::MOVSLDUP:
5315     // Not yet implemented
5316     return false;
5317   default: llvm_unreachable("unknown target shuffle node");
5318   }
5319
5320   // If we have a fake unary shuffle, the shuffle mask is spread across two
5321   // inputs that are actually the same node. Re-map the mask to always point
5322   // into the first input.
5323   if (IsFakeUnary)
5324     for (int &M : Mask)
5325       if (M >= (int)Mask.size())
5326         M -= Mask.size();
5327
5328   return true;
5329 }
5330
5331 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5332 /// element of the result of the vector shuffle.
5333 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5334                                    unsigned Depth) {
5335   if (Depth == 6)
5336     return SDValue();  // Limit search depth.
5337
5338   SDValue V = SDValue(N, 0);
5339   EVT VT = V.getValueType();
5340   unsigned Opcode = V.getOpcode();
5341
5342   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5343   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5344     int Elt = SV->getMaskElt(Index);
5345
5346     if (Elt < 0)
5347       return DAG.getUNDEF(VT.getVectorElementType());
5348
5349     unsigned NumElems = VT.getVectorNumElements();
5350     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5351                                          : SV->getOperand(1);
5352     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5353   }
5354
5355   // Recurse into target specific vector shuffles to find scalars.
5356   if (isTargetShuffle(Opcode)) {
5357     MVT ShufVT = V.getSimpleValueType();
5358     unsigned NumElems = ShufVT.getVectorNumElements();
5359     SmallVector<int, 16> ShuffleMask;
5360     bool IsUnary;
5361
5362     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5363       return SDValue();
5364
5365     int Elt = ShuffleMask[Index];
5366     if (Elt < 0)
5367       return DAG.getUNDEF(ShufVT.getVectorElementType());
5368
5369     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5370                                          : N->getOperand(1);
5371     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5372                                Depth+1);
5373   }
5374
5375   // Actual nodes that may contain scalar elements
5376   if (Opcode == ISD::BITCAST) {
5377     V = V.getOperand(0);
5378     EVT SrcVT = V.getValueType();
5379     unsigned NumElems = VT.getVectorNumElements();
5380
5381     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5382       return SDValue();
5383   }
5384
5385   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5386     return (Index == 0) ? V.getOperand(0)
5387                         : DAG.getUNDEF(VT.getVectorElementType());
5388
5389   if (V.getOpcode() == ISD::BUILD_VECTOR)
5390     return V.getOperand(Index);
5391
5392   return SDValue();
5393 }
5394
5395 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5396 /// shuffle operation which come from a consecutively from a zero. The
5397 /// search can start in two different directions, from left or right.
5398 /// We count undefs as zeros until PreferredNum is reached.
5399 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5400                                          unsigned NumElems, bool ZerosFromLeft,
5401                                          SelectionDAG &DAG,
5402                                          unsigned PreferredNum = -1U) {
5403   unsigned NumZeros = 0;
5404   for (unsigned i = 0; i != NumElems; ++i) {
5405     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5406     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5407     if (!Elt.getNode())
5408       break;
5409
5410     if (X86::isZeroNode(Elt))
5411       ++NumZeros;
5412     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5413       NumZeros = std::min(NumZeros + 1, PreferredNum);
5414     else
5415       break;
5416   }
5417
5418   return NumZeros;
5419 }
5420
5421 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5422 /// correspond consecutively to elements from one of the vector operands,
5423 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5424 static
5425 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5426                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5427                               unsigned NumElems, unsigned &OpNum) {
5428   bool SeenV1 = false;
5429   bool SeenV2 = false;
5430
5431   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5432     int Idx = SVOp->getMaskElt(i);
5433     // Ignore undef indicies
5434     if (Idx < 0)
5435       continue;
5436
5437     if (Idx < (int)NumElems)
5438       SeenV1 = true;
5439     else
5440       SeenV2 = true;
5441
5442     // Only accept consecutive elements from the same vector
5443     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5444       return false;
5445   }
5446
5447   OpNum = SeenV1 ? 0 : 1;
5448   return true;
5449 }
5450
5451 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5452 /// logical left shift of a vector.
5453 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5454                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5455   unsigned NumElems =
5456     SVOp->getSimpleValueType(0).getVectorNumElements();
5457   unsigned NumZeros = getNumOfConsecutiveZeros(
5458       SVOp, NumElems, false /* check zeros from right */, DAG,
5459       SVOp->getMaskElt(0));
5460   unsigned OpSrc;
5461
5462   if (!NumZeros)
5463     return false;
5464
5465   // Considering the elements in the mask that are not consecutive zeros,
5466   // check if they consecutively come from only one of the source vectors.
5467   //
5468   //               V1 = {X, A, B, C}     0
5469   //                         \  \  \    /
5470   //   vector_shuffle V1, V2 <1, 2, 3, X>
5471   //
5472   if (!isShuffleMaskConsecutive(SVOp,
5473             0,                   // Mask Start Index
5474             NumElems-NumZeros,   // Mask End Index(exclusive)
5475             NumZeros,            // Where to start looking in the src vector
5476             NumElems,            // Number of elements in vector
5477             OpSrc))              // Which source operand ?
5478     return false;
5479
5480   isLeft = false;
5481   ShAmt = NumZeros;
5482   ShVal = SVOp->getOperand(OpSrc);
5483   return true;
5484 }
5485
5486 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5487 /// logical left shift of a vector.
5488 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5489                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5490   unsigned NumElems =
5491     SVOp->getSimpleValueType(0).getVectorNumElements();
5492   unsigned NumZeros = getNumOfConsecutiveZeros(
5493       SVOp, NumElems, true /* check zeros from left */, DAG,
5494       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5495   unsigned OpSrc;
5496
5497   if (!NumZeros)
5498     return false;
5499
5500   // Considering the elements in the mask that are not consecutive zeros,
5501   // check if they consecutively come from only one of the source vectors.
5502   //
5503   //                           0    { A, B, X, X } = V2
5504   //                          / \    /  /
5505   //   vector_shuffle V1, V2 <X, X, 4, 5>
5506   //
5507   if (!isShuffleMaskConsecutive(SVOp,
5508             NumZeros,     // Mask Start Index
5509             NumElems,     // Mask End Index(exclusive)
5510             0,            // Where to start looking in the src vector
5511             NumElems,     // Number of elements in vector
5512             OpSrc))       // Which source operand ?
5513     return false;
5514
5515   isLeft = true;
5516   ShAmt = NumZeros;
5517   ShVal = SVOp->getOperand(OpSrc);
5518   return true;
5519 }
5520
5521 /// isVectorShift - Returns true if the shuffle can be implemented as a
5522 /// logical left or right shift of a vector.
5523 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5524                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5525   // Although the logic below support any bitwidth size, there are no
5526   // shift instructions which handle more than 128-bit vectors.
5527   if (!SVOp->getSimpleValueType(0).is128BitVector())
5528     return false;
5529
5530   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5531       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5532     return true;
5533
5534   return false;
5535 }
5536
5537 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5538 ///
5539 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5540                                        unsigned NumNonZero, unsigned NumZero,
5541                                        SelectionDAG &DAG,
5542                                        const X86Subtarget* Subtarget,
5543                                        const TargetLowering &TLI) {
5544   if (NumNonZero > 8)
5545     return SDValue();
5546
5547   SDLoc dl(Op);
5548   SDValue V;
5549   bool First = true;
5550   for (unsigned i = 0; i < 16; ++i) {
5551     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5552     if (ThisIsNonZero && First) {
5553       if (NumZero)
5554         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5555       else
5556         V = DAG.getUNDEF(MVT::v8i16);
5557       First = false;
5558     }
5559
5560     if ((i & 1) != 0) {
5561       SDValue ThisElt, LastElt;
5562       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5563       if (LastIsNonZero) {
5564         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5565                               MVT::i16, Op.getOperand(i-1));
5566       }
5567       if (ThisIsNonZero) {
5568         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5569         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5570                               ThisElt, DAG.getConstant(8, MVT::i8));
5571         if (LastIsNonZero)
5572           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5573       } else
5574         ThisElt = LastElt;
5575
5576       if (ThisElt.getNode())
5577         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5578                         DAG.getIntPtrConstant(i/2));
5579     }
5580   }
5581
5582   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5583 }
5584
5585 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5586 ///
5587 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5588                                      unsigned NumNonZero, unsigned NumZero,
5589                                      SelectionDAG &DAG,
5590                                      const X86Subtarget* Subtarget,
5591                                      const TargetLowering &TLI) {
5592   if (NumNonZero > 4)
5593     return SDValue();
5594
5595   SDLoc dl(Op);
5596   SDValue V;
5597   bool First = true;
5598   for (unsigned i = 0; i < 8; ++i) {
5599     bool isNonZero = (NonZeros & (1 << i)) != 0;
5600     if (isNonZero) {
5601       if (First) {
5602         if (NumZero)
5603           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5604         else
5605           V = DAG.getUNDEF(MVT::v8i16);
5606         First = false;
5607       }
5608       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5609                       MVT::v8i16, V, Op.getOperand(i),
5610                       DAG.getIntPtrConstant(i));
5611     }
5612   }
5613
5614   return V;
5615 }
5616
5617 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5618 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5619                                      unsigned NonZeros, unsigned NumNonZero,
5620                                      unsigned NumZero, SelectionDAG &DAG,
5621                                      const X86Subtarget *Subtarget,
5622                                      const TargetLowering &TLI) {
5623   // We know there's at least one non-zero element
5624   unsigned FirstNonZeroIdx = 0;
5625   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5626   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5627          X86::isZeroNode(FirstNonZero)) {
5628     ++FirstNonZeroIdx;
5629     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5630   }
5631
5632   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5633       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5634     return SDValue();
5635
5636   SDValue V = FirstNonZero.getOperand(0);
5637   MVT VVT = V.getSimpleValueType();
5638   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5639     return SDValue();
5640
5641   unsigned FirstNonZeroDst =
5642       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5643   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5644   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5645   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5646
5647   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5648     SDValue Elem = Op.getOperand(Idx);
5649     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5650       continue;
5651
5652     // TODO: What else can be here? Deal with it.
5653     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5654       return SDValue();
5655
5656     // TODO: Some optimizations are still possible here
5657     // ex: Getting one element from a vector, and the rest from another.
5658     if (Elem.getOperand(0) != V)
5659       return SDValue();
5660
5661     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5662     if (Dst == Idx)
5663       ++CorrectIdx;
5664     else if (IncorrectIdx == -1U) {
5665       IncorrectIdx = Idx;
5666       IncorrectDst = Dst;
5667     } else
5668       // There was already one element with an incorrect index.
5669       // We can't optimize this case to an insertps.
5670       return SDValue();
5671   }
5672
5673   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5674     SDLoc dl(Op);
5675     EVT VT = Op.getSimpleValueType();
5676     unsigned ElementMoveMask = 0;
5677     if (IncorrectIdx == -1U)
5678       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5679     else
5680       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5681
5682     SDValue InsertpsMask =
5683         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5684     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5685   }
5686
5687   return SDValue();
5688 }
5689
5690 /// getVShift - Return a vector logical shift node.
5691 ///
5692 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5693                          unsigned NumBits, SelectionDAG &DAG,
5694                          const TargetLowering &TLI, SDLoc dl) {
5695   assert(VT.is128BitVector() && "Unknown type for VShift");
5696   EVT ShVT = MVT::v2i64;
5697   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5698   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5699   return DAG.getNode(ISD::BITCAST, dl, VT,
5700                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5701                              DAG.getConstant(NumBits,
5702                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5703 }
5704
5705 static SDValue
5706 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5707
5708   // Check if the scalar load can be widened into a vector load. And if
5709   // the address is "base + cst" see if the cst can be "absorbed" into
5710   // the shuffle mask.
5711   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5712     SDValue Ptr = LD->getBasePtr();
5713     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5714       return SDValue();
5715     EVT PVT = LD->getValueType(0);
5716     if (PVT != MVT::i32 && PVT != MVT::f32)
5717       return SDValue();
5718
5719     int FI = -1;
5720     int64_t Offset = 0;
5721     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5722       FI = FINode->getIndex();
5723       Offset = 0;
5724     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5725                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5726       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5727       Offset = Ptr.getConstantOperandVal(1);
5728       Ptr = Ptr.getOperand(0);
5729     } else {
5730       return SDValue();
5731     }
5732
5733     // FIXME: 256-bit vector instructions don't require a strict alignment,
5734     // improve this code to support it better.
5735     unsigned RequiredAlign = VT.getSizeInBits()/8;
5736     SDValue Chain = LD->getChain();
5737     // Make sure the stack object alignment is at least 16 or 32.
5738     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5739     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5740       if (MFI->isFixedObjectIndex(FI)) {
5741         // Can't change the alignment. FIXME: It's possible to compute
5742         // the exact stack offset and reference FI + adjust offset instead.
5743         // If someone *really* cares about this. That's the way to implement it.
5744         return SDValue();
5745       } else {
5746         MFI->setObjectAlignment(FI, RequiredAlign);
5747       }
5748     }
5749
5750     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5751     // Ptr + (Offset & ~15).
5752     if (Offset < 0)
5753       return SDValue();
5754     if ((Offset % RequiredAlign) & 3)
5755       return SDValue();
5756     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5757     if (StartOffset)
5758       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5759                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5760
5761     int EltNo = (Offset - StartOffset) >> 2;
5762     unsigned NumElems = VT.getVectorNumElements();
5763
5764     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5765     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5766                              LD->getPointerInfo().getWithOffset(StartOffset),
5767                              false, false, false, 0);
5768
5769     SmallVector<int, 8> Mask;
5770     for (unsigned i = 0; i != NumElems; ++i)
5771       Mask.push_back(EltNo);
5772
5773     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5774   }
5775
5776   return SDValue();
5777 }
5778
5779 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5780 /// vector of type 'VT', see if the elements can be replaced by a single large
5781 /// load which has the same value as a build_vector whose operands are 'elts'.
5782 ///
5783 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5784 ///
5785 /// FIXME: we'd also like to handle the case where the last elements are zero
5786 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5787 /// There's even a handy isZeroNode for that purpose.
5788 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5789                                         SDLoc &DL, SelectionDAG &DAG,
5790                                         bool isAfterLegalize) {
5791   EVT EltVT = VT.getVectorElementType();
5792   unsigned NumElems = Elts.size();
5793
5794   LoadSDNode *LDBase = nullptr;
5795   unsigned LastLoadedElt = -1U;
5796
5797   // For each element in the initializer, see if we've found a load or an undef.
5798   // If we don't find an initial load element, or later load elements are
5799   // non-consecutive, bail out.
5800   for (unsigned i = 0; i < NumElems; ++i) {
5801     SDValue Elt = Elts[i];
5802
5803     if (!Elt.getNode() ||
5804         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5805       return SDValue();
5806     if (!LDBase) {
5807       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5808         return SDValue();
5809       LDBase = cast<LoadSDNode>(Elt.getNode());
5810       LastLoadedElt = i;
5811       continue;
5812     }
5813     if (Elt.getOpcode() == ISD::UNDEF)
5814       continue;
5815
5816     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5817     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5818       return SDValue();
5819     LastLoadedElt = i;
5820   }
5821
5822   // If we have found an entire vector of loads and undefs, then return a large
5823   // load of the entire vector width starting at the base pointer.  If we found
5824   // consecutive loads for the low half, generate a vzext_load node.
5825   if (LastLoadedElt == NumElems - 1) {
5826
5827     if (isAfterLegalize &&
5828         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5829       return SDValue();
5830
5831     SDValue NewLd = SDValue();
5832
5833     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5834       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5835                           LDBase->getPointerInfo(),
5836                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5837                           LDBase->isInvariant(), 0);
5838     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5839                         LDBase->getPointerInfo(),
5840                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5841                         LDBase->isInvariant(), LDBase->getAlignment());
5842
5843     if (LDBase->hasAnyUseOfValue(1)) {
5844       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5845                                      SDValue(LDBase, 1),
5846                                      SDValue(NewLd.getNode(), 1));
5847       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5848       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5849                              SDValue(NewLd.getNode(), 1));
5850     }
5851
5852     return NewLd;
5853   }
5854   if (NumElems == 4 && LastLoadedElt == 1 &&
5855       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5856     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5857     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5858     SDValue ResNode =
5859         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5860                                 LDBase->getPointerInfo(),
5861                                 LDBase->getAlignment(),
5862                                 false/*isVolatile*/, true/*ReadMem*/,
5863                                 false/*WriteMem*/);
5864
5865     // Make sure the newly-created LOAD is in the same position as LDBase in
5866     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5867     // update uses of LDBase's output chain to use the TokenFactor.
5868     if (LDBase->hasAnyUseOfValue(1)) {
5869       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5870                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5871       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5872       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5873                              SDValue(ResNode.getNode(), 1));
5874     }
5875
5876     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5877   }
5878   return SDValue();
5879 }
5880
5881 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5882 /// to generate a splat value for the following cases:
5883 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5884 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5885 /// a scalar load, or a constant.
5886 /// The VBROADCAST node is returned when a pattern is found,
5887 /// or SDValue() otherwise.
5888 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5889                                     SelectionDAG &DAG) {
5890   if (!Subtarget->hasFp256())
5891     return SDValue();
5892
5893   MVT VT = Op.getSimpleValueType();
5894   SDLoc dl(Op);
5895
5896   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5897          "Unsupported vector type for broadcast.");
5898
5899   SDValue Ld;
5900   bool ConstSplatVal;
5901
5902   switch (Op.getOpcode()) {
5903     default:
5904       // Unknown pattern found.
5905       return SDValue();
5906
5907     case ISD::BUILD_VECTOR: {
5908       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5909       BitVector UndefElements;
5910       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5911
5912       // We need a splat of a single value to use broadcast, and it doesn't
5913       // make any sense if the value is only in one element of the vector.
5914       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5915         return SDValue();
5916
5917       Ld = Splat;
5918       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5919                        Ld.getOpcode() == ISD::ConstantFP);
5920
5921       // Make sure that all of the users of a non-constant load are from the
5922       // BUILD_VECTOR node.
5923       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5924         return SDValue();
5925       break;
5926     }
5927
5928     case ISD::VECTOR_SHUFFLE: {
5929       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5930
5931       // Shuffles must have a splat mask where the first element is
5932       // broadcasted.
5933       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5934         return SDValue();
5935
5936       SDValue Sc = Op.getOperand(0);
5937       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5938           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5939
5940         if (!Subtarget->hasInt256())
5941           return SDValue();
5942
5943         // Use the register form of the broadcast instruction available on AVX2.
5944         if (VT.getSizeInBits() >= 256)
5945           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5946         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5947       }
5948
5949       Ld = Sc.getOperand(0);
5950       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5951                        Ld.getOpcode() == ISD::ConstantFP);
5952
5953       // The scalar_to_vector node and the suspected
5954       // load node must have exactly one user.
5955       // Constants may have multiple users.
5956
5957       // AVX-512 has register version of the broadcast
5958       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5959         Ld.getValueType().getSizeInBits() >= 32;
5960       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5961           !hasRegVer))
5962         return SDValue();
5963       break;
5964     }
5965   }
5966
5967   bool IsGE256 = (VT.getSizeInBits() >= 256);
5968
5969   // Handle the broadcasting a single constant scalar from the constant pool
5970   // into a vector. On Sandybridge it is still better to load a constant vector
5971   // from the constant pool and not to broadcast it from a scalar.
5972   if (ConstSplatVal && Subtarget->hasInt256()) {
5973     EVT CVT = Ld.getValueType();
5974     assert(!CVT.isVector() && "Must not broadcast a vector type");
5975     unsigned ScalarSize = CVT.getSizeInBits();
5976
5977     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5978       const Constant *C = nullptr;
5979       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5980         C = CI->getConstantIntValue();
5981       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5982         C = CF->getConstantFPValue();
5983
5984       assert(C && "Invalid constant type");
5985
5986       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5987       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5988       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5989       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5990                        MachinePointerInfo::getConstantPool(),
5991                        false, false, false, Alignment);
5992
5993       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5994     }
5995   }
5996
5997   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5998   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5999
6000   // Handle AVX2 in-register broadcasts.
6001   if (!IsLoad && Subtarget->hasInt256() &&
6002       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6003     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6004
6005   // The scalar source must be a normal load.
6006   if (!IsLoad)
6007     return SDValue();
6008
6009   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6010     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6011
6012   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6013   // double since there is no vbroadcastsd xmm
6014   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6015     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6016       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6017   }
6018
6019   // Unsupported broadcast.
6020   return SDValue();
6021 }
6022
6023 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6024 /// underlying vector and index.
6025 ///
6026 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6027 /// index.
6028 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6029                                          SDValue ExtIdx) {
6030   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6031   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6032     return Idx;
6033
6034   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6035   // lowered this:
6036   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6037   // to:
6038   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6039   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6040   //                           undef)
6041   //                       Constant<0>)
6042   // In this case the vector is the extract_subvector expression and the index
6043   // is 2, as specified by the shuffle.
6044   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6045   SDValue ShuffleVec = SVOp->getOperand(0);
6046   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6047   assert(ShuffleVecVT.getVectorElementType() ==
6048          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6049
6050   int ShuffleIdx = SVOp->getMaskElt(Idx);
6051   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6052     ExtractedFromVec = ShuffleVec;
6053     return ShuffleIdx;
6054   }
6055   return Idx;
6056 }
6057
6058 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6059   MVT VT = Op.getSimpleValueType();
6060
6061   // Skip if insert_vec_elt is not supported.
6062   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6063   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6064     return SDValue();
6065
6066   SDLoc DL(Op);
6067   unsigned NumElems = Op.getNumOperands();
6068
6069   SDValue VecIn1;
6070   SDValue VecIn2;
6071   SmallVector<unsigned, 4> InsertIndices;
6072   SmallVector<int, 8> Mask(NumElems, -1);
6073
6074   for (unsigned i = 0; i != NumElems; ++i) {
6075     unsigned Opc = Op.getOperand(i).getOpcode();
6076
6077     if (Opc == ISD::UNDEF)
6078       continue;
6079
6080     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6081       // Quit if more than 1 elements need inserting.
6082       if (InsertIndices.size() > 1)
6083         return SDValue();
6084
6085       InsertIndices.push_back(i);
6086       continue;
6087     }
6088
6089     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6090     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6091     // Quit if non-constant index.
6092     if (!isa<ConstantSDNode>(ExtIdx))
6093       return SDValue();
6094     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6095
6096     // Quit if extracted from vector of different type.
6097     if (ExtractedFromVec.getValueType() != VT)
6098       return SDValue();
6099
6100     if (!VecIn1.getNode())
6101       VecIn1 = ExtractedFromVec;
6102     else if (VecIn1 != ExtractedFromVec) {
6103       if (!VecIn2.getNode())
6104         VecIn2 = ExtractedFromVec;
6105       else if (VecIn2 != ExtractedFromVec)
6106         // Quit if more than 2 vectors to shuffle
6107         return SDValue();
6108     }
6109
6110     if (ExtractedFromVec == VecIn1)
6111       Mask[i] = Idx;
6112     else if (ExtractedFromVec == VecIn2)
6113       Mask[i] = Idx + NumElems;
6114   }
6115
6116   if (!VecIn1.getNode())
6117     return SDValue();
6118
6119   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6120   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6121   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6122     unsigned Idx = InsertIndices[i];
6123     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6124                      DAG.getIntPtrConstant(Idx));
6125   }
6126
6127   return NV;
6128 }
6129
6130 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6131 SDValue
6132 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6133
6134   MVT VT = Op.getSimpleValueType();
6135   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6136          "Unexpected type in LowerBUILD_VECTORvXi1!");
6137
6138   SDLoc dl(Op);
6139   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6140     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6141     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6142     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6143   }
6144
6145   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6146     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6147     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6148     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6149   }
6150
6151   bool AllContants = true;
6152   uint64_t Immediate = 0;
6153   int NonConstIdx = -1;
6154   bool IsSplat = true;
6155   unsigned NumNonConsts = 0;
6156   unsigned NumConsts = 0;
6157   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6158     SDValue In = Op.getOperand(idx);
6159     if (In.getOpcode() == ISD::UNDEF)
6160       continue;
6161     if (!isa<ConstantSDNode>(In)) {
6162       AllContants = false;
6163       NonConstIdx = idx;
6164       NumNonConsts++;
6165     }
6166     else {
6167       NumConsts++;
6168       if (cast<ConstantSDNode>(In)->getZExtValue())
6169       Immediate |= (1ULL << idx);
6170     }
6171     if (In != Op.getOperand(0))
6172       IsSplat = false;
6173   }
6174
6175   if (AllContants) {
6176     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6177       DAG.getConstant(Immediate, MVT::i16));
6178     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6179                        DAG.getIntPtrConstant(0));
6180   }
6181
6182   if (NumNonConsts == 1 && NonConstIdx != 0) {
6183     SDValue DstVec;
6184     if (NumConsts) {
6185       SDValue VecAsImm = DAG.getConstant(Immediate,
6186                                          MVT::getIntegerVT(VT.getSizeInBits()));
6187       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6188     }
6189     else 
6190       DstVec = DAG.getUNDEF(VT);
6191     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6192                        Op.getOperand(NonConstIdx),
6193                        DAG.getIntPtrConstant(NonConstIdx));
6194   }
6195   if (!IsSplat && (NonConstIdx != 0))
6196     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6197   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6198   SDValue Select;
6199   if (IsSplat)
6200     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6201                           DAG.getConstant(-1, SelectVT),
6202                           DAG.getConstant(0, SelectVT));
6203   else
6204     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6205                          DAG.getConstant((Immediate | 1), SelectVT),
6206                          DAG.getConstant(Immediate, SelectVT));
6207   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6208 }
6209
6210 /// \brief Return true if \p N implements a horizontal binop and return the
6211 /// operands for the horizontal binop into V0 and V1.
6212 /// 
6213 /// This is a helper function of PerformBUILD_VECTORCombine.
6214 /// This function checks that the build_vector \p N in input implements a
6215 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6216 /// operation to match.
6217 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6218 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6219 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6220 /// arithmetic sub.
6221 ///
6222 /// This function only analyzes elements of \p N whose indices are
6223 /// in range [BaseIdx, LastIdx).
6224 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6225                               SelectionDAG &DAG,
6226                               unsigned BaseIdx, unsigned LastIdx,
6227                               SDValue &V0, SDValue &V1) {
6228   EVT VT = N->getValueType(0);
6229
6230   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6231   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6232          "Invalid Vector in input!");
6233   
6234   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6235   bool CanFold = true;
6236   unsigned ExpectedVExtractIdx = BaseIdx;
6237   unsigned NumElts = LastIdx - BaseIdx;
6238   V0 = DAG.getUNDEF(VT);
6239   V1 = DAG.getUNDEF(VT);
6240
6241   // Check if N implements a horizontal binop.
6242   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6243     SDValue Op = N->getOperand(i + BaseIdx);
6244
6245     // Skip UNDEFs.
6246     if (Op->getOpcode() == ISD::UNDEF) {
6247       // Update the expected vector extract index.
6248       if (i * 2 == NumElts)
6249         ExpectedVExtractIdx = BaseIdx;
6250       ExpectedVExtractIdx += 2;
6251       continue;
6252     }
6253
6254     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6255
6256     if (!CanFold)
6257       break;
6258
6259     SDValue Op0 = Op.getOperand(0);
6260     SDValue Op1 = Op.getOperand(1);
6261
6262     // Try to match the following pattern:
6263     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6264     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6265         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6266         Op0.getOperand(0) == Op1.getOperand(0) &&
6267         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6268         isa<ConstantSDNode>(Op1.getOperand(1)));
6269     if (!CanFold)
6270       break;
6271
6272     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6273     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6274
6275     if (i * 2 < NumElts) {
6276       if (V0.getOpcode() == ISD::UNDEF)
6277         V0 = Op0.getOperand(0);
6278     } else {
6279       if (V1.getOpcode() == ISD::UNDEF)
6280         V1 = Op0.getOperand(0);
6281       if (i * 2 == NumElts)
6282         ExpectedVExtractIdx = BaseIdx;
6283     }
6284
6285     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6286     if (I0 == ExpectedVExtractIdx)
6287       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6288     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6289       // Try to match the following dag sequence:
6290       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6291       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6292     } else
6293       CanFold = false;
6294
6295     ExpectedVExtractIdx += 2;
6296   }
6297
6298   return CanFold;
6299 }
6300
6301 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6302 /// a concat_vector. 
6303 ///
6304 /// This is a helper function of PerformBUILD_VECTORCombine.
6305 /// This function expects two 256-bit vectors called V0 and V1.
6306 /// At first, each vector is split into two separate 128-bit vectors.
6307 /// Then, the resulting 128-bit vectors are used to implement two
6308 /// horizontal binary operations. 
6309 ///
6310 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6311 ///
6312 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6313 /// the two new horizontal binop.
6314 /// When Mode is set, the first horizontal binop dag node would take as input
6315 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6316 /// horizontal binop dag node would take as input the lower 128-bit of V1
6317 /// and the upper 128-bit of V1.
6318 ///   Example:
6319 ///     HADD V0_LO, V0_HI
6320 ///     HADD V1_LO, V1_HI
6321 ///
6322 /// Otherwise, the first horizontal binop dag node takes as input the lower
6323 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6324 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6325 ///   Example:
6326 ///     HADD V0_LO, V1_LO
6327 ///     HADD V0_HI, V1_HI
6328 ///
6329 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6330 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6331 /// the upper 128-bits of the result.
6332 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6333                                      SDLoc DL, SelectionDAG &DAG,
6334                                      unsigned X86Opcode, bool Mode,
6335                                      bool isUndefLO, bool isUndefHI) {
6336   EVT VT = V0.getValueType();
6337   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6338          "Invalid nodes in input!");
6339
6340   unsigned NumElts = VT.getVectorNumElements();
6341   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6342   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6343   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6344   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6345   EVT NewVT = V0_LO.getValueType();
6346
6347   SDValue LO = DAG.getUNDEF(NewVT);
6348   SDValue HI = DAG.getUNDEF(NewVT);
6349
6350   if (Mode) {
6351     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6352     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6353       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6354     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6355       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6356   } else {
6357     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6358     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6359                        V1_LO->getOpcode() != ISD::UNDEF))
6360       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6361
6362     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6363                        V1_HI->getOpcode() != ISD::UNDEF))
6364       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6365   }
6366
6367   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6368 }
6369
6370 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6371 /// sequence of 'vadd + vsub + blendi'.
6372 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6373                            const X86Subtarget *Subtarget) {
6374   SDLoc DL(BV);
6375   EVT VT = BV->getValueType(0);
6376   unsigned NumElts = VT.getVectorNumElements();
6377   SDValue InVec0 = DAG.getUNDEF(VT);
6378   SDValue InVec1 = DAG.getUNDEF(VT);
6379
6380   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6381           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6382
6383   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6384   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6385   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6386     return SDValue();
6387
6388   // Odd-numbered elements in the input build vector are obtained from
6389   // adding two integer/float elements.
6390   // Even-numbered elements in the input build vector are obtained from
6391   // subtracting two integer/float elements.
6392   unsigned ExpectedOpcode = ISD::FSUB;
6393   unsigned NextExpectedOpcode = ISD::FADD;
6394   bool AddFound = false;
6395   bool SubFound = false;
6396
6397   for (unsigned i = 0, e = NumElts; i != e; i++) {
6398     SDValue Op = BV->getOperand(i);
6399       
6400     // Skip 'undef' values.
6401     unsigned Opcode = Op.getOpcode();
6402     if (Opcode == ISD::UNDEF) {
6403       std::swap(ExpectedOpcode, NextExpectedOpcode);
6404       continue;
6405     }
6406       
6407     // Early exit if we found an unexpected opcode.
6408     if (Opcode != ExpectedOpcode)
6409       return SDValue();
6410
6411     SDValue Op0 = Op.getOperand(0);
6412     SDValue Op1 = Op.getOperand(1);
6413
6414     // Try to match the following pattern:
6415     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6416     // Early exit if we cannot match that sequence.
6417     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6418         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6419         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6420         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6421         Op0.getOperand(1) != Op1.getOperand(1))
6422       return SDValue();
6423
6424     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6425     if (I0 != i)
6426       return SDValue();
6427
6428     // We found a valid add/sub node. Update the information accordingly.
6429     if (i & 1)
6430       AddFound = true;
6431     else
6432       SubFound = true;
6433
6434     // Update InVec0 and InVec1.
6435     if (InVec0.getOpcode() == ISD::UNDEF)
6436       InVec0 = Op0.getOperand(0);
6437     if (InVec1.getOpcode() == ISD::UNDEF)
6438       InVec1 = Op1.getOperand(0);
6439
6440     // Make sure that operands in input to each add/sub node always
6441     // come from a same pair of vectors.
6442     if (InVec0 != Op0.getOperand(0)) {
6443       if (ExpectedOpcode == ISD::FSUB)
6444         return SDValue();
6445
6446       // FADD is commutable. Try to commute the operands
6447       // and then test again.
6448       std::swap(Op0, Op1);
6449       if (InVec0 != Op0.getOperand(0))
6450         return SDValue();
6451     }
6452
6453     if (InVec1 != Op1.getOperand(0))
6454       return SDValue();
6455
6456     // Update the pair of expected opcodes.
6457     std::swap(ExpectedOpcode, NextExpectedOpcode);
6458   }
6459
6460   // Don't try to fold this build_vector into a VSELECT if it has
6461   // too many UNDEF operands.
6462   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6463       InVec1.getOpcode() != ISD::UNDEF) {
6464     // Emit a sequence of vector add and sub followed by a VSELECT.
6465     // The new VSELECT will be lowered into a BLENDI.
6466     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6467     // and emit a single ADDSUB instruction.
6468     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6469     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6470
6471     // Construct the VSELECT mask.
6472     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6473     EVT SVT = MaskVT.getVectorElementType();
6474     unsigned SVTBits = SVT.getSizeInBits();
6475     SmallVector<SDValue, 8> Ops;
6476
6477     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6478       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6479                             APInt::getAllOnesValue(SVTBits);
6480       SDValue Constant = DAG.getConstant(Value, SVT);
6481       Ops.push_back(Constant);
6482     }
6483
6484     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6485     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6486   }
6487   
6488   return SDValue();
6489 }
6490
6491 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6492                                           const X86Subtarget *Subtarget) {
6493   SDLoc DL(N);
6494   EVT VT = N->getValueType(0);
6495   unsigned NumElts = VT.getVectorNumElements();
6496   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6497   SDValue InVec0, InVec1;
6498
6499   // Try to match an ADDSUB.
6500   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6501       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6502     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6503     if (Value.getNode())
6504       return Value;
6505   }
6506
6507   // Try to match horizontal ADD/SUB.
6508   unsigned NumUndefsLO = 0;
6509   unsigned NumUndefsHI = 0;
6510   unsigned Half = NumElts/2;
6511
6512   // Count the number of UNDEF operands in the build_vector in input.
6513   for (unsigned i = 0, e = Half; i != e; ++i)
6514     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6515       NumUndefsLO++;
6516
6517   for (unsigned i = Half, e = NumElts; i != e; ++i)
6518     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6519       NumUndefsHI++;
6520
6521   // Early exit if this is either a build_vector of all UNDEFs or all the
6522   // operands but one are UNDEF.
6523   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6524     return SDValue();
6525
6526   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6527     // Try to match an SSE3 float HADD/HSUB.
6528     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6529       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6530     
6531     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6532       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6533   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6534     // Try to match an SSSE3 integer HADD/HSUB.
6535     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6536       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6537     
6538     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6539       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6540   }
6541   
6542   if (!Subtarget->hasAVX())
6543     return SDValue();
6544
6545   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6546     // Try to match an AVX horizontal add/sub of packed single/double
6547     // precision floating point values from 256-bit vectors.
6548     SDValue InVec2, InVec3;
6549     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6550         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6551         ((InVec0.getOpcode() == ISD::UNDEF ||
6552           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6553         ((InVec1.getOpcode() == ISD::UNDEF ||
6554           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6555       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6556
6557     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6558         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6559         ((InVec0.getOpcode() == ISD::UNDEF ||
6560           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6561         ((InVec1.getOpcode() == ISD::UNDEF ||
6562           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6563       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6564   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6565     // Try to match an AVX2 horizontal add/sub of signed integers.
6566     SDValue InVec2, InVec3;
6567     unsigned X86Opcode;
6568     bool CanFold = true;
6569
6570     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6571         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6572         ((InVec0.getOpcode() == ISD::UNDEF ||
6573           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6574         ((InVec1.getOpcode() == ISD::UNDEF ||
6575           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6576       X86Opcode = X86ISD::HADD;
6577     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6578         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6579         ((InVec0.getOpcode() == ISD::UNDEF ||
6580           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6581         ((InVec1.getOpcode() == ISD::UNDEF ||
6582           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6583       X86Opcode = X86ISD::HSUB;
6584     else
6585       CanFold = false;
6586
6587     if (CanFold) {
6588       // Fold this build_vector into a single horizontal add/sub.
6589       // Do this only if the target has AVX2.
6590       if (Subtarget->hasAVX2())
6591         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6592  
6593       // Do not try to expand this build_vector into a pair of horizontal
6594       // add/sub if we can emit a pair of scalar add/sub.
6595       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6596         return SDValue();
6597
6598       // Convert this build_vector into a pair of horizontal binop followed by
6599       // a concat vector.
6600       bool isUndefLO = NumUndefsLO == Half;
6601       bool isUndefHI = NumUndefsHI == Half;
6602       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6603                                    isUndefLO, isUndefHI);
6604     }
6605   }
6606
6607   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6608        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6609     unsigned X86Opcode;
6610     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6611       X86Opcode = X86ISD::HADD;
6612     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6613       X86Opcode = X86ISD::HSUB;
6614     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6615       X86Opcode = X86ISD::FHADD;
6616     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6617       X86Opcode = X86ISD::FHSUB;
6618     else
6619       return SDValue();
6620
6621     // Don't try to expand this build_vector into a pair of horizontal add/sub
6622     // if we can simply emit a pair of scalar add/sub.
6623     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6624       return SDValue();
6625
6626     // Convert this build_vector into two horizontal add/sub followed by
6627     // a concat vector.
6628     bool isUndefLO = NumUndefsLO == Half;
6629     bool isUndefHI = NumUndefsHI == Half;
6630     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6631                                  isUndefLO, isUndefHI);
6632   }
6633
6634   return SDValue();
6635 }
6636
6637 SDValue
6638 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6639   SDLoc dl(Op);
6640
6641   MVT VT = Op.getSimpleValueType();
6642   MVT ExtVT = VT.getVectorElementType();
6643   unsigned NumElems = Op.getNumOperands();
6644
6645   // Generate vectors for predicate vectors.
6646   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6647     return LowerBUILD_VECTORvXi1(Op, DAG);
6648
6649   // Vectors containing all zeros can be matched by pxor and xorps later
6650   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6651     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6652     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6653     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6654       return Op;
6655
6656     return getZeroVector(VT, Subtarget, DAG, dl);
6657   }
6658
6659   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6660   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6661   // vpcmpeqd on 256-bit vectors.
6662   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6663     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6664       return Op;
6665
6666     if (!VT.is512BitVector())
6667       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6668   }
6669
6670   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6671   if (Broadcast.getNode())
6672     return Broadcast;
6673
6674   unsigned EVTBits = ExtVT.getSizeInBits();
6675
6676   unsigned NumZero  = 0;
6677   unsigned NumNonZero = 0;
6678   unsigned NonZeros = 0;
6679   bool IsAllConstants = true;
6680   SmallSet<SDValue, 8> Values;
6681   for (unsigned i = 0; i < NumElems; ++i) {
6682     SDValue Elt = Op.getOperand(i);
6683     if (Elt.getOpcode() == ISD::UNDEF)
6684       continue;
6685     Values.insert(Elt);
6686     if (Elt.getOpcode() != ISD::Constant &&
6687         Elt.getOpcode() != ISD::ConstantFP)
6688       IsAllConstants = false;
6689     if (X86::isZeroNode(Elt))
6690       NumZero++;
6691     else {
6692       NonZeros |= (1 << i);
6693       NumNonZero++;
6694     }
6695   }
6696
6697   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6698   if (NumNonZero == 0)
6699     return DAG.getUNDEF(VT);
6700
6701   // Special case for single non-zero, non-undef, element.
6702   if (NumNonZero == 1) {
6703     unsigned Idx = countTrailingZeros(NonZeros);
6704     SDValue Item = Op.getOperand(Idx);
6705
6706     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6707     // the value are obviously zero, truncate the value to i32 and do the
6708     // insertion that way.  Only do this if the value is non-constant or if the
6709     // value is a constant being inserted into element 0.  It is cheaper to do
6710     // a constant pool load than it is to do a movd + shuffle.
6711     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6712         (!IsAllConstants || Idx == 0)) {
6713       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6714         // Handle SSE only.
6715         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6716         EVT VecVT = MVT::v4i32;
6717         unsigned VecElts = 4;
6718
6719         // Truncate the value (which may itself be a constant) to i32, and
6720         // convert it to a vector with movd (S2V+shuffle to zero extend).
6721         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6722         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6723         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6724
6725         // Now we have our 32-bit value zero extended in the low element of
6726         // a vector.  If Idx != 0, swizzle it into place.
6727         if (Idx != 0) {
6728           SmallVector<int, 4> Mask;
6729           Mask.push_back(Idx);
6730           for (unsigned i = 1; i != VecElts; ++i)
6731             Mask.push_back(i);
6732           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6733                                       &Mask[0]);
6734         }
6735         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6736       }
6737     }
6738
6739     // If we have a constant or non-constant insertion into the low element of
6740     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6741     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6742     // depending on what the source datatype is.
6743     if (Idx == 0) {
6744       if (NumZero == 0)
6745         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6746
6747       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6748           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6749         if (VT.is256BitVector() || VT.is512BitVector()) {
6750           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6751           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6752                              Item, DAG.getIntPtrConstant(0));
6753         }
6754         assert(VT.is128BitVector() && "Expected an SSE value type!");
6755         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6756         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6757         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6758       }
6759
6760       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6761         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6762         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6763         if (VT.is256BitVector()) {
6764           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6765           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6766         } else {
6767           assert(VT.is128BitVector() && "Expected an SSE value type!");
6768           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6769         }
6770         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6771       }
6772     }
6773
6774     // Is it a vector logical left shift?
6775     if (NumElems == 2 && Idx == 1 &&
6776         X86::isZeroNode(Op.getOperand(0)) &&
6777         !X86::isZeroNode(Op.getOperand(1))) {
6778       unsigned NumBits = VT.getSizeInBits();
6779       return getVShift(true, VT,
6780                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6781                                    VT, Op.getOperand(1)),
6782                        NumBits/2, DAG, *this, dl);
6783     }
6784
6785     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6786       return SDValue();
6787
6788     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6789     // is a non-constant being inserted into an element other than the low one,
6790     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6791     // movd/movss) to move this into the low element, then shuffle it into
6792     // place.
6793     if (EVTBits == 32) {
6794       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6795
6796       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6797       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6798       SmallVector<int, 8> MaskVec;
6799       for (unsigned i = 0; i != NumElems; ++i)
6800         MaskVec.push_back(i == Idx ? 0 : 1);
6801       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6802     }
6803   }
6804
6805   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6806   if (Values.size() == 1) {
6807     if (EVTBits == 32) {
6808       // Instead of a shuffle like this:
6809       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6810       // Check if it's possible to issue this instead.
6811       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6812       unsigned Idx = countTrailingZeros(NonZeros);
6813       SDValue Item = Op.getOperand(Idx);
6814       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6815         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6816     }
6817     return SDValue();
6818   }
6819
6820   // A vector full of immediates; various special cases are already
6821   // handled, so this is best done with a single constant-pool load.
6822   if (IsAllConstants)
6823     return SDValue();
6824
6825   // For AVX-length vectors, build the individual 128-bit pieces and use
6826   // shuffles to put them in place.
6827   if (VT.is256BitVector() || VT.is512BitVector()) {
6828     SmallVector<SDValue, 64> V;
6829     for (unsigned i = 0; i != NumElems; ++i)
6830       V.push_back(Op.getOperand(i));
6831
6832     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6833
6834     // Build both the lower and upper subvector.
6835     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6836                                 makeArrayRef(&V[0], NumElems/2));
6837     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6838                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6839
6840     // Recreate the wider vector with the lower and upper part.
6841     if (VT.is256BitVector())
6842       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6843     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6844   }
6845
6846   // Let legalizer expand 2-wide build_vectors.
6847   if (EVTBits == 64) {
6848     if (NumNonZero == 1) {
6849       // One half is zero or undef.
6850       unsigned Idx = countTrailingZeros(NonZeros);
6851       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6852                                  Op.getOperand(Idx));
6853       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6854     }
6855     return SDValue();
6856   }
6857
6858   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6859   if (EVTBits == 8 && NumElems == 16) {
6860     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6861                                         Subtarget, *this);
6862     if (V.getNode()) return V;
6863   }
6864
6865   if (EVTBits == 16 && NumElems == 8) {
6866     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6867                                       Subtarget, *this);
6868     if (V.getNode()) return V;
6869   }
6870
6871   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6872   if (EVTBits == 32 && NumElems == 4) {
6873     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6874                                       NumZero, DAG, Subtarget, *this);
6875     if (V.getNode())
6876       return V;
6877   }
6878
6879   // If element VT is == 32 bits, turn it into a number of shuffles.
6880   SmallVector<SDValue, 8> V(NumElems);
6881   if (NumElems == 4 && NumZero > 0) {
6882     for (unsigned i = 0; i < 4; ++i) {
6883       bool isZero = !(NonZeros & (1 << i));
6884       if (isZero)
6885         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6886       else
6887         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6888     }
6889
6890     for (unsigned i = 0; i < 2; ++i) {
6891       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6892         default: break;
6893         case 0:
6894           V[i] = V[i*2];  // Must be a zero vector.
6895           break;
6896         case 1:
6897           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6898           break;
6899         case 2:
6900           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6901           break;
6902         case 3:
6903           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6904           break;
6905       }
6906     }
6907
6908     bool Reverse1 = (NonZeros & 0x3) == 2;
6909     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6910     int MaskVec[] = {
6911       Reverse1 ? 1 : 0,
6912       Reverse1 ? 0 : 1,
6913       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6914       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6915     };
6916     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6917   }
6918
6919   if (Values.size() > 1 && VT.is128BitVector()) {
6920     // Check for a build vector of consecutive loads.
6921     for (unsigned i = 0; i < NumElems; ++i)
6922       V[i] = Op.getOperand(i);
6923
6924     // Check for elements which are consecutive loads.
6925     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6926     if (LD.getNode())
6927       return LD;
6928
6929     // Check for a build vector from mostly shuffle plus few inserting.
6930     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6931     if (Sh.getNode())
6932       return Sh;
6933
6934     // For SSE 4.1, use insertps to put the high elements into the low element.
6935     if (getSubtarget()->hasSSE41()) {
6936       SDValue Result;
6937       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6938         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6939       else
6940         Result = DAG.getUNDEF(VT);
6941
6942       for (unsigned i = 1; i < NumElems; ++i) {
6943         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6944         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6945                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6946       }
6947       return Result;
6948     }
6949
6950     // Otherwise, expand into a number of unpckl*, start by extending each of
6951     // our (non-undef) elements to the full vector width with the element in the
6952     // bottom slot of the vector (which generates no code for SSE).
6953     for (unsigned i = 0; i < NumElems; ++i) {
6954       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6955         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6956       else
6957         V[i] = DAG.getUNDEF(VT);
6958     }
6959
6960     // Next, we iteratively mix elements, e.g. for v4f32:
6961     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6962     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6963     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6964     unsigned EltStride = NumElems >> 1;
6965     while (EltStride != 0) {
6966       for (unsigned i = 0; i < EltStride; ++i) {
6967         // If V[i+EltStride] is undef and this is the first round of mixing,
6968         // then it is safe to just drop this shuffle: V[i] is already in the
6969         // right place, the one element (since it's the first round) being
6970         // inserted as undef can be dropped.  This isn't safe for successive
6971         // rounds because they will permute elements within both vectors.
6972         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6973             EltStride == NumElems/2)
6974           continue;
6975
6976         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6977       }
6978       EltStride >>= 1;
6979     }
6980     return V[0];
6981   }
6982   return SDValue();
6983 }
6984
6985 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6986 // to create 256-bit vectors from two other 128-bit ones.
6987 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6988   SDLoc dl(Op);
6989   MVT ResVT = Op.getSimpleValueType();
6990
6991   assert((ResVT.is256BitVector() ||
6992           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6993
6994   SDValue V1 = Op.getOperand(0);
6995   SDValue V2 = Op.getOperand(1);
6996   unsigned NumElems = ResVT.getVectorNumElements();
6997   if(ResVT.is256BitVector())
6998     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6999
7000   if (Op.getNumOperands() == 4) {
7001     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7002                                 ResVT.getVectorNumElements()/2);
7003     SDValue V3 = Op.getOperand(2);
7004     SDValue V4 = Op.getOperand(3);
7005     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7006       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7007   }
7008   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7009 }
7010
7011 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7012   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7013   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7014          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7015           Op.getNumOperands() == 4)));
7016
7017   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7018   // from two other 128-bit ones.
7019
7020   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7021   return LowerAVXCONCAT_VECTORS(Op, DAG);
7022 }
7023
7024
7025 //===----------------------------------------------------------------------===//
7026 // Vector shuffle lowering
7027 //
7028 // This is an experimental code path for lowering vector shuffles on x86. It is
7029 // designed to handle arbitrary vector shuffles and blends, gracefully
7030 // degrading performance as necessary. It works hard to recognize idiomatic
7031 // shuffles and lower them to optimal instruction patterns without leaving
7032 // a framework that allows reasonably efficient handling of all vector shuffle
7033 // patterns.
7034 //===----------------------------------------------------------------------===//
7035
7036 /// \brief Tiny helper function to identify a no-op mask.
7037 ///
7038 /// This is a somewhat boring predicate function. It checks whether the mask
7039 /// array input, which is assumed to be a single-input shuffle mask of the kind
7040 /// used by the X86 shuffle instructions (not a fully general
7041 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7042 /// in-place shuffle are 'no-op's.
7043 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7044   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7045     if (Mask[i] != -1 && Mask[i] != i)
7046       return false;
7047   return true;
7048 }
7049
7050 /// \brief Helper function to classify a mask as a single-input mask.
7051 ///
7052 /// This isn't a generic single-input test because in the vector shuffle
7053 /// lowering we canonicalize single inputs to be the first input operand. This
7054 /// means we can more quickly test for a single input by only checking whether
7055 /// an input from the second operand exists. We also assume that the size of
7056 /// mask corresponds to the size of the input vectors which isn't true in the
7057 /// fully general case.
7058 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7059   for (int M : Mask)
7060     if (M >= (int)Mask.size())
7061       return false;
7062   return true;
7063 }
7064
7065 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7066 // 2013 will allow us to use it as a non-type template parameter.
7067 namespace {
7068
7069 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7070 ///
7071 /// See its documentation for details.
7072 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7073   if (Mask.size() != Args.size())
7074     return false;
7075   for (int i = 0, e = Mask.size(); i < e; ++i) {
7076     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7077     assert(*Args[i] < (int)Args.size() * 2 &&
7078            "Argument outside the range of possible shuffle inputs!");
7079     if (Mask[i] != -1 && Mask[i] != *Args[i])
7080       return false;
7081   }
7082   return true;
7083 }
7084
7085 } // namespace
7086
7087 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7088 /// arguments.
7089 ///
7090 /// This is a fast way to test a shuffle mask against a fixed pattern:
7091 ///
7092 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7093 ///
7094 /// It returns true if the mask is exactly as wide as the argument list, and
7095 /// each element of the mask is either -1 (signifying undef) or the value given
7096 /// in the argument.
7097 static const VariadicFunction1<
7098     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7099
7100 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7101 ///
7102 /// This helper function produces an 8-bit shuffle immediate corresponding to
7103 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7104 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7105 /// example.
7106 ///
7107 /// NB: We rely heavily on "undef" masks preserving the input lane.
7108 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7109                                           SelectionDAG &DAG) {
7110   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7111   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7112   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7113   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7114   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7115
7116   unsigned Imm = 0;
7117   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7118   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7119   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7120   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7121   return DAG.getConstant(Imm, MVT::i8);
7122 }
7123
7124 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7125 ///
7126 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7127 /// support for floating point shuffles but not integer shuffles. These
7128 /// instructions will incur a domain crossing penalty on some chips though so
7129 /// it is better to avoid lowering through this for integer vectors where
7130 /// possible.
7131 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7132                                        const X86Subtarget *Subtarget,
7133                                        SelectionDAG &DAG) {
7134   SDLoc DL(Op);
7135   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7136   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7137   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7138   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7139   ArrayRef<int> Mask = SVOp->getMask();
7140   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7141
7142   if (isSingleInputShuffleMask(Mask)) {
7143     // Straight shuffle of a single input vector. Simulate this by using the
7144     // single input as both of the "inputs" to this instruction..
7145     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7146     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7147                        DAG.getConstant(SHUFPDMask, MVT::i8));
7148   }
7149   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7150   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7151
7152   // Use dedicated unpack instructions for masks that match their pattern.
7153   if (isShuffleEquivalent(Mask, 0, 2))
7154     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7155   if (isShuffleEquivalent(Mask, 1, 3))
7156     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7157
7158   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7159   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7160                      DAG.getConstant(SHUFPDMask, MVT::i8));
7161 }
7162
7163 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7164 ///
7165 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7166 /// the integer unit to minimize domain crossing penalties. However, for blends
7167 /// it falls back to the floating point shuffle operation with appropriate bit
7168 /// casting.
7169 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7170                                        const X86Subtarget *Subtarget,
7171                                        SelectionDAG &DAG) {
7172   SDLoc DL(Op);
7173   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7174   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7175   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7176   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7177   ArrayRef<int> Mask = SVOp->getMask();
7178   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7179
7180   if (isSingleInputShuffleMask(Mask)) {
7181     // Straight shuffle of a single input vector. For everything from SSE2
7182     // onward this has a single fast instruction with no scary immediates.
7183     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7184     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7185     int WidenedMask[4] = {
7186         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7187         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7188     return DAG.getNode(
7189         ISD::BITCAST, DL, MVT::v2i64,
7190         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7191                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7192   }
7193
7194   // Use dedicated unpack instructions for masks that match their pattern.
7195   if (isShuffleEquivalent(Mask, 0, 2))
7196     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7197   if (isShuffleEquivalent(Mask, 1, 3))
7198     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7199
7200   // We implement this with SHUFPD which is pretty lame because it will likely
7201   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7202   // However, all the alternatives are still more cycles and newer chips don't
7203   // have this problem. It would be really nice if x86 had better shuffles here.
7204   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7205   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7206   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7207                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7208 }
7209
7210 /// \brief Lower 4-lane 32-bit floating point shuffles.
7211 ///
7212 /// Uses instructions exclusively from the floating point unit to minimize
7213 /// domain crossing penalties, as these are sufficient to implement all v4f32
7214 /// shuffles.
7215 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7216                                        const X86Subtarget *Subtarget,
7217                                        SelectionDAG &DAG) {
7218   SDLoc DL(Op);
7219   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7220   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7221   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7222   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7223   ArrayRef<int> Mask = SVOp->getMask();
7224   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7225
7226   SDValue LowV = V1, HighV = V2;
7227   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7228
7229   int NumV2Elements =
7230       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7231
7232   if (NumV2Elements == 0)
7233     // Straight shuffle of a single input vector. We pass the input vector to
7234     // both operands to simulate this with a SHUFPS.
7235     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7236                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7237
7238   // Use dedicated unpack instructions for masks that match their pattern.
7239   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7240     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7241   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7242     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7243
7244   if (NumV2Elements == 1) {
7245     int V2Index =
7246         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7247         Mask.begin();
7248     // Compute the index adjacent to V2Index and in the same half by toggling
7249     // the low bit.
7250     int V2AdjIndex = V2Index ^ 1;
7251
7252     if (Mask[V2AdjIndex] == -1) {
7253       // Handles all the cases where we have a single V2 element and an undef.
7254       // This will only ever happen in the high lanes because we commute the
7255       // vector otherwise.
7256       if (V2Index < 2)
7257         std::swap(LowV, HighV);
7258       NewMask[V2Index] -= 4;
7259     } else {
7260       // Handle the case where the V2 element ends up adjacent to a V1 element.
7261       // To make this work, blend them together as the first step.
7262       int V1Index = V2AdjIndex;
7263       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7264       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7265                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7266
7267       // Now proceed to reconstruct the final blend as we have the necessary
7268       // high or low half formed.
7269       if (V2Index < 2) {
7270         LowV = V2;
7271         HighV = V1;
7272       } else {
7273         HighV = V2;
7274       }
7275       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7276       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7277     }
7278   } else if (NumV2Elements == 2) {
7279     if (Mask[0] < 4 && Mask[1] < 4) {
7280       // Handle the easy case where we have V1 in the low lanes and V2 in the
7281       // high lanes. We never see this reversed because we sort the shuffle.
7282       NewMask[2] -= 4;
7283       NewMask[3] -= 4;
7284     } else {
7285       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7286       // trying to place elements directly, just blend them and set up the final
7287       // shuffle to place them.
7288
7289       // The first two blend mask elements are for V1, the second two are for
7290       // V2.
7291       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7292                           Mask[2] < 4 ? Mask[2] : Mask[3],
7293                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7294                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7295       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7296                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7297
7298       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7299       // a blend.
7300       LowV = HighV = V1;
7301       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7302       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7303       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7304       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7305     }
7306   }
7307   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7308                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7309 }
7310
7311 /// \brief Lower 4-lane i32 vector shuffles.
7312 ///
7313 /// We try to handle these with integer-domain shuffles where we can, but for
7314 /// blends we use the floating point domain blend instructions.
7315 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7316                                        const X86Subtarget *Subtarget,
7317                                        SelectionDAG &DAG) {
7318   SDLoc DL(Op);
7319   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7320   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7321   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7322   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7323   ArrayRef<int> Mask = SVOp->getMask();
7324   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7325
7326   if (isSingleInputShuffleMask(Mask))
7327     // Straight shuffle of a single input vector. For everything from SSE2
7328     // onward this has a single fast instruction with no scary immediates.
7329     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7330                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7331
7332   // Use dedicated unpack instructions for masks that match their pattern.
7333   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7334     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7335   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7336     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7337
7338   // We implement this with SHUFPS because it can blend from two vectors.
7339   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7340   // up the inputs, bypassing domain shift penalties that we would encur if we
7341   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7342   // relevant.
7343   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7344                      DAG.getVectorShuffle(
7345                          MVT::v4f32, DL,
7346                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7347                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7348 }
7349
7350 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7351 /// shuffle lowering, and the most complex part.
7352 ///
7353 /// The lowering strategy is to try to form pairs of input lanes which are
7354 /// targeted at the same half of the final vector, and then use a dword shuffle
7355 /// to place them onto the right half, and finally unpack the paired lanes into
7356 /// their final position.
7357 ///
7358 /// The exact breakdown of how to form these dword pairs and align them on the
7359 /// correct sides is really tricky. See the comments within the function for
7360 /// more of the details.
7361 static SDValue lowerV8I16SingleInputVectorShuffle(
7362     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7363     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7364   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7365   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7366   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7367
7368   SmallVector<int, 4> LoInputs;
7369   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7370                [](int M) { return M >= 0; });
7371   std::sort(LoInputs.begin(), LoInputs.end());
7372   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7373   SmallVector<int, 4> HiInputs;
7374   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7375                [](int M) { return M >= 0; });
7376   std::sort(HiInputs.begin(), HiInputs.end());
7377   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7378   int NumLToL =
7379       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7380   int NumHToL = LoInputs.size() - NumLToL;
7381   int NumLToH =
7382       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7383   int NumHToH = HiInputs.size() - NumLToH;
7384   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7385   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7386   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7387   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7388
7389   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7390   // such inputs we can swap two of the dwords across the half mark and end up
7391   // with <=2 inputs to each half in each half. Once there, we can fall through
7392   // to the generic code below. For example:
7393   //
7394   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7395   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7396   //
7397   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7398   // and an existing 2-into-2 on the other half. In this case we may have to
7399   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7400   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7401   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7402   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7403   // half than the one we target for fixing) will be fixed when we re-enter this
7404   // path. We will also combine away any sequence of PSHUFD instructions that
7405   // result into a single instruction. Here is an example of the tricky case:
7406   //
7407   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7408   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7409   //
7410   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7411   //
7412   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7413   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7414   //
7415   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7416   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7417   //
7418   // The result is fine to be handled by the generic logic.
7419   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7420                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7421                           int AOffset, int BOffset) {
7422     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7423            "Must call this with A having 3 or 1 inputs from the A half.");
7424     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7425            "Must call this with B having 1 or 3 inputs from the B half.");
7426     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7427            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7428
7429     // Compute the index of dword with only one word among the three inputs in
7430     // a half by taking the sum of the half with three inputs and subtracting
7431     // the sum of the actual three inputs. The difference is the remaining
7432     // slot.
7433     int ADWord, BDWord;
7434     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7435     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7436     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7437     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7438     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7439     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7440     int TripleNonInputIdx =
7441         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7442     TripleDWord = TripleNonInputIdx / 2;
7443
7444     // We use xor with one to compute the adjacent DWord to whichever one the
7445     // OneInput is in.
7446     OneInputDWord = (OneInput / 2) ^ 1;
7447
7448     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7449     // and BToA inputs. If there is also such a problem with the BToB and AToB
7450     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7451     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7452     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7453     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7454       // Compute how many inputs will be flipped by swapping these DWords. We
7455       // need
7456       // to balance this to ensure we don't form a 3-1 shuffle in the other
7457       // half.
7458       int NumFlippedAToBInputs =
7459           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7460           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7461       int NumFlippedBToBInputs =
7462           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7463           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7464       if ((NumFlippedAToBInputs == 1 &&
7465            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7466           (NumFlippedBToBInputs == 1 &&
7467            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7468         // We choose whether to fix the A half or B half based on whether that
7469         // half has zero flipped inputs. At zero, we may not be able to fix it
7470         // with that half. We also bias towards fixing the B half because that
7471         // will more commonly be the high half, and we have to bias one way.
7472         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7473                                                        ArrayRef<int> Inputs) {
7474           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7475           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7476                                          PinnedIdx ^ 1) != Inputs.end();
7477           // Determine whether the free index is in the flipped dword or the
7478           // unflipped dword based on where the pinned index is. We use this bit
7479           // in an xor to conditionally select the adjacent dword.
7480           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7481           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7482                                              FixFreeIdx) != Inputs.end();
7483           if (IsFixIdxInput == IsFixFreeIdxInput)
7484             FixFreeIdx += 1;
7485           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7486                                         FixFreeIdx) != Inputs.end();
7487           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7488                  "We need to be changing the number of flipped inputs!");
7489           int PSHUFHalfMask[] = {0, 1, 2, 3};
7490           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7491           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7492                           MVT::v8i16, V,
7493                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7494
7495           for (int &M : Mask)
7496             if (M != -1 && M == FixIdx)
7497               M = FixFreeIdx;
7498             else if (M != -1 && M == FixFreeIdx)
7499               M = FixIdx;
7500         };
7501         if (NumFlippedBToBInputs != 0) {
7502           int BPinnedIdx =
7503               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7504           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7505         } else {
7506           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7507           int APinnedIdx =
7508               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7509           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7510         }
7511       }
7512     }
7513
7514     int PSHUFDMask[] = {0, 1, 2, 3};
7515     PSHUFDMask[ADWord] = BDWord;
7516     PSHUFDMask[BDWord] = ADWord;
7517     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7518                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7519                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7520                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7521
7522     // Adjust the mask to match the new locations of A and B.
7523     for (int &M : Mask)
7524       if (M != -1 && M/2 == ADWord)
7525         M = 2 * BDWord + M % 2;
7526       else if (M != -1 && M/2 == BDWord)
7527         M = 2 * ADWord + M % 2;
7528
7529     // Recurse back into this routine to re-compute state now that this isn't
7530     // a 3 and 1 problem.
7531     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7532                                 Mask);
7533   };
7534   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7535     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7536   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7537     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7538
7539   // At this point there are at most two inputs to the low and high halves from
7540   // each half. That means the inputs can always be grouped into dwords and
7541   // those dwords can then be moved to the correct half with a dword shuffle.
7542   // We use at most one low and one high word shuffle to collect these paired
7543   // inputs into dwords, and finally a dword shuffle to place them.
7544   int PSHUFLMask[4] = {-1, -1, -1, -1};
7545   int PSHUFHMask[4] = {-1, -1, -1, -1};
7546   int PSHUFDMask[4] = {-1, -1, -1, -1};
7547
7548   // First fix the masks for all the inputs that are staying in their
7549   // original halves. This will then dictate the targets of the cross-half
7550   // shuffles.
7551   auto fixInPlaceInputs =
7552       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7553                     MutableArrayRef<int> SourceHalfMask,
7554                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7555     if (InPlaceInputs.empty())
7556       return;
7557     if (InPlaceInputs.size() == 1) {
7558       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7559           InPlaceInputs[0] - HalfOffset;
7560       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7561       return;
7562     }
7563     if (IncomingInputs.empty()) {
7564       // Just fix all of the in place inputs.
7565       for (int Input : InPlaceInputs) {
7566         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7567         PSHUFDMask[Input / 2] = Input / 2;
7568       }
7569       return;
7570     }
7571
7572     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7573     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7574         InPlaceInputs[0] - HalfOffset;
7575     // Put the second input next to the first so that they are packed into
7576     // a dword. We find the adjacent index by toggling the low bit.
7577     int AdjIndex = InPlaceInputs[0] ^ 1;
7578     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7579     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7580     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7581   };
7582   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7583   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7584
7585   // Now gather the cross-half inputs and place them into a free dword of
7586   // their target half.
7587   // FIXME: This operation could almost certainly be simplified dramatically to
7588   // look more like the 3-1 fixing operation.
7589   auto moveInputsToRightHalf = [&PSHUFDMask](
7590       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7591       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7592       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7593       int DestOffset) {
7594     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7595       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7596     };
7597     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7598                                                int Word) {
7599       int LowWord = Word & ~1;
7600       int HighWord = Word | 1;
7601       return isWordClobbered(SourceHalfMask, LowWord) ||
7602              isWordClobbered(SourceHalfMask, HighWord);
7603     };
7604
7605     if (IncomingInputs.empty())
7606       return;
7607
7608     if (ExistingInputs.empty()) {
7609       // Map any dwords with inputs from them into the right half.
7610       for (int Input : IncomingInputs) {
7611         // If the source half mask maps over the inputs, turn those into
7612         // swaps and use the swapped lane.
7613         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7614           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7615             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7616                 Input - SourceOffset;
7617             // We have to swap the uses in our half mask in one sweep.
7618             for (int &M : HalfMask)
7619               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7620                 M = Input;
7621               else if (M == Input)
7622                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7623           } else {
7624             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7625                        Input - SourceOffset &&
7626                    "Previous placement doesn't match!");
7627           }
7628           // Note that this correctly re-maps both when we do a swap and when
7629           // we observe the other side of the swap above. We rely on that to
7630           // avoid swapping the members of the input list directly.
7631           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7632         }
7633
7634         // Map the input's dword into the correct half.
7635         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7636           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7637         else
7638           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7639                      Input / 2 &&
7640                  "Previous placement doesn't match!");
7641       }
7642
7643       // And just directly shift any other-half mask elements to be same-half
7644       // as we will have mirrored the dword containing the element into the
7645       // same position within that half.
7646       for (int &M : HalfMask)
7647         if (M >= SourceOffset && M < SourceOffset + 4) {
7648           M = M - SourceOffset + DestOffset;
7649           assert(M >= 0 && "This should never wrap below zero!");
7650         }
7651       return;
7652     }
7653
7654     // Ensure we have the input in a viable dword of its current half. This
7655     // is particularly tricky because the original position may be clobbered
7656     // by inputs being moved and *staying* in that half.
7657     if (IncomingInputs.size() == 1) {
7658       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7659         int InputFixed = std::find(std::begin(SourceHalfMask),
7660                                    std::end(SourceHalfMask), -1) -
7661                          std::begin(SourceHalfMask) + SourceOffset;
7662         SourceHalfMask[InputFixed - SourceOffset] =
7663             IncomingInputs[0] - SourceOffset;
7664         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7665                      InputFixed);
7666         IncomingInputs[0] = InputFixed;
7667       }
7668     } else if (IncomingInputs.size() == 2) {
7669       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7670           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7671         // We have two non-adjacent or clobbered inputs we need to extract from
7672         // the source half. To do this, we need to map them into some adjacent
7673         // dword slot in the source mask.
7674         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7675                               IncomingInputs[1] - SourceOffset};
7676
7677         // If there is a free slot in the source half mask adjacent to one of
7678         // the inputs, place the other input in it. We use (Index XOR 1) to
7679         // compute an adjacent index.
7680         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7681             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7682           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7683           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7684           InputsFixed[1] = InputsFixed[0] ^ 1;
7685         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7686                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7687           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7688           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7689           InputsFixed[0] = InputsFixed[1] ^ 1;
7690         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7691                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7692           // The two inputs are in the same DWord but it is clobbered and the
7693           // adjacent DWord isn't used at all. Move both inputs to the free
7694           // slot.
7695           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7696           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7697           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7698           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7699         } else {
7700           // The only way we hit this point is if there is no clobbering
7701           // (because there are no off-half inputs to this half) and there is no
7702           // free slot adjacent to one of the inputs. In this case, we have to
7703           // swap an input with a non-input.
7704           for (int i = 0; i < 4; ++i)
7705             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7706                    "We can't handle any clobbers here!");
7707           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7708                  "Cannot have adjacent inputs here!");
7709
7710           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7711           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7712
7713           // We also have to update the final source mask in this case because
7714           // it may need to undo the above swap.
7715           for (int &M : FinalSourceHalfMask)
7716             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
7717               M = InputsFixed[1] + SourceOffset;
7718             else if (M == InputsFixed[1] + SourceOffset)
7719               M = (InputsFixed[0] ^ 1) + SourceOffset;
7720
7721           InputsFixed[1] = InputsFixed[0] ^ 1;
7722         }
7723
7724         // Point everything at the fixed inputs.
7725         for (int &M : HalfMask)
7726           if (M == IncomingInputs[0])
7727             M = InputsFixed[0] + SourceOffset;
7728           else if (M == IncomingInputs[1])
7729             M = InputsFixed[1] + SourceOffset;
7730
7731         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7732         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7733       }
7734     } else {
7735       llvm_unreachable("Unhandled input size!");
7736     }
7737
7738     // Now hoist the DWord down to the right half.
7739     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7740     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7741     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7742     for (int &M : HalfMask)
7743       for (int Input : IncomingInputs)
7744         if (M == Input)
7745           M = FreeDWord * 2 + Input % 2;
7746   };
7747   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
7748                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7749   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
7750                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7751
7752   // Now enact all the shuffles we've computed to move the inputs into their
7753   // target half.
7754   if (!isNoopShuffleMask(PSHUFLMask))
7755     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7756                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7757   if (!isNoopShuffleMask(PSHUFHMask))
7758     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7759                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7760   if (!isNoopShuffleMask(PSHUFDMask))
7761     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7762                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7763                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7764                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7765
7766   // At this point, each half should contain all its inputs, and we can then
7767   // just shuffle them into their final position.
7768   assert(std::count_if(LoMask.begin(), LoMask.end(),
7769                        [](int M) { return M >= 4; }) == 0 &&
7770          "Failed to lift all the high half inputs to the low mask!");
7771   assert(std::count_if(HiMask.begin(), HiMask.end(),
7772                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7773          "Failed to lift all the low half inputs to the high mask!");
7774
7775   // Do a half shuffle for the low mask.
7776   if (!isNoopShuffleMask(LoMask))
7777     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7778                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7779
7780   // Do a half shuffle with the high mask after shifting its values down.
7781   for (int &M : HiMask)
7782     if (M >= 0)
7783       M -= 4;
7784   if (!isNoopShuffleMask(HiMask))
7785     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7786                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7787
7788   return V;
7789 }
7790
7791 /// \brief Detect whether the mask pattern should be lowered through
7792 /// interleaving.
7793 ///
7794 /// This essentially tests whether viewing the mask as an interleaving of two
7795 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7796 /// lowering it through interleaving is a significantly better strategy.
7797 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7798   int NumEvenInputs[2] = {0, 0};
7799   int NumOddInputs[2] = {0, 0};
7800   int NumLoInputs[2] = {0, 0};
7801   int NumHiInputs[2] = {0, 0};
7802   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7803     if (Mask[i] < 0)
7804       continue;
7805
7806     int InputIdx = Mask[i] >= Size;
7807
7808     if (i < Size / 2)
7809       ++NumLoInputs[InputIdx];
7810     else
7811       ++NumHiInputs[InputIdx];
7812
7813     if ((i % 2) == 0)
7814       ++NumEvenInputs[InputIdx];
7815     else
7816       ++NumOddInputs[InputIdx];
7817   }
7818
7819   // The minimum number of cross-input results for both the interleaved and
7820   // split cases. If interleaving results in fewer cross-input results, return
7821   // true.
7822   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7823                                     NumEvenInputs[0] + NumOddInputs[1]);
7824   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7825                               NumLoInputs[0] + NumHiInputs[1]);
7826   return InterleavedCrosses < SplitCrosses;
7827 }
7828
7829 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7830 ///
7831 /// This strategy only works when the inputs from each vector fit into a single
7832 /// half of that vector, and generally there are not so many inputs as to leave
7833 /// the in-place shuffles required highly constrained (and thus expensive). It
7834 /// shifts all the inputs into a single side of both input vectors and then
7835 /// uses an unpack to interleave these inputs in a single vector. At that
7836 /// point, we will fall back on the generic single input shuffle lowering.
7837 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7838                                                  SDValue V2,
7839                                                  MutableArrayRef<int> Mask,
7840                                                  const X86Subtarget *Subtarget,
7841                                                  SelectionDAG &DAG) {
7842   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7843   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7844   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7845   for (int i = 0; i < 8; ++i)
7846     if (Mask[i] >= 0 && Mask[i] < 4)
7847       LoV1Inputs.push_back(i);
7848     else if (Mask[i] >= 4 && Mask[i] < 8)
7849       HiV1Inputs.push_back(i);
7850     else if (Mask[i] >= 8 && Mask[i] < 12)
7851       LoV2Inputs.push_back(i);
7852     else if (Mask[i] >= 12)
7853       HiV2Inputs.push_back(i);
7854
7855   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7856   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7857   (void)NumV1Inputs;
7858   (void)NumV2Inputs;
7859   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7860   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7861   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7862
7863   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7864                      HiV1Inputs.size() + HiV2Inputs.size();
7865
7866   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7867                               ArrayRef<int> HiInputs, bool MoveToLo,
7868                               int MaskOffset) {
7869     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7870     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7871     if (BadInputs.empty())
7872       return V;
7873
7874     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7875     int MoveOffset = MoveToLo ? 0 : 4;
7876
7877     if (GoodInputs.empty()) {
7878       for (int BadInput : BadInputs) {
7879         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7880         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7881       }
7882     } else {
7883       if (GoodInputs.size() == 2) {
7884         // If the low inputs are spread across two dwords, pack them into
7885         // a single dword.
7886         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
7887         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
7888         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
7889         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
7890       } else {
7891         // Otherwise pin the good inputs.
7892         for (int GoodInput : GoodInputs)
7893           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7894       }
7895
7896       if (BadInputs.size() == 2) {
7897         // If we have two bad inputs then there may be either one or two good
7898         // inputs fixed in place. Find a fixed input, and then find the *other*
7899         // two adjacent indices by using modular arithmetic.
7900         int GoodMaskIdx =
7901             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
7902                          [](int M) { return M >= 0; }) -
7903             std::begin(MoveMask);
7904         int MoveMaskIdx =
7905             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
7906         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7907         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7908         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7909         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
7910         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7911         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
7912       } else {
7913         assert(BadInputs.size() == 1 && "All sizes handled");
7914         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
7915                                     std::end(MoveMask), -1) -
7916                           std::begin(MoveMask);
7917         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7918         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7919       }
7920     }
7921
7922     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7923                                 MoveMask);
7924   };
7925   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7926                         /*MaskOffset*/ 0);
7927   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7928                         /*MaskOffset*/ 8);
7929
7930   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7931   // cross-half traffic in the final shuffle.
7932
7933   // Munge the mask to be a single-input mask after the unpack merges the
7934   // results.
7935   for (int &M : Mask)
7936     if (M != -1)
7937       M = 2 * (M % 4) + (M / 8);
7938
7939   return DAG.getVectorShuffle(
7940       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7941                                   DL, MVT::v8i16, V1, V2),
7942       DAG.getUNDEF(MVT::v8i16), Mask);
7943 }
7944
7945 /// \brief Generic lowering of 8-lane i16 shuffles.
7946 ///
7947 /// This handles both single-input shuffles and combined shuffle/blends with
7948 /// two inputs. The single input shuffles are immediately delegated to
7949 /// a dedicated lowering routine.
7950 ///
7951 /// The blends are lowered in one of three fundamental ways. If there are few
7952 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7953 /// of the input is significantly cheaper when lowered as an interleaving of
7954 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7955 /// halves of the inputs separately (making them have relatively few inputs)
7956 /// and then concatenate them.
7957 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7958                                        const X86Subtarget *Subtarget,
7959                                        SelectionDAG &DAG) {
7960   SDLoc DL(Op);
7961   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7962   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7963   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7964   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7965   ArrayRef<int> OrigMask = SVOp->getMask();
7966   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7967                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7968   MutableArrayRef<int> Mask(MaskStorage);
7969
7970   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7971
7972   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7973   auto isV2 = [](int M) { return M >= 8; };
7974
7975   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7976   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7977
7978   if (NumV2Inputs == 0)
7979     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7980
7981   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7982                             "to be V1-input shuffles.");
7983
7984   if (NumV1Inputs + NumV2Inputs <= 4)
7985     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7986
7987   // Check whether an interleaving lowering is likely to be more efficient.
7988   // This isn't perfect but it is a strong heuristic that tends to work well on
7989   // the kinds of shuffles that show up in practice.
7990   //
7991   // FIXME: Handle 1x, 2x, and 4x interleaving.
7992   if (shouldLowerAsInterleaving(Mask)) {
7993     // FIXME: Figure out whether we should pack these into the low or high
7994     // halves.
7995
7996     int EMask[8], OMask[8];
7997     for (int i = 0; i < 4; ++i) {
7998       EMask[i] = Mask[2*i];
7999       OMask[i] = Mask[2*i + 1];
8000       EMask[i + 4] = -1;
8001       OMask[i + 4] = -1;
8002     }
8003
8004     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
8005     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
8006
8007     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
8008   }
8009
8010   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8011   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8012
8013   for (int i = 0; i < 4; ++i) {
8014     LoBlendMask[i] = Mask[i];
8015     HiBlendMask[i] = Mask[i + 4];
8016   }
8017
8018   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8019   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8020   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
8021   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
8022
8023   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8024                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
8025 }
8026
8027 /// \brief Check whether a compaction lowering can be done by dropping even
8028 /// elements and compute how many times even elements must be dropped.
8029 ///
8030 /// This handles shuffles which take every Nth element where N is a power of
8031 /// two. Example shuffle masks:
8032 ///
8033 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8034 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8035 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8036 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8037 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8038 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8039 ///
8040 /// Any of these lanes can of course be undef.
8041 ///
8042 /// This routine only supports N <= 3.
8043 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8044 /// for larger N.
8045 ///
8046 /// \returns N above, or the number of times even elements must be dropped if
8047 /// there is such a number. Otherwise returns zero.
8048 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8049   // Figure out whether we're looping over two inputs or just one.
8050   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8051
8052   // The modulus for the shuffle vector entries is based on whether this is
8053   // a single input or not.
8054   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8055   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8056          "We should only be called with masks with a power-of-2 size!");
8057
8058   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8059
8060   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8061   // and 2^3 simultaneously. This is because we may have ambiguity with
8062   // partially undef inputs.
8063   bool ViableForN[3] = {true, true, true};
8064
8065   for (int i = 0, e = Mask.size(); i < e; ++i) {
8066     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8067     // want.
8068     if (Mask[i] == -1)
8069       continue;
8070
8071     bool IsAnyViable = false;
8072     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8073       if (ViableForN[j]) {
8074         uint64_t N = j + 1;
8075
8076         // The shuffle mask must be equal to (i * 2^N) % M.
8077         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8078           IsAnyViable = true;
8079         else
8080           ViableForN[j] = false;
8081       }
8082     // Early exit if we exhaust the possible powers of two.
8083     if (!IsAnyViable)
8084       break;
8085   }
8086
8087   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8088     if (ViableForN[j])
8089       return j + 1;
8090
8091   // Return 0 as there is no viable power of two.
8092   return 0;
8093 }
8094
8095 /// \brief Generic lowering of v16i8 shuffles.
8096 ///
8097 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8098 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8099 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8100 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8101 /// back together.
8102 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8103                                        const X86Subtarget *Subtarget,
8104                                        SelectionDAG &DAG) {
8105   SDLoc DL(Op);
8106   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8107   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8108   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8109   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8110   ArrayRef<int> OrigMask = SVOp->getMask();
8111   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8112   int MaskStorage[16] = {
8113       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
8114       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
8115       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
8116       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8117   MutableArrayRef<int> Mask(MaskStorage);
8118   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8119   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8120
8121   // For single-input shuffles, there are some nicer lowering tricks we can use.
8122   if (isSingleInputShuffleMask(Mask)) {
8123     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8124     // Notably, this handles splat and partial-splat shuffles more efficiently.
8125     // However, it only makes sense if the pre-duplication shuffle simplifies
8126     // things significantly. Currently, this means we need to be able to
8127     // express the pre-duplication shuffle as an i16 shuffle.
8128     //
8129     // FIXME: We should check for other patterns which can be widened into an
8130     // i16 shuffle as well.
8131     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8132       for (int i = 0; i < 16; i += 2) {
8133         if (Mask[i] != Mask[i + 1])
8134           return false;
8135       }
8136       return true;
8137     };
8138     auto tryToWidenViaDuplication = [&]() -> SDValue {
8139       if (!canWidenViaDuplication(Mask))
8140         return SDValue();
8141       SmallVector<int, 4> LoInputs;
8142       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8143                    [](int M) { return M >= 0 && M < 8; });
8144       std::sort(LoInputs.begin(), LoInputs.end());
8145       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8146                      LoInputs.end());
8147       SmallVector<int, 4> HiInputs;
8148       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8149                    [](int M) { return M >= 8; });
8150       std::sort(HiInputs.begin(), HiInputs.end());
8151       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8152                      HiInputs.end());
8153
8154       bool TargetLo = LoInputs.size() >= HiInputs.size();
8155       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8156       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8157
8158       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8159       SmallDenseMap<int, int, 8> LaneMap;
8160       for (int I : InPlaceInputs) {
8161         PreDupI16Shuffle[I/2] = I/2;
8162         LaneMap[I] = I;
8163       }
8164       int j = TargetLo ? 0 : 4, je = j + 4;
8165       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8166         // Check if j is already a shuffle of this input. This happens when
8167         // there are two adjacent bytes after we move the low one.
8168         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8169           // If we haven't yet mapped the input, search for a slot into which
8170           // we can map it.
8171           while (j < je && PreDupI16Shuffle[j] != -1)
8172             ++j;
8173
8174           if (j == je)
8175             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8176             return SDValue();
8177
8178           // Map this input with the i16 shuffle.
8179           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8180         }
8181
8182         // Update the lane map based on the mapping we ended up with.
8183         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8184       }
8185       V1 = DAG.getNode(
8186           ISD::BITCAST, DL, MVT::v16i8,
8187           DAG.getVectorShuffle(MVT::v8i16, DL,
8188                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8189                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8190
8191       // Unpack the bytes to form the i16s that will be shuffled into place.
8192       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8193                        MVT::v16i8, V1, V1);
8194
8195       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8196       for (int i = 0; i < 16; i += 2) {
8197         if (Mask[i] != -1)
8198           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8199         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8200       }
8201       return DAG.getNode(
8202           ISD::BITCAST, DL, MVT::v16i8,
8203           DAG.getVectorShuffle(MVT::v8i16, DL,
8204                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8205                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8206     };
8207     if (SDValue V = tryToWidenViaDuplication())
8208       return V;
8209   }
8210
8211   // Check whether an interleaving lowering is likely to be more efficient.
8212   // This isn't perfect but it is a strong heuristic that tends to work well on
8213   // the kinds of shuffles that show up in practice.
8214   //
8215   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8216   if (shouldLowerAsInterleaving(Mask)) {
8217     // FIXME: Figure out whether we should pack these into the low or high
8218     // halves.
8219
8220     int EMask[16], OMask[16];
8221     for (int i = 0; i < 8; ++i) {
8222       EMask[i] = Mask[2*i];
8223       OMask[i] = Mask[2*i + 1];
8224       EMask[i + 8] = -1;
8225       OMask[i + 8] = -1;
8226     }
8227
8228     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8229     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8230
8231     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8232   }
8233
8234   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8235   // with PSHUFB. It is important to do this before we attempt to generate any
8236   // blends but after all of the single-input lowerings. If the single input
8237   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8238   // want to preserve that and we can DAG combine any longer sequences into
8239   // a PSHUFB in the end. But once we start blending from multiple inputs,
8240   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8241   // and there are *very* few patterns that would actually be faster than the
8242   // PSHUFB approach because of its ability to zero lanes.
8243   //
8244   // FIXME: The only exceptions to the above are blends which are exact
8245   // interleavings with direct instructions supporting them. We currently don't
8246   // handle those well here.
8247   if (Subtarget->hasSSSE3()) {
8248     SDValue V1Mask[16];
8249     SDValue V2Mask[16];
8250     for (int i = 0; i < 16; ++i)
8251       if (Mask[i] == -1) {
8252         V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8253       } else {
8254         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8255         V2Mask[i] =
8256             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8257       }
8258     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8259                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8260     if (isSingleInputShuffleMask(Mask))
8261       return V1; // Single inputs are easy.
8262
8263     // Otherwise, blend the two.
8264     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8265                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8266     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8267   }
8268
8269   // Check whether a compaction lowering can be done. This handles shuffles
8270   // which take every Nth element for some even N. See the helper function for
8271   // details.
8272   //
8273   // We special case these as they can be particularly efficiently handled with
8274   // the PACKUSB instruction on x86 and they show up in common patterns of
8275   // rearranging bytes to truncate wide elements.
8276   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8277     // NumEvenDrops is the power of two stride of the elements. Another way of
8278     // thinking about it is that we need to drop the even elements this many
8279     // times to get the original input.
8280     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8281
8282     // First we need to zero all the dropped bytes.
8283     assert(NumEvenDrops <= 3 &&
8284            "No support for dropping even elements more than 3 times.");
8285     // We use the mask type to pick which bytes are preserved based on how many
8286     // elements are dropped.
8287     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8288     SDValue ByteClearMask =
8289         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8290                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8291     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8292     if (!IsSingleInput)
8293       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8294
8295     // Now pack things back together.
8296     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8297     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8298     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8299     for (int i = 1; i < NumEvenDrops; ++i) {
8300       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8301       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8302     }
8303
8304     return Result;
8305   }
8306
8307   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8308   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8309   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8310   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8311
8312   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8313                             MutableArrayRef<int> V1HalfBlendMask,
8314                             MutableArrayRef<int> V2HalfBlendMask) {
8315     for (int i = 0; i < 8; ++i)
8316       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8317         V1HalfBlendMask[i] = HalfMask[i];
8318         HalfMask[i] = i;
8319       } else if (HalfMask[i] >= 16) {
8320         V2HalfBlendMask[i] = HalfMask[i] - 16;
8321         HalfMask[i] = i + 8;
8322       }
8323   };
8324   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8325   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8326
8327   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8328
8329   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8330                              MutableArrayRef<int> HiBlendMask) {
8331     SDValue V1, V2;
8332     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8333     // them out and avoid using UNPCK{L,H} to extract the elements of V as
8334     // i16s.
8335     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8336                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
8337         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8338                      [](int M) { return M >= 0 && M % 2 == 1; })) {
8339       // Use a mask to drop the high bytes.
8340       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8341       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8342                        DAG.getConstant(0x00FF, MVT::v8i16));
8343
8344       // This will be a single vector shuffle instead of a blend so nuke V2.
8345       V2 = DAG.getUNDEF(MVT::v8i16);
8346
8347       // Squash the masks to point directly into V1.
8348       for (int &M : LoBlendMask)
8349         if (M >= 0)
8350           M /= 2;
8351       for (int &M : HiBlendMask)
8352         if (M >= 0)
8353           M /= 2;
8354     } else {
8355       // Otherwise just unpack the low half of V into V1 and the high half into
8356       // V2 so that we can blend them as i16s.
8357       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8358                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8359       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8360                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8361     }
8362
8363     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8364     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8365     return std::make_pair(BlendedLo, BlendedHi);
8366   };
8367   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8368   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8369   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8370
8371   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8372   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8373
8374   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8375 }
8376
8377 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8378 ///
8379 /// This routine breaks down the specific type of 128-bit shuffle and
8380 /// dispatches to the lowering routines accordingly.
8381 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8382                                         MVT VT, const X86Subtarget *Subtarget,
8383                                         SelectionDAG &DAG) {
8384   switch (VT.SimpleTy) {
8385   case MVT::v2i64:
8386     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8387   case MVT::v2f64:
8388     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8389   case MVT::v4i32:
8390     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8391   case MVT::v4f32:
8392     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8393   case MVT::v8i16:
8394     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8395   case MVT::v16i8:
8396     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8397
8398   default:
8399     llvm_unreachable("Unimplemented!");
8400   }
8401 }
8402
8403 static bool isHalfCrossingShuffleMask(ArrayRef<int> Mask) {
8404   int Size = Mask.size();
8405   for (int M : Mask.slice(0, Size / 2))
8406     if (M >= 0 && (M % Size) >= Size / 2)
8407       return true;
8408   for (int M : Mask.slice(Size / 2, Size / 2))
8409     if (M >= 0 && (M % Size) < Size / 2)
8410       return true;
8411   return false;
8412 }
8413
8414 /// \brief Generic routine to split a 256-bit vector shuffle into 128-bit
8415 /// shuffles.
8416 ///
8417 /// There is a severely limited set of shuffles available in AVX1 for 256-bit
8418 /// vectors resulting in routinely needing to split the shuffle into two 128-bit
8419 /// shuffles. This can be done generically for any 256-bit vector shuffle and so
8420 /// we encode the logic here for specific shuffle lowering routines to bail to
8421 /// when they exhaust the features avaible to more directly handle the shuffle.
8422 static SDValue splitAndLower256BitVectorShuffle(SDValue Op, SDValue V1,
8423                                                 SDValue V2,
8424                                                 const X86Subtarget *Subtarget,
8425                                                 SelectionDAG &DAG) {
8426   SDLoc DL(Op);
8427   MVT VT = Op.getSimpleValueType();
8428   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8429   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8430   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8431   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8432   ArrayRef<int> Mask = SVOp->getMask();
8433
8434   ArrayRef<int> LoMask = Mask.slice(0, Mask.size()/2);
8435   ArrayRef<int> HiMask = Mask.slice(Mask.size()/2);
8436
8437   int NumElements = VT.getVectorNumElements();
8438   int SplitNumElements = NumElements / 2;
8439   MVT ScalarVT = VT.getScalarType();
8440   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8441
8442   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8443                              DAG.getIntPtrConstant(0));
8444   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8445                              DAG.getIntPtrConstant(SplitNumElements));
8446   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8447                              DAG.getIntPtrConstant(0));
8448   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8449                              DAG.getIntPtrConstant(SplitNumElements));
8450
8451   // Now create two 4-way blends of these half-width vectors.
8452   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8453     SmallVector<int, 16> V1BlendMask, V2BlendMask, BlendMask;
8454     for (int i = 0; i < SplitNumElements; ++i) {
8455       int M = HalfMask[i];
8456       if (M >= NumElements) {
8457         V2BlendMask.push_back(M - NumElements);
8458         V1BlendMask.push_back(-1);
8459         BlendMask.push_back(SplitNumElements + i);
8460       } else if (M >= 0) {
8461         V2BlendMask.push_back(-1);
8462         V1BlendMask.push_back(M);
8463         BlendMask.push_back(i);
8464       } else {
8465         V2BlendMask.push_back(-1);
8466         V1BlendMask.push_back(-1);
8467         BlendMask.push_back(-1);
8468       }
8469     }
8470     SDValue V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8471     SDValue V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8472     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8473   };
8474   SDValue Lo = HalfBlend(LoMask);
8475   SDValue Hi = HalfBlend(HiMask);
8476   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8477 }
8478
8479 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
8480 ///
8481 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
8482 /// isn't available.
8483 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8484                                        const X86Subtarget *Subtarget,
8485                                        SelectionDAG &DAG) {
8486   SDLoc DL(Op);
8487   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8488   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8489   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8490   ArrayRef<int> Mask = SVOp->getMask();
8491   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8492
8493   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8494   // shuffles aren't a problem and FP and int have the same patterns.
8495
8496   // FIXME: We can handle these more cleverly than splitting for v4f64.
8497   if (isHalfCrossingShuffleMask(Mask))
8498     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8499
8500   if (isSingleInputShuffleMask(Mask)) {
8501     // Non-half-crossing single input shuffles can be lowerid with an
8502     // interleaved permutation.
8503     unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
8504                             ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
8505     return DAG.getNode(X86ISD::VPERMILP, DL, MVT::v4f64, V1,
8506                        DAG.getConstant(VPERMILPMask, MVT::i8));
8507   }
8508
8509   // X86 has dedicated unpack instructions that can handle specific blend
8510   // operations: UNPCKH and UNPCKL.
8511   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
8512     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
8513   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
8514     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
8515   // FIXME: It would be nice to find a way to get canonicalization to commute
8516   // these patterns.
8517   if (isShuffleEquivalent(Mask, 4, 0, 6, 2))
8518     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
8519   if (isShuffleEquivalent(Mask, 5, 1, 7, 3))
8520     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
8521
8522   // Check if the blend happens to exactly fit that of SHUFPD.
8523   if (Mask[0] < 4 && (Mask[1] == -1 || Mask[1] >= 4) &&
8524       Mask[2] < 4 && (Mask[3] == -1 || Mask[3] >= 4)) {
8525     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
8526                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
8527     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
8528                        DAG.getConstant(SHUFPDMask, MVT::i8));
8529   }
8530   if ((Mask[0] == -1 || Mask[0] >= 4) && Mask[1] < 4 &&
8531       (Mask[2] == -1 || Mask[2] >= 4) && Mask[3] < 4) {
8532     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
8533                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
8534     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
8535                        DAG.getConstant(SHUFPDMask, MVT::i8));
8536   }
8537
8538   // Shuffle the input elements into the desired positions in V1 and V2 and
8539   // blend them together.
8540   int V1Mask[] = {-1, -1, -1, -1};
8541   int V2Mask[] = {-1, -1, -1, -1};
8542   for (int i = 0; i < 4; ++i)
8543     if (Mask[i] >= 0 && Mask[i] < 4)
8544       V1Mask[i] = Mask[i];
8545     else if (Mask[i] >= 4)
8546       V2Mask[i] = Mask[i] - 4;
8547
8548   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, V1, DAG.getUNDEF(MVT::v4f64), V1Mask);
8549   V2 = DAG.getVectorShuffle(MVT::v4f64, DL, V2, DAG.getUNDEF(MVT::v4f64), V2Mask);
8550
8551   unsigned BlendMask = 0;
8552   for (int i = 0; i < 4; ++i)
8553     if (Mask[i] >= 4)
8554       BlendMask |= 1 << i;
8555
8556   return DAG.getNode(X86ISD::BLENDI, DL, MVT::v4f64, V1, V2,
8557                      DAG.getConstant(BlendMask, MVT::i8));
8558 }
8559
8560 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
8561 ///
8562 /// Largely delegates to common code when we have AVX2 and to the floating-point
8563 /// code when we only have AVX.
8564 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8565                                        const X86Subtarget *Subtarget,
8566                                        SelectionDAG &DAG) {
8567   SDLoc DL(Op);
8568   assert(Op.getSimpleValueType() == MVT::v4i64 && "Bad shuffle type!");
8569   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8570   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8571   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8572   ArrayRef<int> Mask = SVOp->getMask();
8573   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8574
8575   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8576   // shuffles aren't a problem and FP and int have the same patterns.
8577
8578   if (isHalfCrossingShuffleMask(Mask))
8579     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8580
8581   // AVX1 doesn't provide any facilities for v4i64 shuffles, bitcast and
8582   // delegate to floating point code.
8583   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V1);
8584   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V2);
8585   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i64,
8586                      lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG));
8587 }
8588
8589 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
8590 ///
8591 /// This routine either breaks down the specific type of a 256-bit x86 vector
8592 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
8593 /// together based on the available instructions.
8594 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8595                                         MVT VT, const X86Subtarget *Subtarget,
8596                                         SelectionDAG &DAG) {
8597   switch (VT.SimpleTy) {
8598   case MVT::v4f64:
8599     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8600   case MVT::v4i64:
8601     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8602   case MVT::v8i32:
8603   case MVT::v8f32:
8604   case MVT::v16i16:
8605   case MVT::v32i8:
8606     // Fall back to the basic pattern of extracting the high half and forming
8607     // a 4-way blend.
8608     // FIXME: Add targeted lowering for each type that can document rationale
8609     // for delegating to this when necessary.
8610     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8611
8612   default:
8613     llvm_unreachable("Not a valid 256-bit x86 vector type!");
8614   }
8615 }
8616
8617 /// \brief Tiny helper function to test whether a shuffle mask could be
8618 /// simplified by widening the elements being shuffled.
8619 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8620   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8621     if (Mask[i] % 2 != 0 || Mask[i] + 1 != Mask[i+1])
8622       return false;
8623
8624   return true;
8625 }
8626
8627 /// \brief Top-level lowering for x86 vector shuffles.
8628 ///
8629 /// This handles decomposition, canonicalization, and lowering of all x86
8630 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8631 /// above in helper routines. The canonicalization attempts to widen shuffles
8632 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8633 /// s.t. only one of the two inputs needs to be tested, etc.
8634 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8635                                   SelectionDAG &DAG) {
8636   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8637   ArrayRef<int> Mask = SVOp->getMask();
8638   SDValue V1 = Op.getOperand(0);
8639   SDValue V2 = Op.getOperand(1);
8640   MVT VT = Op.getSimpleValueType();
8641   int NumElements = VT.getVectorNumElements();
8642   SDLoc dl(Op);
8643
8644   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8645
8646   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8647   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8648   if (V1IsUndef && V2IsUndef)
8649     return DAG.getUNDEF(VT);
8650
8651   // When we create a shuffle node we put the UNDEF node to second operand,
8652   // but in some cases the first operand may be transformed to UNDEF.
8653   // In this case we should just commute the node.
8654   if (V1IsUndef)
8655     return DAG.getCommutedVectorShuffle(*SVOp);
8656
8657   // Check for non-undef masks pointing at an undef vector and make the masks
8658   // undef as well. This makes it easier to match the shuffle based solely on
8659   // the mask.
8660   if (V2IsUndef)
8661     for (int M : Mask)
8662       if (M >= NumElements) {
8663         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8664         for (int &M : NewMask)
8665           if (M >= NumElements)
8666             M = -1;
8667         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8668       }
8669
8670   // For integer vector shuffles, try to collapse them into a shuffle of fewer
8671   // lanes but wider integers. We cap this to not form integers larger than i64
8672   // but it might be interesting to form i128 integers to handle flipping the
8673   // low and high halves of AVX 256-bit vectors.
8674   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8675       canWidenShuffleElements(Mask)) {
8676     SmallVector<int, 8> NewMask;
8677     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8678       NewMask.push_back(Mask[i] / 2);
8679     MVT NewVT =
8680         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8681                          VT.getVectorNumElements() / 2);
8682     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8683     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8684     return DAG.getNode(ISD::BITCAST, dl, VT,
8685                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8686   }
8687
8688   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8689   for (int M : SVOp->getMask())
8690     if (M < 0)
8691       ++NumUndefElements;
8692     else if (M < NumElements)
8693       ++NumV1Elements;
8694     else
8695       ++NumV2Elements;
8696
8697   // Commute the shuffle as needed such that more elements come from V1 than
8698   // V2. This allows us to match the shuffle pattern strictly on how many
8699   // elements come from V1 without handling the symmetric cases.
8700   if (NumV2Elements > NumV1Elements)
8701     return DAG.getCommutedVectorShuffle(*SVOp);
8702
8703   // When the number of V1 and V2 elements are the same, try to minimize the
8704   // number of uses of V2 in the low half of the vector.
8705   if (NumV1Elements == NumV2Elements) {
8706     int LowV1Elements = 0, LowV2Elements = 0;
8707     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8708       if (M >= NumElements)
8709         ++LowV2Elements;
8710       else if (M >= 0)
8711         ++LowV1Elements;
8712     if (LowV2Elements > LowV1Elements)
8713       return DAG.getCommutedVectorShuffle(*SVOp);
8714   }
8715
8716   // For each vector width, delegate to a specialized lowering routine.
8717   if (VT.getSizeInBits() == 128)
8718     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8719
8720   if (VT.getSizeInBits() == 256)
8721     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8722
8723   llvm_unreachable("Unimplemented!");
8724 }
8725
8726
8727 //===----------------------------------------------------------------------===//
8728 // Legacy vector shuffle lowering
8729 //
8730 // This code is the legacy code handling vector shuffles until the above
8731 // replaces its functionality and performance.
8732 //===----------------------------------------------------------------------===//
8733
8734 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8735                         bool hasInt256, unsigned *MaskOut = nullptr) {
8736   MVT EltVT = VT.getVectorElementType();
8737
8738   // There is no blend with immediate in AVX-512.
8739   if (VT.is512BitVector())
8740     return false;
8741
8742   if (!hasSSE41 || EltVT == MVT::i8)
8743     return false;
8744   if (!hasInt256 && VT == MVT::v16i16)
8745     return false;
8746
8747   unsigned MaskValue = 0;
8748   unsigned NumElems = VT.getVectorNumElements();
8749   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8750   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8751   unsigned NumElemsInLane = NumElems / NumLanes;
8752
8753   // Blend for v16i16 should be symetric for the both lanes.
8754   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8755
8756     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8757     int EltIdx = MaskVals[i];
8758
8759     if ((EltIdx < 0 || EltIdx == (int)i) &&
8760         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8761       continue;
8762
8763     if (((unsigned)EltIdx == (i + NumElems)) &&
8764         (SndLaneEltIdx < 0 ||
8765          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8766       MaskValue |= (1 << i);
8767     else
8768       return false;
8769   }
8770
8771   if (MaskOut)
8772     *MaskOut = MaskValue;
8773   return true;
8774 }
8775
8776 // Try to lower a shuffle node into a simple blend instruction.
8777 // This function assumes isBlendMask returns true for this
8778 // SuffleVectorSDNode
8779 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8780                                           unsigned MaskValue,
8781                                           const X86Subtarget *Subtarget,
8782                                           SelectionDAG &DAG) {
8783   MVT VT = SVOp->getSimpleValueType(0);
8784   MVT EltVT = VT.getVectorElementType();
8785   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8786                      Subtarget->hasInt256() && "Trying to lower a "
8787                                                "VECTOR_SHUFFLE to a Blend but "
8788                                                "with the wrong mask"));
8789   SDValue V1 = SVOp->getOperand(0);
8790   SDValue V2 = SVOp->getOperand(1);
8791   SDLoc dl(SVOp);
8792   unsigned NumElems = VT.getVectorNumElements();
8793
8794   // Convert i32 vectors to floating point if it is not AVX2.
8795   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8796   MVT BlendVT = VT;
8797   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8798     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8799                                NumElems);
8800     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8801     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8802   }
8803
8804   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8805                             DAG.getConstant(MaskValue, MVT::i32));
8806   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8807 }
8808
8809 /// In vector type \p VT, return true if the element at index \p InputIdx
8810 /// falls on a different 128-bit lane than \p OutputIdx.
8811 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8812                                      unsigned OutputIdx) {
8813   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8814   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8815 }
8816
8817 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8818 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8819 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8820 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8821 /// zero.
8822 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8823                          SelectionDAG &DAG) {
8824   MVT VT = V1.getSimpleValueType();
8825   assert(VT.is128BitVector() || VT.is256BitVector());
8826
8827   MVT EltVT = VT.getVectorElementType();
8828   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8829   unsigned NumElts = VT.getVectorNumElements();
8830
8831   SmallVector<SDValue, 32> PshufbMask;
8832   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8833     int InputIdx = MaskVals[OutputIdx];
8834     unsigned InputByteIdx;
8835
8836     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8837       InputByteIdx = 0x80;
8838     else {
8839       // Cross lane is not allowed.
8840       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8841         return SDValue();
8842       InputByteIdx = InputIdx * EltSizeInBytes;
8843       // Index is an byte offset within the 128-bit lane.
8844       InputByteIdx &= 0xf;
8845     }
8846
8847     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8848       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8849       if (InputByteIdx != 0x80)
8850         ++InputByteIdx;
8851     }
8852   }
8853
8854   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8855   if (ShufVT != VT)
8856     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8857   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8858                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8859 }
8860
8861 // v8i16 shuffles - Prefer shuffles in the following order:
8862 // 1. [all]   pshuflw, pshufhw, optional move
8863 // 2. [ssse3] 1 x pshufb
8864 // 3. [ssse3] 2 x pshufb + 1 x por
8865 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8866 static SDValue
8867 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8868                          SelectionDAG &DAG) {
8869   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8870   SDValue V1 = SVOp->getOperand(0);
8871   SDValue V2 = SVOp->getOperand(1);
8872   SDLoc dl(SVOp);
8873   SmallVector<int, 8> MaskVals;
8874
8875   // Determine if more than 1 of the words in each of the low and high quadwords
8876   // of the result come from the same quadword of one of the two inputs.  Undef
8877   // mask values count as coming from any quadword, for better codegen.
8878   //
8879   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8880   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8881   unsigned LoQuad[] = { 0, 0, 0, 0 };
8882   unsigned HiQuad[] = { 0, 0, 0, 0 };
8883   // Indices of quads used.
8884   std::bitset<4> InputQuads;
8885   for (unsigned i = 0; i < 8; ++i) {
8886     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8887     int EltIdx = SVOp->getMaskElt(i);
8888     MaskVals.push_back(EltIdx);
8889     if (EltIdx < 0) {
8890       ++Quad[0];
8891       ++Quad[1];
8892       ++Quad[2];
8893       ++Quad[3];
8894       continue;
8895     }
8896     ++Quad[EltIdx / 4];
8897     InputQuads.set(EltIdx / 4);
8898   }
8899
8900   int BestLoQuad = -1;
8901   unsigned MaxQuad = 1;
8902   for (unsigned i = 0; i < 4; ++i) {
8903     if (LoQuad[i] > MaxQuad) {
8904       BestLoQuad = i;
8905       MaxQuad = LoQuad[i];
8906     }
8907   }
8908
8909   int BestHiQuad = -1;
8910   MaxQuad = 1;
8911   for (unsigned i = 0; i < 4; ++i) {
8912     if (HiQuad[i] > MaxQuad) {
8913       BestHiQuad = i;
8914       MaxQuad = HiQuad[i];
8915     }
8916   }
8917
8918   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8919   // of the two input vectors, shuffle them into one input vector so only a
8920   // single pshufb instruction is necessary. If there are more than 2 input
8921   // quads, disable the next transformation since it does not help SSSE3.
8922   bool V1Used = InputQuads[0] || InputQuads[1];
8923   bool V2Used = InputQuads[2] || InputQuads[3];
8924   if (Subtarget->hasSSSE3()) {
8925     if (InputQuads.count() == 2 && V1Used && V2Used) {
8926       BestLoQuad = InputQuads[0] ? 0 : 1;
8927       BestHiQuad = InputQuads[2] ? 2 : 3;
8928     }
8929     if (InputQuads.count() > 2) {
8930       BestLoQuad = -1;
8931       BestHiQuad = -1;
8932     }
8933   }
8934
8935   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8936   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8937   // words from all 4 input quadwords.
8938   SDValue NewV;
8939   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8940     int MaskV[] = {
8941       BestLoQuad < 0 ? 0 : BestLoQuad,
8942       BestHiQuad < 0 ? 1 : BestHiQuad
8943     };
8944     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8945                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8946                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8947     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8948
8949     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8950     // source words for the shuffle, to aid later transformations.
8951     bool AllWordsInNewV = true;
8952     bool InOrder[2] = { true, true };
8953     for (unsigned i = 0; i != 8; ++i) {
8954       int idx = MaskVals[i];
8955       if (idx != (int)i)
8956         InOrder[i/4] = false;
8957       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8958         continue;
8959       AllWordsInNewV = false;
8960       break;
8961     }
8962
8963     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8964     if (AllWordsInNewV) {
8965       for (int i = 0; i != 8; ++i) {
8966         int idx = MaskVals[i];
8967         if (idx < 0)
8968           continue;
8969         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8970         if ((idx != i) && idx < 4)
8971           pshufhw = false;
8972         if ((idx != i) && idx > 3)
8973           pshuflw = false;
8974       }
8975       V1 = NewV;
8976       V2Used = false;
8977       BestLoQuad = 0;
8978       BestHiQuad = 1;
8979     }
8980
8981     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8982     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8983     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8984       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8985       unsigned TargetMask = 0;
8986       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8987                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8988       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8989       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8990                              getShufflePSHUFLWImmediate(SVOp);
8991       V1 = NewV.getOperand(0);
8992       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8993     }
8994   }
8995
8996   // Promote splats to a larger type which usually leads to more efficient code.
8997   // FIXME: Is this true if pshufb is available?
8998   if (SVOp->isSplat())
8999     return PromoteSplat(SVOp, DAG);
9000
9001   // If we have SSSE3, and all words of the result are from 1 input vector,
9002   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
9003   // is present, fall back to case 4.
9004   if (Subtarget->hasSSSE3()) {
9005     SmallVector<SDValue,16> pshufbMask;
9006
9007     // If we have elements from both input vectors, set the high bit of the
9008     // shuffle mask element to zero out elements that come from V2 in the V1
9009     // mask, and elements that come from V1 in the V2 mask, so that the two
9010     // results can be OR'd together.
9011     bool TwoInputs = V1Used && V2Used;
9012     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
9013     if (!TwoInputs)
9014       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9015
9016     // Calculate the shuffle mask for the second input, shuffle it, and
9017     // OR it with the first shuffled input.
9018     CommuteVectorShuffleMask(MaskVals, 8);
9019     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
9020     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9021     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9022   }
9023
9024   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
9025   // and update MaskVals with new element order.
9026   std::bitset<8> InOrder;
9027   if (BestLoQuad >= 0) {
9028     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
9029     for (int i = 0; i != 4; ++i) {
9030       int idx = MaskVals[i];
9031       if (idx < 0) {
9032         InOrder.set(i);
9033       } else if ((idx / 4) == BestLoQuad) {
9034         MaskV[i] = idx & 3;
9035         InOrder.set(i);
9036       }
9037     }
9038     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9039                                 &MaskV[0]);
9040
9041     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9042       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9043       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
9044                                   NewV.getOperand(0),
9045                                   getShufflePSHUFLWImmediate(SVOp), DAG);
9046     }
9047   }
9048
9049   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
9050   // and update MaskVals with the new element order.
9051   if (BestHiQuad >= 0) {
9052     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
9053     for (unsigned i = 4; i != 8; ++i) {
9054       int idx = MaskVals[i];
9055       if (idx < 0) {
9056         InOrder.set(i);
9057       } else if ((idx / 4) == BestHiQuad) {
9058         MaskV[i] = (idx & 3) + 4;
9059         InOrder.set(i);
9060       }
9061     }
9062     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9063                                 &MaskV[0]);
9064
9065     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9066       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9067       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
9068                                   NewV.getOperand(0),
9069                                   getShufflePSHUFHWImmediate(SVOp), DAG);
9070     }
9071   }
9072
9073   // In case BestHi & BestLo were both -1, which means each quadword has a word
9074   // from each of the four input quadwords, calculate the InOrder bitvector now
9075   // before falling through to the insert/extract cleanup.
9076   if (BestLoQuad == -1 && BestHiQuad == -1) {
9077     NewV = V1;
9078     for (int i = 0; i != 8; ++i)
9079       if (MaskVals[i] < 0 || MaskVals[i] == i)
9080         InOrder.set(i);
9081   }
9082
9083   // The other elements are put in the right place using pextrw and pinsrw.
9084   for (unsigned i = 0; i != 8; ++i) {
9085     if (InOrder[i])
9086       continue;
9087     int EltIdx = MaskVals[i];
9088     if (EltIdx < 0)
9089       continue;
9090     SDValue ExtOp = (EltIdx < 8) ?
9091       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
9092                   DAG.getIntPtrConstant(EltIdx)) :
9093       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
9094                   DAG.getIntPtrConstant(EltIdx - 8));
9095     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
9096                        DAG.getIntPtrConstant(i));
9097   }
9098   return NewV;
9099 }
9100
9101 /// \brief v16i16 shuffles
9102 ///
9103 /// FIXME: We only support generation of a single pshufb currently.  We can
9104 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
9105 /// well (e.g 2 x pshufb + 1 x por).
9106 static SDValue
9107 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
9108   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9109   SDValue V1 = SVOp->getOperand(0);
9110   SDValue V2 = SVOp->getOperand(1);
9111   SDLoc dl(SVOp);
9112
9113   if (V2.getOpcode() != ISD::UNDEF)
9114     return SDValue();
9115
9116   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9117   return getPSHUFB(MaskVals, V1, dl, DAG);
9118 }
9119
9120 // v16i8 shuffles - Prefer shuffles in the following order:
9121 // 1. [ssse3] 1 x pshufb
9122 // 2. [ssse3] 2 x pshufb + 1 x por
9123 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
9124 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
9125                                         const X86Subtarget* Subtarget,
9126                                         SelectionDAG &DAG) {
9127   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9128   SDValue V1 = SVOp->getOperand(0);
9129   SDValue V2 = SVOp->getOperand(1);
9130   SDLoc dl(SVOp);
9131   ArrayRef<int> MaskVals = SVOp->getMask();
9132
9133   // Promote splats to a larger type which usually leads to more efficient code.
9134   // FIXME: Is this true if pshufb is available?
9135   if (SVOp->isSplat())
9136     return PromoteSplat(SVOp, DAG);
9137
9138   // If we have SSSE3, case 1 is generated when all result bytes come from
9139   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
9140   // present, fall back to case 3.
9141
9142   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
9143   if (Subtarget->hasSSSE3()) {
9144     SmallVector<SDValue,16> pshufbMask;
9145
9146     // If all result elements are from one input vector, then only translate
9147     // undef mask values to 0x80 (zero out result) in the pshufb mask.
9148     //
9149     // Otherwise, we have elements from both input vectors, and must zero out
9150     // elements that come from V2 in the first mask, and V1 in the second mask
9151     // so that we can OR them together.
9152     for (unsigned i = 0; i != 16; ++i) {
9153       int EltIdx = MaskVals[i];
9154       if (EltIdx < 0 || EltIdx >= 16)
9155         EltIdx = 0x80;
9156       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9157     }
9158     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
9159                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9160                                  MVT::v16i8, pshufbMask));
9161
9162     // As PSHUFB will zero elements with negative indices, it's safe to ignore
9163     // the 2nd operand if it's undefined or zero.
9164     if (V2.getOpcode() == ISD::UNDEF ||
9165         ISD::isBuildVectorAllZeros(V2.getNode()))
9166       return V1;
9167
9168     // Calculate the shuffle mask for the second input, shuffle it, and
9169     // OR it with the first shuffled input.
9170     pshufbMask.clear();
9171     for (unsigned i = 0; i != 16; ++i) {
9172       int EltIdx = MaskVals[i];
9173       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
9174       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9175     }
9176     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
9177                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9178                                  MVT::v16i8, pshufbMask));
9179     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9180   }
9181
9182   // No SSSE3 - Calculate in place words and then fix all out of place words
9183   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
9184   // the 16 different words that comprise the two doublequadword input vectors.
9185   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9186   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9187   SDValue NewV = V1;
9188   for (int i = 0; i != 8; ++i) {
9189     int Elt0 = MaskVals[i*2];
9190     int Elt1 = MaskVals[i*2+1];
9191
9192     // This word of the result is all undef, skip it.
9193     if (Elt0 < 0 && Elt1 < 0)
9194       continue;
9195
9196     // This word of the result is already in the correct place, skip it.
9197     if ((Elt0 == i*2) && (Elt1 == i*2+1))
9198       continue;
9199
9200     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
9201     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
9202     SDValue InsElt;
9203
9204     // If Elt0 and Elt1 are defined, are consecutive, and can be load
9205     // using a single extract together, load it and store it.
9206     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
9207       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9208                            DAG.getIntPtrConstant(Elt1 / 2));
9209       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9210                         DAG.getIntPtrConstant(i));
9211       continue;
9212     }
9213
9214     // If Elt1 is defined, extract it from the appropriate source.  If the
9215     // source byte is not also odd, shift the extracted word left 8 bits
9216     // otherwise clear the bottom 8 bits if we need to do an or.
9217     if (Elt1 >= 0) {
9218       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9219                            DAG.getIntPtrConstant(Elt1 / 2));
9220       if ((Elt1 & 1) == 0)
9221         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
9222                              DAG.getConstant(8,
9223                                   TLI.getShiftAmountTy(InsElt.getValueType())));
9224       else if (Elt0 >= 0)
9225         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
9226                              DAG.getConstant(0xFF00, MVT::i16));
9227     }
9228     // If Elt0 is defined, extract it from the appropriate source.  If the
9229     // source byte is not also even, shift the extracted word right 8 bits. If
9230     // Elt1 was also defined, OR the extracted values together before
9231     // inserting them in the result.
9232     if (Elt0 >= 0) {
9233       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
9234                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
9235       if ((Elt0 & 1) != 0)
9236         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
9237                               DAG.getConstant(8,
9238                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
9239       else if (Elt1 >= 0)
9240         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
9241                              DAG.getConstant(0x00FF, MVT::i16));
9242       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
9243                          : InsElt0;
9244     }
9245     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9246                        DAG.getIntPtrConstant(i));
9247   }
9248   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
9249 }
9250
9251 // v32i8 shuffles - Translate to VPSHUFB if possible.
9252 static
9253 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
9254                                  const X86Subtarget *Subtarget,
9255                                  SelectionDAG &DAG) {
9256   MVT VT = SVOp->getSimpleValueType(0);
9257   SDValue V1 = SVOp->getOperand(0);
9258   SDValue V2 = SVOp->getOperand(1);
9259   SDLoc dl(SVOp);
9260   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9261
9262   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9263   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
9264   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
9265
9266   // VPSHUFB may be generated if
9267   // (1) one of input vector is undefined or zeroinitializer.
9268   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
9269   // And (2) the mask indexes don't cross the 128-bit lane.
9270   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
9271       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
9272     return SDValue();
9273
9274   if (V1IsAllZero && !V2IsAllZero) {
9275     CommuteVectorShuffleMask(MaskVals, 32);
9276     V1 = V2;
9277   }
9278   return getPSHUFB(MaskVals, V1, dl, DAG);
9279 }
9280
9281 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
9282 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
9283 /// done when every pair / quad of shuffle mask elements point to elements in
9284 /// the right sequence. e.g.
9285 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
9286 static
9287 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
9288                                  SelectionDAG &DAG) {
9289   MVT VT = SVOp->getSimpleValueType(0);
9290   SDLoc dl(SVOp);
9291   unsigned NumElems = VT.getVectorNumElements();
9292   MVT NewVT;
9293   unsigned Scale;
9294   switch (VT.SimpleTy) {
9295   default: llvm_unreachable("Unexpected!");
9296   case MVT::v2i64:
9297   case MVT::v2f64:
9298            return SDValue(SVOp, 0);
9299   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
9300   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
9301   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
9302   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
9303   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
9304   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
9305   }
9306
9307   SmallVector<int, 8> MaskVec;
9308   for (unsigned i = 0; i != NumElems; i += Scale) {
9309     int StartIdx = -1;
9310     for (unsigned j = 0; j != Scale; ++j) {
9311       int EltIdx = SVOp->getMaskElt(i+j);
9312       if (EltIdx < 0)
9313         continue;
9314       if (StartIdx < 0)
9315         StartIdx = (EltIdx / Scale);
9316       if (EltIdx != (int)(StartIdx*Scale + j))
9317         return SDValue();
9318     }
9319     MaskVec.push_back(StartIdx);
9320   }
9321
9322   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
9323   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
9324   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
9325 }
9326
9327 /// getVZextMovL - Return a zero-extending vector move low node.
9328 ///
9329 static SDValue getVZextMovL(MVT VT, MVT OpVT,
9330                             SDValue SrcOp, SelectionDAG &DAG,
9331                             const X86Subtarget *Subtarget, SDLoc dl) {
9332   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
9333     LoadSDNode *LD = nullptr;
9334     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
9335       LD = dyn_cast<LoadSDNode>(SrcOp);
9336     if (!LD) {
9337       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
9338       // instead.
9339       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
9340       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
9341           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9342           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
9343           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
9344         // PR2108
9345         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
9346         return DAG.getNode(ISD::BITCAST, dl, VT,
9347                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9348                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9349                                                    OpVT,
9350                                                    SrcOp.getOperand(0)
9351                                                           .getOperand(0))));
9352       }
9353     }
9354   }
9355
9356   return DAG.getNode(ISD::BITCAST, dl, VT,
9357                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9358                                  DAG.getNode(ISD::BITCAST, dl,
9359                                              OpVT, SrcOp)));
9360 }
9361
9362 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
9363 /// which could not be matched by any known target speficic shuffle
9364 static SDValue
9365 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9366
9367   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
9368   if (NewOp.getNode())
9369     return NewOp;
9370
9371   MVT VT = SVOp->getSimpleValueType(0);
9372
9373   unsigned NumElems = VT.getVectorNumElements();
9374   unsigned NumLaneElems = NumElems / 2;
9375
9376   SDLoc dl(SVOp);
9377   MVT EltVT = VT.getVectorElementType();
9378   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
9379   SDValue Output[2];
9380
9381   SmallVector<int, 16> Mask;
9382   for (unsigned l = 0; l < 2; ++l) {
9383     // Build a shuffle mask for the output, discovering on the fly which
9384     // input vectors to use as shuffle operands (recorded in InputUsed).
9385     // If building a suitable shuffle vector proves too hard, then bail
9386     // out with UseBuildVector set.
9387     bool UseBuildVector = false;
9388     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9389     unsigned LaneStart = l * NumLaneElems;
9390     for (unsigned i = 0; i != NumLaneElems; ++i) {
9391       // The mask element.  This indexes into the input.
9392       int Idx = SVOp->getMaskElt(i+LaneStart);
9393       if (Idx < 0) {
9394         // the mask element does not index into any input vector.
9395         Mask.push_back(-1);
9396         continue;
9397       }
9398
9399       // The input vector this mask element indexes into.
9400       int Input = Idx / NumLaneElems;
9401
9402       // Turn the index into an offset from the start of the input vector.
9403       Idx -= Input * NumLaneElems;
9404
9405       // Find or create a shuffle vector operand to hold this input.
9406       unsigned OpNo;
9407       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9408         if (InputUsed[OpNo] == Input)
9409           // This input vector is already an operand.
9410           break;
9411         if (InputUsed[OpNo] < 0) {
9412           // Create a new operand for this input vector.
9413           InputUsed[OpNo] = Input;
9414           break;
9415         }
9416       }
9417
9418       if (OpNo >= array_lengthof(InputUsed)) {
9419         // More than two input vectors used!  Give up on trying to create a
9420         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
9421         UseBuildVector = true;
9422         break;
9423       }
9424
9425       // Add the mask index for the new shuffle vector.
9426       Mask.push_back(Idx + OpNo * NumLaneElems);
9427     }
9428
9429     if (UseBuildVector) {
9430       SmallVector<SDValue, 16> SVOps;
9431       for (unsigned i = 0; i != NumLaneElems; ++i) {
9432         // The mask element.  This indexes into the input.
9433         int Idx = SVOp->getMaskElt(i+LaneStart);
9434         if (Idx < 0) {
9435           SVOps.push_back(DAG.getUNDEF(EltVT));
9436           continue;
9437         }
9438
9439         // The input vector this mask element indexes into.
9440         int Input = Idx / NumElems;
9441
9442         // Turn the index into an offset from the start of the input vector.
9443         Idx -= Input * NumElems;
9444
9445         // Extract the vector element by hand.
9446         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9447                                     SVOp->getOperand(Input),
9448                                     DAG.getIntPtrConstant(Idx)));
9449       }
9450
9451       // Construct the output using a BUILD_VECTOR.
9452       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9453     } else if (InputUsed[0] < 0) {
9454       // No input vectors were used! The result is undefined.
9455       Output[l] = DAG.getUNDEF(NVT);
9456     } else {
9457       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9458                                         (InputUsed[0] % 2) * NumLaneElems,
9459                                         DAG, dl);
9460       // If only one input was used, use an undefined vector for the other.
9461       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9462         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9463                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9464       // At least one input vector was used. Create a new shuffle vector.
9465       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9466     }
9467
9468     Mask.clear();
9469   }
9470
9471   // Concatenate the result back
9472   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9473 }
9474
9475 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9476 /// 4 elements, and match them with several different shuffle types.
9477 static SDValue
9478 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9479   SDValue V1 = SVOp->getOperand(0);
9480   SDValue V2 = SVOp->getOperand(1);
9481   SDLoc dl(SVOp);
9482   MVT VT = SVOp->getSimpleValueType(0);
9483
9484   assert(VT.is128BitVector() && "Unsupported vector size");
9485
9486   std::pair<int, int> Locs[4];
9487   int Mask1[] = { -1, -1, -1, -1 };
9488   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9489
9490   unsigned NumHi = 0;
9491   unsigned NumLo = 0;
9492   for (unsigned i = 0; i != 4; ++i) {
9493     int Idx = PermMask[i];
9494     if (Idx < 0) {
9495       Locs[i] = std::make_pair(-1, -1);
9496     } else {
9497       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9498       if (Idx < 4) {
9499         Locs[i] = std::make_pair(0, NumLo);
9500         Mask1[NumLo] = Idx;
9501         NumLo++;
9502       } else {
9503         Locs[i] = std::make_pair(1, NumHi);
9504         if (2+NumHi < 4)
9505           Mask1[2+NumHi] = Idx;
9506         NumHi++;
9507       }
9508     }
9509   }
9510
9511   if (NumLo <= 2 && NumHi <= 2) {
9512     // If no more than two elements come from either vector. This can be
9513     // implemented with two shuffles. First shuffle gather the elements.
9514     // The second shuffle, which takes the first shuffle as both of its
9515     // vector operands, put the elements into the right order.
9516     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9517
9518     int Mask2[] = { -1, -1, -1, -1 };
9519
9520     for (unsigned i = 0; i != 4; ++i)
9521       if (Locs[i].first != -1) {
9522         unsigned Idx = (i < 2) ? 0 : 4;
9523         Idx += Locs[i].first * 2 + Locs[i].second;
9524         Mask2[i] = Idx;
9525       }
9526
9527     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9528   }
9529
9530   if (NumLo == 3 || NumHi == 3) {
9531     // Otherwise, we must have three elements from one vector, call it X, and
9532     // one element from the other, call it Y.  First, use a shufps to build an
9533     // intermediate vector with the one element from Y and the element from X
9534     // that will be in the same half in the final destination (the indexes don't
9535     // matter). Then, use a shufps to build the final vector, taking the half
9536     // containing the element from Y from the intermediate, and the other half
9537     // from X.
9538     if (NumHi == 3) {
9539       // Normalize it so the 3 elements come from V1.
9540       CommuteVectorShuffleMask(PermMask, 4);
9541       std::swap(V1, V2);
9542     }
9543
9544     // Find the element from V2.
9545     unsigned HiIndex;
9546     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9547       int Val = PermMask[HiIndex];
9548       if (Val < 0)
9549         continue;
9550       if (Val >= 4)
9551         break;
9552     }
9553
9554     Mask1[0] = PermMask[HiIndex];
9555     Mask1[1] = -1;
9556     Mask1[2] = PermMask[HiIndex^1];
9557     Mask1[3] = -1;
9558     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9559
9560     if (HiIndex >= 2) {
9561       Mask1[0] = PermMask[0];
9562       Mask1[1] = PermMask[1];
9563       Mask1[2] = HiIndex & 1 ? 6 : 4;
9564       Mask1[3] = HiIndex & 1 ? 4 : 6;
9565       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9566     }
9567
9568     Mask1[0] = HiIndex & 1 ? 2 : 0;
9569     Mask1[1] = HiIndex & 1 ? 0 : 2;
9570     Mask1[2] = PermMask[2];
9571     Mask1[3] = PermMask[3];
9572     if (Mask1[2] >= 0)
9573       Mask1[2] += 4;
9574     if (Mask1[3] >= 0)
9575       Mask1[3] += 4;
9576     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9577   }
9578
9579   // Break it into (shuffle shuffle_hi, shuffle_lo).
9580   int LoMask[] = { -1, -1, -1, -1 };
9581   int HiMask[] = { -1, -1, -1, -1 };
9582
9583   int *MaskPtr = LoMask;
9584   unsigned MaskIdx = 0;
9585   unsigned LoIdx = 0;
9586   unsigned HiIdx = 2;
9587   for (unsigned i = 0; i != 4; ++i) {
9588     if (i == 2) {
9589       MaskPtr = HiMask;
9590       MaskIdx = 1;
9591       LoIdx = 0;
9592       HiIdx = 2;
9593     }
9594     int Idx = PermMask[i];
9595     if (Idx < 0) {
9596       Locs[i] = std::make_pair(-1, -1);
9597     } else if (Idx < 4) {
9598       Locs[i] = std::make_pair(MaskIdx, LoIdx);
9599       MaskPtr[LoIdx] = Idx;
9600       LoIdx++;
9601     } else {
9602       Locs[i] = std::make_pair(MaskIdx, HiIdx);
9603       MaskPtr[HiIdx] = Idx;
9604       HiIdx++;
9605     }
9606   }
9607
9608   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9609   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9610   int MaskOps[] = { -1, -1, -1, -1 };
9611   for (unsigned i = 0; i != 4; ++i)
9612     if (Locs[i].first != -1)
9613       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9614   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9615 }
9616
9617 static bool MayFoldVectorLoad(SDValue V) {
9618   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9619     V = V.getOperand(0);
9620
9621   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9622     V = V.getOperand(0);
9623   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9624       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9625     // BUILD_VECTOR (load), undef
9626     V = V.getOperand(0);
9627
9628   return MayFoldLoad(V);
9629 }
9630
9631 static
9632 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9633   MVT VT = Op.getSimpleValueType();
9634
9635   // Canonizalize to v2f64.
9636   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9637   return DAG.getNode(ISD::BITCAST, dl, VT,
9638                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9639                                           V1, DAG));
9640 }
9641
9642 static
9643 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9644                         bool HasSSE2) {
9645   SDValue V1 = Op.getOperand(0);
9646   SDValue V2 = Op.getOperand(1);
9647   MVT VT = Op.getSimpleValueType();
9648
9649   assert(VT != MVT::v2i64 && "unsupported shuffle type");
9650
9651   if (HasSSE2 && VT == MVT::v2f64)
9652     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9653
9654   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9655   return DAG.getNode(ISD::BITCAST, dl, VT,
9656                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9657                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9658                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9659 }
9660
9661 static
9662 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9663   SDValue V1 = Op.getOperand(0);
9664   SDValue V2 = Op.getOperand(1);
9665   MVT VT = Op.getSimpleValueType();
9666
9667   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9668          "unsupported shuffle type");
9669
9670   if (V2.getOpcode() == ISD::UNDEF)
9671     V2 = V1;
9672
9673   // v4i32 or v4f32
9674   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9675 }
9676
9677 static
9678 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9679   SDValue V1 = Op.getOperand(0);
9680   SDValue V2 = Op.getOperand(1);
9681   MVT VT = Op.getSimpleValueType();
9682   unsigned NumElems = VT.getVectorNumElements();
9683
9684   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9685   // operand of these instructions is only memory, so check if there's a
9686   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9687   // same masks.
9688   bool CanFoldLoad = false;
9689
9690   // Trivial case, when V2 comes from a load.
9691   if (MayFoldVectorLoad(V2))
9692     CanFoldLoad = true;
9693
9694   // When V1 is a load, it can be folded later into a store in isel, example:
9695   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9696   //    turns into:
9697   //  (MOVLPSmr addr:$src1, VR128:$src2)
9698   // So, recognize this potential and also use MOVLPS or MOVLPD
9699   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9700     CanFoldLoad = true;
9701
9702   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9703   if (CanFoldLoad) {
9704     if (HasSSE2 && NumElems == 2)
9705       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9706
9707     if (NumElems == 4)
9708       // If we don't care about the second element, proceed to use movss.
9709       if (SVOp->getMaskElt(1) != -1)
9710         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9711   }
9712
9713   // movl and movlp will both match v2i64, but v2i64 is never matched by
9714   // movl earlier because we make it strict to avoid messing with the movlp load
9715   // folding logic (see the code above getMOVLP call). Match it here then,
9716   // this is horrible, but will stay like this until we move all shuffle
9717   // matching to x86 specific nodes. Note that for the 1st condition all
9718   // types are matched with movsd.
9719   if (HasSSE2) {
9720     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9721     // as to remove this logic from here, as much as possible
9722     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9723       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9724     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9725   }
9726
9727   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9728
9729   // Invert the operand order and use SHUFPS to match it.
9730   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9731                               getShuffleSHUFImmediate(SVOp), DAG);
9732 }
9733
9734 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9735                                          SelectionDAG &DAG) {
9736   SDLoc dl(Load);
9737   MVT VT = Load->getSimpleValueType(0);
9738   MVT EVT = VT.getVectorElementType();
9739   SDValue Addr = Load->getOperand(1);
9740   SDValue NewAddr = DAG.getNode(
9741       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9742       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9743
9744   SDValue NewLoad =
9745       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9746                   DAG.getMachineFunction().getMachineMemOperand(
9747                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9748   return NewLoad;
9749 }
9750
9751 // It is only safe to call this function if isINSERTPSMask is true for
9752 // this shufflevector mask.
9753 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9754                            SelectionDAG &DAG) {
9755   // Generate an insertps instruction when inserting an f32 from memory onto a
9756   // v4f32 or when copying a member from one v4f32 to another.
9757   // We also use it for transferring i32 from one register to another,
9758   // since it simply copies the same bits.
9759   // If we're transferring an i32 from memory to a specific element in a
9760   // register, we output a generic DAG that will match the PINSRD
9761   // instruction.
9762   MVT VT = SVOp->getSimpleValueType(0);
9763   MVT EVT = VT.getVectorElementType();
9764   SDValue V1 = SVOp->getOperand(0);
9765   SDValue V2 = SVOp->getOperand(1);
9766   auto Mask = SVOp->getMask();
9767   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9768          "unsupported vector type for insertps/pinsrd");
9769
9770   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9771   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9772   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9773
9774   SDValue From;
9775   SDValue To;
9776   unsigned DestIndex;
9777   if (FromV1 == 1) {
9778     From = V1;
9779     To = V2;
9780     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9781                 Mask.begin();
9782
9783     // If we have 1 element from each vector, we have to check if we're
9784     // changing V1's element's place. If so, we're done. Otherwise, we
9785     // should assume we're changing V2's element's place and behave
9786     // accordingly.
9787     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9788     assert(DestIndex <= INT32_MAX && "truncated destination index");
9789     if (FromV1 == FromV2 &&
9790         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9791       From = V2;
9792       To = V1;
9793       DestIndex =
9794           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9795     }
9796   } else {
9797     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9798            "More than one element from V1 and from V2, or no elements from one "
9799            "of the vectors. This case should not have returned true from "
9800            "isINSERTPSMask");
9801     From = V2;
9802     To = V1;
9803     DestIndex =
9804         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9805   }
9806
9807   // Get an index into the source vector in the range [0,4) (the mask is
9808   // in the range [0,8) because it can address V1 and V2)
9809   unsigned SrcIndex = Mask[DestIndex] % 4;
9810   if (MayFoldLoad(From)) {
9811     // Trivial case, when From comes from a load and is only used by the
9812     // shuffle. Make it use insertps from the vector that we need from that
9813     // load.
9814     SDValue NewLoad =
9815         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9816     if (!NewLoad.getNode())
9817       return SDValue();
9818
9819     if (EVT == MVT::f32) {
9820       // Create this as a scalar to vector to match the instruction pattern.
9821       SDValue LoadScalarToVector =
9822           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9823       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9824       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9825                          InsertpsMask);
9826     } else { // EVT == MVT::i32
9827       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9828       // instruction, to match the PINSRD instruction, which loads an i32 to a
9829       // certain vector element.
9830       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9831                          DAG.getConstant(DestIndex, MVT::i32));
9832     }
9833   }
9834
9835   // Vector-element-to-vector
9836   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9837   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9838 }
9839
9840 // Reduce a vector shuffle to zext.
9841 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9842                                     SelectionDAG &DAG) {
9843   // PMOVZX is only available from SSE41.
9844   if (!Subtarget->hasSSE41())
9845     return SDValue();
9846
9847   MVT VT = Op.getSimpleValueType();
9848
9849   // Only AVX2 support 256-bit vector integer extending.
9850   if (!Subtarget->hasInt256() && VT.is256BitVector())
9851     return SDValue();
9852
9853   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9854   SDLoc DL(Op);
9855   SDValue V1 = Op.getOperand(0);
9856   SDValue V2 = Op.getOperand(1);
9857   unsigned NumElems = VT.getVectorNumElements();
9858
9859   // Extending is an unary operation and the element type of the source vector
9860   // won't be equal to or larger than i64.
9861   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9862       VT.getVectorElementType() == MVT::i64)
9863     return SDValue();
9864
9865   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9866   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9867   while ((1U << Shift) < NumElems) {
9868     if (SVOp->getMaskElt(1U << Shift) == 1)
9869       break;
9870     Shift += 1;
9871     // The maximal ratio is 8, i.e. from i8 to i64.
9872     if (Shift > 3)
9873       return SDValue();
9874   }
9875
9876   // Check the shuffle mask.
9877   unsigned Mask = (1U << Shift) - 1;
9878   for (unsigned i = 0; i != NumElems; ++i) {
9879     int EltIdx = SVOp->getMaskElt(i);
9880     if ((i & Mask) != 0 && EltIdx != -1)
9881       return SDValue();
9882     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9883       return SDValue();
9884   }
9885
9886   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9887   MVT NeVT = MVT::getIntegerVT(NBits);
9888   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9889
9890   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9891     return SDValue();
9892
9893   // Simplify the operand as it's prepared to be fed into shuffle.
9894   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9895   if (V1.getOpcode() == ISD::BITCAST &&
9896       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9897       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9898       V1.getOperand(0).getOperand(0)
9899         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9900     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9901     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9902     ConstantSDNode *CIdx =
9903       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9904     // If it's foldable, i.e. normal load with single use, we will let code
9905     // selection to fold it. Otherwise, we will short the conversion sequence.
9906     if (CIdx && CIdx->getZExtValue() == 0 &&
9907         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9908       MVT FullVT = V.getSimpleValueType();
9909       MVT V1VT = V1.getSimpleValueType();
9910       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9911         // The "ext_vec_elt" node is wider than the result node.
9912         // In this case we should extract subvector from V.
9913         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9914         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9915         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9916                                         FullVT.getVectorNumElements()/Ratio);
9917         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9918                         DAG.getIntPtrConstant(0));
9919       }
9920       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9921     }
9922   }
9923
9924   return DAG.getNode(ISD::BITCAST, DL, VT,
9925                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9926 }
9927
9928 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9929                                       SelectionDAG &DAG) {
9930   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9931   MVT VT = Op.getSimpleValueType();
9932   SDLoc dl(Op);
9933   SDValue V1 = Op.getOperand(0);
9934   SDValue V2 = Op.getOperand(1);
9935
9936   if (isZeroShuffle(SVOp))
9937     return getZeroVector(VT, Subtarget, DAG, dl);
9938
9939   // Handle splat operations
9940   if (SVOp->isSplat()) {
9941     // Use vbroadcast whenever the splat comes from a foldable load
9942     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9943     if (Broadcast.getNode())
9944       return Broadcast;
9945   }
9946
9947   // Check integer expanding shuffles.
9948   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9949   if (NewOp.getNode())
9950     return NewOp;
9951
9952   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9953   // do it!
9954   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9955       VT == MVT::v32i8) {
9956     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9957     if (NewOp.getNode())
9958       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9959   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9960     // FIXME: Figure out a cleaner way to do this.
9961     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9962       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9963       if (NewOp.getNode()) {
9964         MVT NewVT = NewOp.getSimpleValueType();
9965         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9966                                NewVT, true, false))
9967           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9968                               dl);
9969       }
9970     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9971       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9972       if (NewOp.getNode()) {
9973         MVT NewVT = NewOp.getSimpleValueType();
9974         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9975           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9976                               dl);
9977       }
9978     }
9979   }
9980   return SDValue();
9981 }
9982
9983 SDValue
9984 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9985   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9986   SDValue V1 = Op.getOperand(0);
9987   SDValue V2 = Op.getOperand(1);
9988   MVT VT = Op.getSimpleValueType();
9989   SDLoc dl(Op);
9990   unsigned NumElems = VT.getVectorNumElements();
9991   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9992   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9993   bool V1IsSplat = false;
9994   bool V2IsSplat = false;
9995   bool HasSSE2 = Subtarget->hasSSE2();
9996   bool HasFp256    = Subtarget->hasFp256();
9997   bool HasInt256   = Subtarget->hasInt256();
9998   MachineFunction &MF = DAG.getMachineFunction();
9999   bool OptForSize = MF.getFunction()->getAttributes().
10000     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
10001
10002   // Check if we should use the experimental vector shuffle lowering. If so,
10003   // delegate completely to that code path.
10004   if (ExperimentalVectorShuffleLowering)
10005     return lowerVectorShuffle(Op, Subtarget, DAG);
10006
10007   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10008
10009   if (V1IsUndef && V2IsUndef)
10010     return DAG.getUNDEF(VT);
10011
10012   // When we create a shuffle node we put the UNDEF node to second operand,
10013   // but in some cases the first operand may be transformed to UNDEF.
10014   // In this case we should just commute the node.
10015   if (V1IsUndef)
10016     return DAG.getCommutedVectorShuffle(*SVOp);
10017
10018   // Vector shuffle lowering takes 3 steps:
10019   //
10020   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
10021   //    narrowing and commutation of operands should be handled.
10022   // 2) Matching of shuffles with known shuffle masks to x86 target specific
10023   //    shuffle nodes.
10024   // 3) Rewriting of unmatched masks into new generic shuffle operations,
10025   //    so the shuffle can be broken into other shuffles and the legalizer can
10026   //    try the lowering again.
10027   //
10028   // The general idea is that no vector_shuffle operation should be left to
10029   // be matched during isel, all of them must be converted to a target specific
10030   // node here.
10031
10032   // Normalize the input vectors. Here splats, zeroed vectors, profitable
10033   // narrowing and commutation of operands should be handled. The actual code
10034   // doesn't include all of those, work in progress...
10035   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
10036   if (NewOp.getNode())
10037     return NewOp;
10038
10039   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
10040
10041   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
10042   // unpckh_undef). Only use pshufd if speed is more important than size.
10043   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10044     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10045   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10046     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10047
10048   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
10049       V2IsUndef && MayFoldVectorLoad(V1))
10050     return getMOVDDup(Op, dl, V1, DAG);
10051
10052   if (isMOVHLPS_v_undef_Mask(M, VT))
10053     return getMOVHighToLow(Op, dl, DAG);
10054
10055   // Use to match splats
10056   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
10057       (VT == MVT::v2f64 || VT == MVT::v2i64))
10058     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10059
10060   if (isPSHUFDMask(M, VT)) {
10061     // The actual implementation will match the mask in the if above and then
10062     // during isel it can match several different instructions, not only pshufd
10063     // as its name says, sad but true, emulate the behavior for now...
10064     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
10065       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
10066
10067     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
10068
10069     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
10070       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
10071
10072     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
10073       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
10074                                   DAG);
10075
10076     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
10077                                 TargetMask, DAG);
10078   }
10079
10080   if (isPALIGNRMask(M, VT, Subtarget))
10081     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
10082                                 getShufflePALIGNRImmediate(SVOp),
10083                                 DAG);
10084
10085   if (isVALIGNMask(M, VT, Subtarget))
10086     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
10087                                 getShuffleVALIGNImmediate(SVOp),
10088                                 DAG);
10089
10090   // Check if this can be converted into a logical shift.
10091   bool isLeft = false;
10092   unsigned ShAmt = 0;
10093   SDValue ShVal;
10094   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
10095   if (isShift && ShVal.hasOneUse()) {
10096     // If the shifted value has multiple uses, it may be cheaper to use
10097     // v_set0 + movlhps or movhlps, etc.
10098     MVT EltVT = VT.getVectorElementType();
10099     ShAmt *= EltVT.getSizeInBits();
10100     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10101   }
10102
10103   if (isMOVLMask(M, VT)) {
10104     if (ISD::isBuildVectorAllZeros(V1.getNode()))
10105       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
10106     if (!isMOVLPMask(M, VT)) {
10107       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
10108         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10109
10110       if (VT == MVT::v4i32 || VT == MVT::v4f32)
10111         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10112     }
10113   }
10114
10115   // FIXME: fold these into legal mask.
10116   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
10117     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
10118
10119   if (isMOVHLPSMask(M, VT))
10120     return getMOVHighToLow(Op, dl, DAG);
10121
10122   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
10123     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
10124
10125   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
10126     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
10127
10128   if (isMOVLPMask(M, VT))
10129     return getMOVLP(Op, dl, DAG, HasSSE2);
10130
10131   if (ShouldXformToMOVHLPS(M, VT) ||
10132       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
10133     return DAG.getCommutedVectorShuffle(*SVOp);
10134
10135   if (isShift) {
10136     // No better options. Use a vshldq / vsrldq.
10137     MVT EltVT = VT.getVectorElementType();
10138     ShAmt *= EltVT.getSizeInBits();
10139     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10140   }
10141
10142   bool Commuted = false;
10143   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
10144   // 1,1,1,1 -> v8i16 though.
10145   BitVector UndefElements;
10146   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
10147     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10148       V1IsSplat = true;
10149   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
10150     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10151       V2IsSplat = true;
10152
10153   // Canonicalize the splat or undef, if present, to be on the RHS.
10154   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
10155     CommuteVectorShuffleMask(M, NumElems);
10156     std::swap(V1, V2);
10157     std::swap(V1IsSplat, V2IsSplat);
10158     Commuted = true;
10159   }
10160
10161   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
10162     // Shuffling low element of v1 into undef, just return v1.
10163     if (V2IsUndef)
10164       return V1;
10165     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
10166     // the instruction selector will not match, so get a canonical MOVL with
10167     // swapped operands to undo the commute.
10168     return getMOVL(DAG, dl, VT, V2, V1);
10169   }
10170
10171   if (isUNPCKLMask(M, VT, HasInt256))
10172     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10173
10174   if (isUNPCKHMask(M, VT, HasInt256))
10175     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10176
10177   if (V2IsSplat) {
10178     // Normalize mask so all entries that point to V2 points to its first
10179     // element then try to match unpck{h|l} again. If match, return a
10180     // new vector_shuffle with the corrected mask.p
10181     SmallVector<int, 8> NewMask(M.begin(), M.end());
10182     NormalizeMask(NewMask, NumElems);
10183     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
10184       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10185     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
10186       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10187   }
10188
10189   if (Commuted) {
10190     // Commute is back and try unpck* again.
10191     // FIXME: this seems wrong.
10192     CommuteVectorShuffleMask(M, NumElems);
10193     std::swap(V1, V2);
10194     std::swap(V1IsSplat, V2IsSplat);
10195
10196     if (isUNPCKLMask(M, VT, HasInt256))
10197       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10198
10199     if (isUNPCKHMask(M, VT, HasInt256))
10200       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10201   }
10202
10203   // Normalize the node to match x86 shuffle ops if needed
10204   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
10205     return DAG.getCommutedVectorShuffle(*SVOp);
10206
10207   // The checks below are all present in isShuffleMaskLegal, but they are
10208   // inlined here right now to enable us to directly emit target specific
10209   // nodes, and remove one by one until they don't return Op anymore.
10210
10211   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
10212       SVOp->getSplatIndex() == 0 && V2IsUndef) {
10213     if (VT == MVT::v2f64 || VT == MVT::v2i64)
10214       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10215   }
10216
10217   if (isPSHUFHWMask(M, VT, HasInt256))
10218     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
10219                                 getShufflePSHUFHWImmediate(SVOp),
10220                                 DAG);
10221
10222   if (isPSHUFLWMask(M, VT, HasInt256))
10223     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
10224                                 getShufflePSHUFLWImmediate(SVOp),
10225                                 DAG);
10226
10227   unsigned MaskValue;
10228   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
10229                   &MaskValue))
10230     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
10231
10232   if (isSHUFPMask(M, VT))
10233     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
10234                                 getShuffleSHUFImmediate(SVOp), DAG);
10235
10236   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10237     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10238   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10239     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10240
10241   //===--------------------------------------------------------------------===//
10242   // Generate target specific nodes for 128 or 256-bit shuffles only
10243   // supported in the AVX instruction set.
10244   //
10245
10246   // Handle VMOVDDUPY permutations
10247   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
10248     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
10249
10250   // Handle VPERMILPS/D* permutations
10251   if (isVPERMILPMask(M, VT)) {
10252     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
10253       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
10254                                   getShuffleSHUFImmediate(SVOp), DAG);
10255     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
10256                                 getShuffleSHUFImmediate(SVOp), DAG);
10257   }
10258
10259   unsigned Idx;
10260   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
10261     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
10262                               Idx*(NumElems/2), DAG, dl);
10263
10264   // Handle VPERM2F128/VPERM2I128 permutations
10265   if (isVPERM2X128Mask(M, VT, HasFp256))
10266     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
10267                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
10268
10269   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
10270     return getINSERTPS(SVOp, dl, DAG);
10271
10272   unsigned Imm8;
10273   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
10274     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
10275
10276   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
10277       VT.is512BitVector()) {
10278     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
10279     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
10280     SmallVector<SDValue, 16> permclMask;
10281     for (unsigned i = 0; i != NumElems; ++i) {
10282       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
10283     }
10284
10285     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
10286     if (V2IsUndef)
10287       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
10288       return DAG.getNode(X86ISD::VPERMV, dl, VT,
10289                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
10290     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
10291                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
10292   }
10293
10294   //===--------------------------------------------------------------------===//
10295   // Since no target specific shuffle was selected for this generic one,
10296   // lower it into other known shuffles. FIXME: this isn't true yet, but
10297   // this is the plan.
10298   //
10299
10300   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
10301   if (VT == MVT::v8i16) {
10302     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
10303     if (NewOp.getNode())
10304       return NewOp;
10305   }
10306
10307   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
10308     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
10309     if (NewOp.getNode())
10310       return NewOp;
10311   }
10312
10313   if (VT == MVT::v16i8) {
10314     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
10315     if (NewOp.getNode())
10316       return NewOp;
10317   }
10318
10319   if (VT == MVT::v32i8) {
10320     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
10321     if (NewOp.getNode())
10322       return NewOp;
10323   }
10324
10325   // Handle all 128-bit wide vectors with 4 elements, and match them with
10326   // several different shuffle types.
10327   if (NumElems == 4 && VT.is128BitVector())
10328     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
10329
10330   // Handle general 256-bit shuffles
10331   if (VT.is256BitVector())
10332     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
10333
10334   return SDValue();
10335 }
10336
10337 // This function assumes its argument is a BUILD_VECTOR of constants or
10338 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10339 // true.
10340 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10341                                     unsigned &MaskValue) {
10342   MaskValue = 0;
10343   unsigned NumElems = BuildVector->getNumOperands();
10344   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10345   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10346   unsigned NumElemsInLane = NumElems / NumLanes;
10347
10348   // Blend for v16i16 should be symetric for the both lanes.
10349   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10350     SDValue EltCond = BuildVector->getOperand(i);
10351     SDValue SndLaneEltCond =
10352         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10353
10354     int Lane1Cond = -1, Lane2Cond = -1;
10355     if (isa<ConstantSDNode>(EltCond))
10356       Lane1Cond = !isZero(EltCond);
10357     if (isa<ConstantSDNode>(SndLaneEltCond))
10358       Lane2Cond = !isZero(SndLaneEltCond);
10359
10360     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10361       // Lane1Cond != 0, means we want the first argument.
10362       // Lane1Cond == 0, means we want the second argument.
10363       // The encoding of this argument is 0 for the first argument, 1
10364       // for the second. Therefore, invert the condition.
10365       MaskValue |= !Lane1Cond << i;
10366     else if (Lane1Cond < 0)
10367       MaskValue |= !Lane2Cond << i;
10368     else
10369       return false;
10370   }
10371   return true;
10372 }
10373
10374 // Try to lower a vselect node into a simple blend instruction.
10375 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
10376                                    SelectionDAG &DAG) {
10377   SDValue Cond = Op.getOperand(0);
10378   SDValue LHS = Op.getOperand(1);
10379   SDValue RHS = Op.getOperand(2);
10380   SDLoc dl(Op);
10381   MVT VT = Op.getSimpleValueType();
10382   MVT EltVT = VT.getVectorElementType();
10383   unsigned NumElems = VT.getVectorNumElements();
10384
10385   // There is no blend with immediate in AVX-512.
10386   if (VT.is512BitVector())
10387     return SDValue();
10388
10389   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10390     return SDValue();
10391   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10392     return SDValue();
10393
10394   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10395     return SDValue();
10396
10397   // Check the mask for BLEND and build the value.
10398   unsigned MaskValue = 0;
10399   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10400     return SDValue();
10401
10402   // Convert i32 vectors to floating point if it is not AVX2.
10403   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10404   MVT BlendVT = VT;
10405   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10406     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10407                                NumElems);
10408     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10409     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10410   }
10411
10412   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10413                             DAG.getConstant(MaskValue, MVT::i32));
10414   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10415 }
10416
10417 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10418   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10419   if (BlendOp.getNode())
10420     return BlendOp;
10421
10422   // Some types for vselect were previously set to Expand, not Legal or
10423   // Custom. Return an empty SDValue so we fall-through to Expand, after
10424   // the Custom lowering phase.
10425   MVT VT = Op.getSimpleValueType();
10426   switch (VT.SimpleTy) {
10427   default:
10428     break;
10429   case MVT::v8i16:
10430   case MVT::v16i16:
10431     return SDValue();
10432   }
10433
10434   // We couldn't create a "Blend with immediate" node.
10435   // This node should still be legal, but we'll have to emit a blendv*
10436   // instruction.
10437   return Op;
10438 }
10439
10440 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10441   MVT VT = Op.getSimpleValueType();
10442   SDLoc dl(Op);
10443
10444   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10445     return SDValue();
10446
10447   if (VT.getSizeInBits() == 8) {
10448     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10449                                   Op.getOperand(0), Op.getOperand(1));
10450     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10451                                   DAG.getValueType(VT));
10452     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10453   }
10454
10455   if (VT.getSizeInBits() == 16) {
10456     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10457     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10458     if (Idx == 0)
10459       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10460                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10461                                      DAG.getNode(ISD::BITCAST, dl,
10462                                                  MVT::v4i32,
10463                                                  Op.getOperand(0)),
10464                                      Op.getOperand(1)));
10465     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10466                                   Op.getOperand(0), Op.getOperand(1));
10467     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10468                                   DAG.getValueType(VT));
10469     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10470   }
10471
10472   if (VT == MVT::f32) {
10473     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10474     // the result back to FR32 register. It's only worth matching if the
10475     // result has a single use which is a store or a bitcast to i32.  And in
10476     // the case of a store, it's not worth it if the index is a constant 0,
10477     // because a MOVSSmr can be used instead, which is smaller and faster.
10478     if (!Op.hasOneUse())
10479       return SDValue();
10480     SDNode *User = *Op.getNode()->use_begin();
10481     if ((User->getOpcode() != ISD::STORE ||
10482          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10483           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10484         (User->getOpcode() != ISD::BITCAST ||
10485          User->getValueType(0) != MVT::i32))
10486       return SDValue();
10487     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10488                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10489                                               Op.getOperand(0)),
10490                                               Op.getOperand(1));
10491     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10492   }
10493
10494   if (VT == MVT::i32 || VT == MVT::i64) {
10495     // ExtractPS/pextrq works with constant index.
10496     if (isa<ConstantSDNode>(Op.getOperand(1)))
10497       return Op;
10498   }
10499   return SDValue();
10500 }
10501
10502 /// Extract one bit from mask vector, like v16i1 or v8i1.
10503 /// AVX-512 feature.
10504 SDValue
10505 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10506   SDValue Vec = Op.getOperand(0);
10507   SDLoc dl(Vec);
10508   MVT VecVT = Vec.getSimpleValueType();
10509   SDValue Idx = Op.getOperand(1);
10510   MVT EltVT = Op.getSimpleValueType();
10511
10512   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10513
10514   // variable index can't be handled in mask registers,
10515   // extend vector to VR512
10516   if (!isa<ConstantSDNode>(Idx)) {
10517     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10518     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10519     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10520                               ExtVT.getVectorElementType(), Ext, Idx);
10521     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10522   }
10523
10524   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10525   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10526   unsigned MaxSift = rc->getSize()*8 - 1;
10527   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10528                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10529   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10530                     DAG.getConstant(MaxSift, MVT::i8));
10531   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10532                        DAG.getIntPtrConstant(0));
10533 }
10534
10535 SDValue
10536 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10537                                            SelectionDAG &DAG) const {
10538   SDLoc dl(Op);
10539   SDValue Vec = Op.getOperand(0);
10540   MVT VecVT = Vec.getSimpleValueType();
10541   SDValue Idx = Op.getOperand(1);
10542
10543   if (Op.getSimpleValueType() == MVT::i1)
10544     return ExtractBitFromMaskVector(Op, DAG);
10545
10546   if (!isa<ConstantSDNode>(Idx)) {
10547     if (VecVT.is512BitVector() ||
10548         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10549          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10550
10551       MVT MaskEltVT =
10552         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10553       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10554                                     MaskEltVT.getSizeInBits());
10555
10556       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10557       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10558                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10559                                 Idx, DAG.getConstant(0, getPointerTy()));
10560       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10561       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10562                         Perm, DAG.getConstant(0, getPointerTy()));
10563     }
10564     return SDValue();
10565   }
10566
10567   // If this is a 256-bit vector result, first extract the 128-bit vector and
10568   // then extract the element from the 128-bit vector.
10569   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10570
10571     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10572     // Get the 128-bit vector.
10573     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10574     MVT EltVT = VecVT.getVectorElementType();
10575
10576     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10577
10578     //if (IdxVal >= NumElems/2)
10579     //  IdxVal -= NumElems/2;
10580     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10581     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10582                        DAG.getConstant(IdxVal, MVT::i32));
10583   }
10584
10585   assert(VecVT.is128BitVector() && "Unexpected vector length");
10586
10587   if (Subtarget->hasSSE41()) {
10588     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10589     if (Res.getNode())
10590       return Res;
10591   }
10592
10593   MVT VT = Op.getSimpleValueType();
10594   // TODO: handle v16i8.
10595   if (VT.getSizeInBits() == 16) {
10596     SDValue Vec = Op.getOperand(0);
10597     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10598     if (Idx == 0)
10599       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10600                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10601                                      DAG.getNode(ISD::BITCAST, dl,
10602                                                  MVT::v4i32, Vec),
10603                                      Op.getOperand(1)));
10604     // Transform it so it match pextrw which produces a 32-bit result.
10605     MVT EltVT = MVT::i32;
10606     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10607                                   Op.getOperand(0), Op.getOperand(1));
10608     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10609                                   DAG.getValueType(VT));
10610     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10611   }
10612
10613   if (VT.getSizeInBits() == 32) {
10614     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10615     if (Idx == 0)
10616       return Op;
10617
10618     // SHUFPS the element to the lowest double word, then movss.
10619     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10620     MVT VVT = Op.getOperand(0).getSimpleValueType();
10621     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10622                                        DAG.getUNDEF(VVT), Mask);
10623     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10624                        DAG.getIntPtrConstant(0));
10625   }
10626
10627   if (VT.getSizeInBits() == 64) {
10628     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10629     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10630     //        to match extract_elt for f64.
10631     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10632     if (Idx == 0)
10633       return Op;
10634
10635     // UNPCKHPD the element to the lowest double word, then movsd.
10636     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10637     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10638     int Mask[2] = { 1, -1 };
10639     MVT VVT = Op.getOperand(0).getSimpleValueType();
10640     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10641                                        DAG.getUNDEF(VVT), Mask);
10642     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10643                        DAG.getIntPtrConstant(0));
10644   }
10645
10646   return SDValue();
10647 }
10648
10649 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10650   MVT VT = Op.getSimpleValueType();
10651   MVT EltVT = VT.getVectorElementType();
10652   SDLoc dl(Op);
10653
10654   SDValue N0 = Op.getOperand(0);
10655   SDValue N1 = Op.getOperand(1);
10656   SDValue N2 = Op.getOperand(2);
10657
10658   if (!VT.is128BitVector())
10659     return SDValue();
10660
10661   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
10662       isa<ConstantSDNode>(N2)) {
10663     unsigned Opc;
10664     if (VT == MVT::v8i16)
10665       Opc = X86ISD::PINSRW;
10666     else if (VT == MVT::v16i8)
10667       Opc = X86ISD::PINSRB;
10668     else
10669       Opc = X86ISD::PINSRB;
10670
10671     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10672     // argument.
10673     if (N1.getValueType() != MVT::i32)
10674       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10675     if (N2.getValueType() != MVT::i32)
10676       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10677     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10678   }
10679
10680   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
10681     // Bits [7:6] of the constant are the source select.  This will always be
10682     //  zero here.  The DAG Combiner may combine an extract_elt index into these
10683     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
10684     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10685     // Bits [5:4] of the constant are the destination select.  This is the
10686     //  value of the incoming immediate.
10687     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10688     //   combine either bitwise AND or insert of float 0.0 to set these bits.
10689     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10690     // Create this as a scalar to vector..
10691     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10692     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10693   }
10694
10695   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10696     // PINSR* works with constant index.
10697     return Op;
10698   }
10699   return SDValue();
10700 }
10701
10702 /// Insert one bit to mask vector, like v16i1 or v8i1.
10703 /// AVX-512 feature.
10704 SDValue 
10705 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10706   SDLoc dl(Op);
10707   SDValue Vec = Op.getOperand(0);
10708   SDValue Elt = Op.getOperand(1);
10709   SDValue Idx = Op.getOperand(2);
10710   MVT VecVT = Vec.getSimpleValueType();
10711
10712   if (!isa<ConstantSDNode>(Idx)) {
10713     // Non constant index. Extend source and destination,
10714     // insert element and then truncate the result.
10715     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10716     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10717     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10718       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10719       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10720     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10721   }
10722
10723   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10724   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10725   if (Vec.getOpcode() == ISD::UNDEF)
10726     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10727                        DAG.getConstant(IdxVal, MVT::i8));
10728   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10729   unsigned MaxSift = rc->getSize()*8 - 1;
10730   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10731                     DAG.getConstant(MaxSift, MVT::i8));
10732   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10733                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10734   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10735 }
10736 SDValue
10737 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10738   MVT VT = Op.getSimpleValueType();
10739   MVT EltVT = VT.getVectorElementType();
10740   
10741   if (EltVT == MVT::i1)
10742     return InsertBitToMaskVector(Op, DAG);
10743
10744   SDLoc dl(Op);
10745   SDValue N0 = Op.getOperand(0);
10746   SDValue N1 = Op.getOperand(1);
10747   SDValue N2 = Op.getOperand(2);
10748
10749   // If this is a 256-bit vector result, first extract the 128-bit vector,
10750   // insert the element into the extracted half and then place it back.
10751   if (VT.is256BitVector() || VT.is512BitVector()) {
10752     if (!isa<ConstantSDNode>(N2))
10753       return SDValue();
10754
10755     // Get the desired 128-bit vector half.
10756     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10757     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10758
10759     // Insert the element into the desired half.
10760     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10761     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10762
10763     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10764                     DAG.getConstant(IdxIn128, MVT::i32));
10765
10766     // Insert the changed part back to the 256-bit vector
10767     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10768   }
10769
10770   if (Subtarget->hasSSE41())
10771     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10772
10773   if (EltVT == MVT::i8)
10774     return SDValue();
10775
10776   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10777     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10778     // as its second argument.
10779     if (N1.getValueType() != MVT::i32)
10780       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10781     if (N2.getValueType() != MVT::i32)
10782       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10783     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10784   }
10785   return SDValue();
10786 }
10787
10788 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10789   SDLoc dl(Op);
10790   MVT OpVT = Op.getSimpleValueType();
10791
10792   // If this is a 256-bit vector result, first insert into a 128-bit
10793   // vector and then insert into the 256-bit vector.
10794   if (!OpVT.is128BitVector()) {
10795     // Insert into a 128-bit vector.
10796     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10797     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10798                                  OpVT.getVectorNumElements() / SizeFactor);
10799
10800     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10801
10802     // Insert the 128-bit vector.
10803     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10804   }
10805
10806   if (OpVT == MVT::v1i64 &&
10807       Op.getOperand(0).getValueType() == MVT::i64)
10808     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10809
10810   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10811   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10812   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10813                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10814 }
10815
10816 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10817 // a simple subregister reference or explicit instructions to grab
10818 // upper bits of a vector.
10819 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10820                                       SelectionDAG &DAG) {
10821   SDLoc dl(Op);
10822   SDValue In =  Op.getOperand(0);
10823   SDValue Idx = Op.getOperand(1);
10824   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10825   MVT ResVT   = Op.getSimpleValueType();
10826   MVT InVT    = In.getSimpleValueType();
10827
10828   if (Subtarget->hasFp256()) {
10829     if (ResVT.is128BitVector() &&
10830         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10831         isa<ConstantSDNode>(Idx)) {
10832       return Extract128BitVector(In, IdxVal, DAG, dl);
10833     }
10834     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10835         isa<ConstantSDNode>(Idx)) {
10836       return Extract256BitVector(In, IdxVal, DAG, dl);
10837     }
10838   }
10839   return SDValue();
10840 }
10841
10842 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10843 // simple superregister reference or explicit instructions to insert
10844 // the upper bits of a vector.
10845 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10846                                      SelectionDAG &DAG) {
10847   if (Subtarget->hasFp256()) {
10848     SDLoc dl(Op.getNode());
10849     SDValue Vec = Op.getNode()->getOperand(0);
10850     SDValue SubVec = Op.getNode()->getOperand(1);
10851     SDValue Idx = Op.getNode()->getOperand(2);
10852
10853     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10854          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10855         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10856         isa<ConstantSDNode>(Idx)) {
10857       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10858       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10859     }
10860
10861     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10862         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10863         isa<ConstantSDNode>(Idx)) {
10864       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10865       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10866     }
10867   }
10868   return SDValue();
10869 }
10870
10871 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10872 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10873 // one of the above mentioned nodes. It has to be wrapped because otherwise
10874 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10875 // be used to form addressing mode. These wrapped nodes will be selected
10876 // into MOV32ri.
10877 SDValue
10878 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10879   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10880
10881   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10882   // global base reg.
10883   unsigned char OpFlag = 0;
10884   unsigned WrapperKind = X86ISD::Wrapper;
10885   CodeModel::Model M = DAG.getTarget().getCodeModel();
10886
10887   if (Subtarget->isPICStyleRIPRel() &&
10888       (M == CodeModel::Small || M == CodeModel::Kernel))
10889     WrapperKind = X86ISD::WrapperRIP;
10890   else if (Subtarget->isPICStyleGOT())
10891     OpFlag = X86II::MO_GOTOFF;
10892   else if (Subtarget->isPICStyleStubPIC())
10893     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10894
10895   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10896                                              CP->getAlignment(),
10897                                              CP->getOffset(), OpFlag);
10898   SDLoc DL(CP);
10899   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10900   // With PIC, the address is actually $g + Offset.
10901   if (OpFlag) {
10902     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10903                          DAG.getNode(X86ISD::GlobalBaseReg,
10904                                      SDLoc(), getPointerTy()),
10905                          Result);
10906   }
10907
10908   return Result;
10909 }
10910
10911 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10912   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10913
10914   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10915   // global base reg.
10916   unsigned char OpFlag = 0;
10917   unsigned WrapperKind = X86ISD::Wrapper;
10918   CodeModel::Model M = DAG.getTarget().getCodeModel();
10919
10920   if (Subtarget->isPICStyleRIPRel() &&
10921       (M == CodeModel::Small || M == CodeModel::Kernel))
10922     WrapperKind = X86ISD::WrapperRIP;
10923   else if (Subtarget->isPICStyleGOT())
10924     OpFlag = X86II::MO_GOTOFF;
10925   else if (Subtarget->isPICStyleStubPIC())
10926     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10927
10928   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10929                                           OpFlag);
10930   SDLoc DL(JT);
10931   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10932
10933   // With PIC, the address is actually $g + Offset.
10934   if (OpFlag)
10935     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10936                          DAG.getNode(X86ISD::GlobalBaseReg,
10937                                      SDLoc(), getPointerTy()),
10938                          Result);
10939
10940   return Result;
10941 }
10942
10943 SDValue
10944 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10945   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10946
10947   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10948   // global base reg.
10949   unsigned char OpFlag = 0;
10950   unsigned WrapperKind = X86ISD::Wrapper;
10951   CodeModel::Model M = DAG.getTarget().getCodeModel();
10952
10953   if (Subtarget->isPICStyleRIPRel() &&
10954       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10955     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10956       OpFlag = X86II::MO_GOTPCREL;
10957     WrapperKind = X86ISD::WrapperRIP;
10958   } else if (Subtarget->isPICStyleGOT()) {
10959     OpFlag = X86II::MO_GOT;
10960   } else if (Subtarget->isPICStyleStubPIC()) {
10961     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10962   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10963     OpFlag = X86II::MO_DARWIN_NONLAZY;
10964   }
10965
10966   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10967
10968   SDLoc DL(Op);
10969   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10970
10971   // With PIC, the address is actually $g + Offset.
10972   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10973       !Subtarget->is64Bit()) {
10974     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10975                          DAG.getNode(X86ISD::GlobalBaseReg,
10976                                      SDLoc(), getPointerTy()),
10977                          Result);
10978   }
10979
10980   // For symbols that require a load from a stub to get the address, emit the
10981   // load.
10982   if (isGlobalStubReference(OpFlag))
10983     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10984                          MachinePointerInfo::getGOT(), false, false, false, 0);
10985
10986   return Result;
10987 }
10988
10989 SDValue
10990 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10991   // Create the TargetBlockAddressAddress node.
10992   unsigned char OpFlags =
10993     Subtarget->ClassifyBlockAddressReference();
10994   CodeModel::Model M = DAG.getTarget().getCodeModel();
10995   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10996   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10997   SDLoc dl(Op);
10998   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10999                                              OpFlags);
11000
11001   if (Subtarget->isPICStyleRIPRel() &&
11002       (M == CodeModel::Small || M == CodeModel::Kernel))
11003     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11004   else
11005     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11006
11007   // With PIC, the address is actually $g + Offset.
11008   if (isGlobalRelativeToPICBase(OpFlags)) {
11009     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11010                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11011                          Result);
11012   }
11013
11014   return Result;
11015 }
11016
11017 SDValue
11018 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11019                                       int64_t Offset, SelectionDAG &DAG) const {
11020   // Create the TargetGlobalAddress node, folding in the constant
11021   // offset if it is legal.
11022   unsigned char OpFlags =
11023       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11024   CodeModel::Model M = DAG.getTarget().getCodeModel();
11025   SDValue Result;
11026   if (OpFlags == X86II::MO_NO_FLAG &&
11027       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11028     // A direct static reference to a global.
11029     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11030     Offset = 0;
11031   } else {
11032     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11033   }
11034
11035   if (Subtarget->isPICStyleRIPRel() &&
11036       (M == CodeModel::Small || M == CodeModel::Kernel))
11037     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11038   else
11039     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11040
11041   // With PIC, the address is actually $g + Offset.
11042   if (isGlobalRelativeToPICBase(OpFlags)) {
11043     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11044                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11045                          Result);
11046   }
11047
11048   // For globals that require a load from a stub to get the address, emit the
11049   // load.
11050   if (isGlobalStubReference(OpFlags))
11051     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11052                          MachinePointerInfo::getGOT(), false, false, false, 0);
11053
11054   // If there was a non-zero offset that we didn't fold, create an explicit
11055   // addition for it.
11056   if (Offset != 0)
11057     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11058                          DAG.getConstant(Offset, getPointerTy()));
11059
11060   return Result;
11061 }
11062
11063 SDValue
11064 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11065   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11066   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11067   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11068 }
11069
11070 static SDValue
11071 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11072            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11073            unsigned char OperandFlags, bool LocalDynamic = false) {
11074   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11075   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11076   SDLoc dl(GA);
11077   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11078                                            GA->getValueType(0),
11079                                            GA->getOffset(),
11080                                            OperandFlags);
11081
11082   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11083                                            : X86ISD::TLSADDR;
11084
11085   if (InFlag) {
11086     SDValue Ops[] = { Chain,  TGA, *InFlag };
11087     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11088   } else {
11089     SDValue Ops[]  = { Chain, TGA };
11090     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11091   }
11092
11093   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11094   MFI->setAdjustsStack(true);
11095
11096   SDValue Flag = Chain.getValue(1);
11097   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11098 }
11099
11100 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11101 static SDValue
11102 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11103                                 const EVT PtrVT) {
11104   SDValue InFlag;
11105   SDLoc dl(GA);  // ? function entry point might be better
11106   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11107                                    DAG.getNode(X86ISD::GlobalBaseReg,
11108                                                SDLoc(), PtrVT), InFlag);
11109   InFlag = Chain.getValue(1);
11110
11111   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11112 }
11113
11114 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11115 static SDValue
11116 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11117                                 const EVT PtrVT) {
11118   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11119                     X86::RAX, X86II::MO_TLSGD);
11120 }
11121
11122 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11123                                            SelectionDAG &DAG,
11124                                            const EVT PtrVT,
11125                                            bool is64Bit) {
11126   SDLoc dl(GA);
11127
11128   // Get the start address of the TLS block for this module.
11129   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11130       .getInfo<X86MachineFunctionInfo>();
11131   MFI->incNumLocalDynamicTLSAccesses();
11132
11133   SDValue Base;
11134   if (is64Bit) {
11135     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11136                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11137   } else {
11138     SDValue InFlag;
11139     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11140         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11141     InFlag = Chain.getValue(1);
11142     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11143                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11144   }
11145
11146   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11147   // of Base.
11148
11149   // Build x@dtpoff.
11150   unsigned char OperandFlags = X86II::MO_DTPOFF;
11151   unsigned WrapperKind = X86ISD::Wrapper;
11152   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11153                                            GA->getValueType(0),
11154                                            GA->getOffset(), OperandFlags);
11155   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11156
11157   // Add x@dtpoff with the base.
11158   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11159 }
11160
11161 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11162 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11163                                    const EVT PtrVT, TLSModel::Model model,
11164                                    bool is64Bit, bool isPIC) {
11165   SDLoc dl(GA);
11166
11167   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11168   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11169                                                          is64Bit ? 257 : 256));
11170
11171   SDValue ThreadPointer =
11172       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11173                   MachinePointerInfo(Ptr), false, false, false, 0);
11174
11175   unsigned char OperandFlags = 0;
11176   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11177   // initialexec.
11178   unsigned WrapperKind = X86ISD::Wrapper;
11179   if (model == TLSModel::LocalExec) {
11180     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11181   } else if (model == TLSModel::InitialExec) {
11182     if (is64Bit) {
11183       OperandFlags = X86II::MO_GOTTPOFF;
11184       WrapperKind = X86ISD::WrapperRIP;
11185     } else {
11186       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11187     }
11188   } else {
11189     llvm_unreachable("Unexpected model");
11190   }
11191
11192   // emit "addl x@ntpoff,%eax" (local exec)
11193   // or "addl x@indntpoff,%eax" (initial exec)
11194   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11195   SDValue TGA =
11196       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11197                                  GA->getOffset(), OperandFlags);
11198   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11199
11200   if (model == TLSModel::InitialExec) {
11201     if (isPIC && !is64Bit) {
11202       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11203                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11204                            Offset);
11205     }
11206
11207     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11208                          MachinePointerInfo::getGOT(), false, false, false, 0);
11209   }
11210
11211   // The address of the thread local variable is the add of the thread
11212   // pointer with the offset of the variable.
11213   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11214 }
11215
11216 SDValue
11217 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11218
11219   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11220   const GlobalValue *GV = GA->getGlobal();
11221
11222   if (Subtarget->isTargetELF()) {
11223     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11224
11225     switch (model) {
11226       case TLSModel::GeneralDynamic:
11227         if (Subtarget->is64Bit())
11228           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11229         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11230       case TLSModel::LocalDynamic:
11231         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11232                                            Subtarget->is64Bit());
11233       case TLSModel::InitialExec:
11234       case TLSModel::LocalExec:
11235         return LowerToTLSExecModel(
11236             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11237             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11238     }
11239     llvm_unreachable("Unknown TLS model.");
11240   }
11241
11242   if (Subtarget->isTargetDarwin()) {
11243     // Darwin only has one model of TLS.  Lower to that.
11244     unsigned char OpFlag = 0;
11245     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11246                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11247
11248     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11249     // global base reg.
11250     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11251                  !Subtarget->is64Bit();
11252     if (PIC32)
11253       OpFlag = X86II::MO_TLVP_PIC_BASE;
11254     else
11255       OpFlag = X86II::MO_TLVP;
11256     SDLoc DL(Op);
11257     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11258                                                 GA->getValueType(0),
11259                                                 GA->getOffset(), OpFlag);
11260     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11261
11262     // With PIC32, the address is actually $g + Offset.
11263     if (PIC32)
11264       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11265                            DAG.getNode(X86ISD::GlobalBaseReg,
11266                                        SDLoc(), getPointerTy()),
11267                            Offset);
11268
11269     // Lowering the machine isd will make sure everything is in the right
11270     // location.
11271     SDValue Chain = DAG.getEntryNode();
11272     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11273     SDValue Args[] = { Chain, Offset };
11274     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11275
11276     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11277     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11278     MFI->setAdjustsStack(true);
11279
11280     // And our return value (tls address) is in the standard call return value
11281     // location.
11282     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11283     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11284                               Chain.getValue(1));
11285   }
11286
11287   if (Subtarget->isTargetKnownWindowsMSVC() ||
11288       Subtarget->isTargetWindowsGNU()) {
11289     // Just use the implicit TLS architecture
11290     // Need to generate someting similar to:
11291     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11292     //                                  ; from TEB
11293     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11294     //   mov     rcx, qword [rdx+rcx*8]
11295     //   mov     eax, .tls$:tlsvar
11296     //   [rax+rcx] contains the address
11297     // Windows 64bit: gs:0x58
11298     // Windows 32bit: fs:__tls_array
11299
11300     SDLoc dl(GA);
11301     SDValue Chain = DAG.getEntryNode();
11302
11303     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11304     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11305     // use its literal value of 0x2C.
11306     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11307                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11308                                                              256)
11309                                         : Type::getInt32PtrTy(*DAG.getContext(),
11310                                                               257));
11311
11312     SDValue TlsArray =
11313         Subtarget->is64Bit()
11314             ? DAG.getIntPtrConstant(0x58)
11315             : (Subtarget->isTargetWindowsGNU()
11316                    ? DAG.getIntPtrConstant(0x2C)
11317                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11318
11319     SDValue ThreadPointer =
11320         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11321                     MachinePointerInfo(Ptr), false, false, false, 0);
11322
11323     // Load the _tls_index variable
11324     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11325     if (Subtarget->is64Bit())
11326       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11327                            IDX, MachinePointerInfo(), MVT::i32,
11328                            false, false, false, 0);
11329     else
11330       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11331                         false, false, false, 0);
11332
11333     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11334                                     getPointerTy());
11335     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11336
11337     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11338     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11339                       false, false, false, 0);
11340
11341     // Get the offset of start of .tls section
11342     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11343                                              GA->getValueType(0),
11344                                              GA->getOffset(), X86II::MO_SECREL);
11345     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11346
11347     // The address of the thread local variable is the add of the thread
11348     // pointer with the offset of the variable.
11349     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11350   }
11351
11352   llvm_unreachable("TLS not implemented for this target.");
11353 }
11354
11355 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11356 /// and take a 2 x i32 value to shift plus a shift amount.
11357 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11358   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11359   MVT VT = Op.getSimpleValueType();
11360   unsigned VTBits = VT.getSizeInBits();
11361   SDLoc dl(Op);
11362   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11363   SDValue ShOpLo = Op.getOperand(0);
11364   SDValue ShOpHi = Op.getOperand(1);
11365   SDValue ShAmt  = Op.getOperand(2);
11366   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11367   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11368   // during isel.
11369   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11370                                   DAG.getConstant(VTBits - 1, MVT::i8));
11371   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11372                                      DAG.getConstant(VTBits - 1, MVT::i8))
11373                        : DAG.getConstant(0, VT);
11374
11375   SDValue Tmp2, Tmp3;
11376   if (Op.getOpcode() == ISD::SHL_PARTS) {
11377     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11378     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11379   } else {
11380     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11381     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11382   }
11383
11384   // If the shift amount is larger or equal than the width of a part we can't
11385   // rely on the results of shld/shrd. Insert a test and select the appropriate
11386   // values for large shift amounts.
11387   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11388                                 DAG.getConstant(VTBits, MVT::i8));
11389   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11390                              AndNode, DAG.getConstant(0, MVT::i8));
11391
11392   SDValue Hi, Lo;
11393   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11394   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11395   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11396
11397   if (Op.getOpcode() == ISD::SHL_PARTS) {
11398     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11399     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11400   } else {
11401     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11402     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11403   }
11404
11405   SDValue Ops[2] = { Lo, Hi };
11406   return DAG.getMergeValues(Ops, dl);
11407 }
11408
11409 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11410                                            SelectionDAG &DAG) const {
11411   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11412
11413   if (SrcVT.isVector())
11414     return SDValue();
11415
11416   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11417          "Unknown SINT_TO_FP to lower!");
11418
11419   // These are really Legal; return the operand so the caller accepts it as
11420   // Legal.
11421   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11422     return Op;
11423   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11424       Subtarget->is64Bit()) {
11425     return Op;
11426   }
11427
11428   SDLoc dl(Op);
11429   unsigned Size = SrcVT.getSizeInBits()/8;
11430   MachineFunction &MF = DAG.getMachineFunction();
11431   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11432   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11433   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11434                                StackSlot,
11435                                MachinePointerInfo::getFixedStack(SSFI),
11436                                false, false, 0);
11437   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11438 }
11439
11440 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11441                                      SDValue StackSlot,
11442                                      SelectionDAG &DAG) const {
11443   // Build the FILD
11444   SDLoc DL(Op);
11445   SDVTList Tys;
11446   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11447   if (useSSE)
11448     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11449   else
11450     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11451
11452   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11453
11454   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11455   MachineMemOperand *MMO;
11456   if (FI) {
11457     int SSFI = FI->getIndex();
11458     MMO =
11459       DAG.getMachineFunction()
11460       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11461                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11462   } else {
11463     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11464     StackSlot = StackSlot.getOperand(1);
11465   }
11466   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11467   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11468                                            X86ISD::FILD, DL,
11469                                            Tys, Ops, SrcVT, MMO);
11470
11471   if (useSSE) {
11472     Chain = Result.getValue(1);
11473     SDValue InFlag = Result.getValue(2);
11474
11475     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11476     // shouldn't be necessary except that RFP cannot be live across
11477     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11478     MachineFunction &MF = DAG.getMachineFunction();
11479     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11480     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11481     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11482     Tys = DAG.getVTList(MVT::Other);
11483     SDValue Ops[] = {
11484       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11485     };
11486     MachineMemOperand *MMO =
11487       DAG.getMachineFunction()
11488       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11489                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11490
11491     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11492                                     Ops, Op.getValueType(), MMO);
11493     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11494                          MachinePointerInfo::getFixedStack(SSFI),
11495                          false, false, false, 0);
11496   }
11497
11498   return Result;
11499 }
11500
11501 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11502 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11503                                                SelectionDAG &DAG) const {
11504   // This algorithm is not obvious. Here it is what we're trying to output:
11505   /*
11506      movq       %rax,  %xmm0
11507      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11508      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11509      #ifdef __SSE3__
11510        haddpd   %xmm0, %xmm0
11511      #else
11512        pshufd   $0x4e, %xmm0, %xmm1
11513        addpd    %xmm1, %xmm0
11514      #endif
11515   */
11516
11517   SDLoc dl(Op);
11518   LLVMContext *Context = DAG.getContext();
11519
11520   // Build some magic constants.
11521   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11522   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11523   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11524
11525   SmallVector<Constant*,2> CV1;
11526   CV1.push_back(
11527     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11528                                       APInt(64, 0x4330000000000000ULL))));
11529   CV1.push_back(
11530     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11531                                       APInt(64, 0x4530000000000000ULL))));
11532   Constant *C1 = ConstantVector::get(CV1);
11533   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11534
11535   // Load the 64-bit value into an XMM register.
11536   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11537                             Op.getOperand(0));
11538   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11539                               MachinePointerInfo::getConstantPool(),
11540                               false, false, false, 16);
11541   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11542                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11543                               CLod0);
11544
11545   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11546                               MachinePointerInfo::getConstantPool(),
11547                               false, false, false, 16);
11548   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11549   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11550   SDValue Result;
11551
11552   if (Subtarget->hasSSE3()) {
11553     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11554     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11555   } else {
11556     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11557     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11558                                            S2F, 0x4E, DAG);
11559     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11560                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11561                          Sub);
11562   }
11563
11564   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11565                      DAG.getIntPtrConstant(0));
11566 }
11567
11568 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11569 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11570                                                SelectionDAG &DAG) const {
11571   SDLoc dl(Op);
11572   // FP constant to bias correct the final result.
11573   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11574                                    MVT::f64);
11575
11576   // Load the 32-bit value into an XMM register.
11577   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11578                              Op.getOperand(0));
11579
11580   // Zero out the upper parts of the register.
11581   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11582
11583   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11584                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11585                      DAG.getIntPtrConstant(0));
11586
11587   // Or the load with the bias.
11588   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11589                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11590                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11591                                                    MVT::v2f64, Load)),
11592                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11593                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11594                                                    MVT::v2f64, Bias)));
11595   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11596                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11597                    DAG.getIntPtrConstant(0));
11598
11599   // Subtract the bias.
11600   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11601
11602   // Handle final rounding.
11603   EVT DestVT = Op.getValueType();
11604
11605   if (DestVT.bitsLT(MVT::f64))
11606     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11607                        DAG.getIntPtrConstant(0));
11608   if (DestVT.bitsGT(MVT::f64))
11609     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11610
11611   // Handle final rounding.
11612   return Sub;
11613 }
11614
11615 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11616                                                SelectionDAG &DAG) const {
11617   SDValue N0 = Op.getOperand(0);
11618   MVT SVT = N0.getSimpleValueType();
11619   SDLoc dl(Op);
11620
11621   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11622           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11623          "Custom UINT_TO_FP is not supported!");
11624
11625   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11626   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11627                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11628 }
11629
11630 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11631                                            SelectionDAG &DAG) const {
11632   SDValue N0 = Op.getOperand(0);
11633   SDLoc dl(Op);
11634
11635   if (Op.getValueType().isVector())
11636     return lowerUINT_TO_FP_vec(Op, DAG);
11637
11638   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11639   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11640   // the optimization here.
11641   if (DAG.SignBitIsZero(N0))
11642     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11643
11644   MVT SrcVT = N0.getSimpleValueType();
11645   MVT DstVT = Op.getSimpleValueType();
11646   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11647     return LowerUINT_TO_FP_i64(Op, DAG);
11648   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11649     return LowerUINT_TO_FP_i32(Op, DAG);
11650   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11651     return SDValue();
11652
11653   // Make a 64-bit buffer, and use it to build an FILD.
11654   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11655   if (SrcVT == MVT::i32) {
11656     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11657     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11658                                      getPointerTy(), StackSlot, WordOff);
11659     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11660                                   StackSlot, MachinePointerInfo(),
11661                                   false, false, 0);
11662     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11663                                   OffsetSlot, MachinePointerInfo(),
11664                                   false, false, 0);
11665     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11666     return Fild;
11667   }
11668
11669   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11670   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11671                                StackSlot, MachinePointerInfo(),
11672                                false, false, 0);
11673   // For i64 source, we need to add the appropriate power of 2 if the input
11674   // was negative.  This is the same as the optimization in
11675   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11676   // we must be careful to do the computation in x87 extended precision, not
11677   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11678   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11679   MachineMemOperand *MMO =
11680     DAG.getMachineFunction()
11681     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11682                           MachineMemOperand::MOLoad, 8, 8);
11683
11684   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11685   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11686   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11687                                          MVT::i64, MMO);
11688
11689   APInt FF(32, 0x5F800000ULL);
11690
11691   // Check whether the sign bit is set.
11692   SDValue SignSet = DAG.getSetCC(dl,
11693                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11694                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11695                                  ISD::SETLT);
11696
11697   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11698   SDValue FudgePtr = DAG.getConstantPool(
11699                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11700                                          getPointerTy());
11701
11702   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11703   SDValue Zero = DAG.getIntPtrConstant(0);
11704   SDValue Four = DAG.getIntPtrConstant(4);
11705   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11706                                Zero, Four);
11707   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11708
11709   // Load the value out, extending it from f32 to f80.
11710   // FIXME: Avoid the extend by constructing the right constant pool?
11711   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11712                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11713                                  MVT::f32, false, false, false, 4);
11714   // Extend everything to 80 bits to force it to be done on x87.
11715   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11716   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11717 }
11718
11719 std::pair<SDValue,SDValue>
11720 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11721                                     bool IsSigned, bool IsReplace) const {
11722   SDLoc DL(Op);
11723
11724   EVT DstTy = Op.getValueType();
11725
11726   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11727     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11728     DstTy = MVT::i64;
11729   }
11730
11731   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11732          DstTy.getSimpleVT() >= MVT::i16 &&
11733          "Unknown FP_TO_INT to lower!");
11734
11735   // These are really Legal.
11736   if (DstTy == MVT::i32 &&
11737       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11738     return std::make_pair(SDValue(), SDValue());
11739   if (Subtarget->is64Bit() &&
11740       DstTy == MVT::i64 &&
11741       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11742     return std::make_pair(SDValue(), SDValue());
11743
11744   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11745   // stack slot, or into the FTOL runtime function.
11746   MachineFunction &MF = DAG.getMachineFunction();
11747   unsigned MemSize = DstTy.getSizeInBits()/8;
11748   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11749   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11750
11751   unsigned Opc;
11752   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11753     Opc = X86ISD::WIN_FTOL;
11754   else
11755     switch (DstTy.getSimpleVT().SimpleTy) {
11756     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11757     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11758     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11759     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11760     }
11761
11762   SDValue Chain = DAG.getEntryNode();
11763   SDValue Value = Op.getOperand(0);
11764   EVT TheVT = Op.getOperand(0).getValueType();
11765   // FIXME This causes a redundant load/store if the SSE-class value is already
11766   // in memory, such as if it is on the callstack.
11767   if (isScalarFPTypeInSSEReg(TheVT)) {
11768     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11769     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11770                          MachinePointerInfo::getFixedStack(SSFI),
11771                          false, false, 0);
11772     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11773     SDValue Ops[] = {
11774       Chain, StackSlot, DAG.getValueType(TheVT)
11775     };
11776
11777     MachineMemOperand *MMO =
11778       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11779                               MachineMemOperand::MOLoad, MemSize, MemSize);
11780     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11781     Chain = Value.getValue(1);
11782     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11783     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11784   }
11785
11786   MachineMemOperand *MMO =
11787     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11788                             MachineMemOperand::MOStore, MemSize, MemSize);
11789
11790   if (Opc != X86ISD::WIN_FTOL) {
11791     // Build the FP_TO_INT*_IN_MEM
11792     SDValue Ops[] = { Chain, Value, StackSlot };
11793     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11794                                            Ops, DstTy, MMO);
11795     return std::make_pair(FIST, StackSlot);
11796   } else {
11797     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11798       DAG.getVTList(MVT::Other, MVT::Glue),
11799       Chain, Value);
11800     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11801       MVT::i32, ftol.getValue(1));
11802     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11803       MVT::i32, eax.getValue(2));
11804     SDValue Ops[] = { eax, edx };
11805     SDValue pair = IsReplace
11806       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11807       : DAG.getMergeValues(Ops, DL);
11808     return std::make_pair(pair, SDValue());
11809   }
11810 }
11811
11812 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11813                               const X86Subtarget *Subtarget) {
11814   MVT VT = Op->getSimpleValueType(0);
11815   SDValue In = Op->getOperand(0);
11816   MVT InVT = In.getSimpleValueType();
11817   SDLoc dl(Op);
11818
11819   // Optimize vectors in AVX mode:
11820   //
11821   //   v8i16 -> v8i32
11822   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11823   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11824   //   Concat upper and lower parts.
11825   //
11826   //   v4i32 -> v4i64
11827   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11828   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11829   //   Concat upper and lower parts.
11830   //
11831
11832   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11833       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11834       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11835     return SDValue();
11836
11837   if (Subtarget->hasInt256())
11838     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11839
11840   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11841   SDValue Undef = DAG.getUNDEF(InVT);
11842   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11843   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11844   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11845
11846   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11847                              VT.getVectorNumElements()/2);
11848
11849   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11850   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11851
11852   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11853 }
11854
11855 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11856                                         SelectionDAG &DAG) {
11857   MVT VT = Op->getSimpleValueType(0);
11858   SDValue In = Op->getOperand(0);
11859   MVT InVT = In.getSimpleValueType();
11860   SDLoc DL(Op);
11861   unsigned int NumElts = VT.getVectorNumElements();
11862   if (NumElts != 8 && NumElts != 16)
11863     return SDValue();
11864
11865   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11866     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11867
11868   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11869   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11870   // Now we have only mask extension
11871   assert(InVT.getVectorElementType() == MVT::i1);
11872   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11873   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11874   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11875   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11876   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11877                            MachinePointerInfo::getConstantPool(),
11878                            false, false, false, Alignment);
11879
11880   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11881   if (VT.is512BitVector())
11882     return Brcst;
11883   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11884 }
11885
11886 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11887                                SelectionDAG &DAG) {
11888   if (Subtarget->hasFp256()) {
11889     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11890     if (Res.getNode())
11891       return Res;
11892   }
11893
11894   return SDValue();
11895 }
11896
11897 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11898                                 SelectionDAG &DAG) {
11899   SDLoc DL(Op);
11900   MVT VT = Op.getSimpleValueType();
11901   SDValue In = Op.getOperand(0);
11902   MVT SVT = In.getSimpleValueType();
11903
11904   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11905     return LowerZERO_EXTEND_AVX512(Op, DAG);
11906
11907   if (Subtarget->hasFp256()) {
11908     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11909     if (Res.getNode())
11910       return Res;
11911   }
11912
11913   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11914          VT.getVectorNumElements() != SVT.getVectorNumElements());
11915   return SDValue();
11916 }
11917
11918 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11919   SDLoc DL(Op);
11920   MVT VT = Op.getSimpleValueType();
11921   SDValue In = Op.getOperand(0);
11922   MVT InVT = In.getSimpleValueType();
11923
11924   if (VT == MVT::i1) {
11925     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11926            "Invalid scalar TRUNCATE operation");
11927     if (InVT.getSizeInBits() >= 32)
11928       return SDValue();
11929     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11930     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11931   }
11932   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11933          "Invalid TRUNCATE operation");
11934
11935   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11936     if (VT.getVectorElementType().getSizeInBits() >=8)
11937       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11938
11939     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11940     unsigned NumElts = InVT.getVectorNumElements();
11941     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11942     if (InVT.getSizeInBits() < 512) {
11943       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11944       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11945       InVT = ExtVT;
11946     }
11947     
11948     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11949     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11950     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11951     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11952     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11953                            MachinePointerInfo::getConstantPool(),
11954                            false, false, false, Alignment);
11955     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11956     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11957     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11958   }
11959
11960   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11961     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11962     if (Subtarget->hasInt256()) {
11963       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11964       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11965       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11966                                 ShufMask);
11967       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11968                          DAG.getIntPtrConstant(0));
11969     }
11970
11971     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11972                                DAG.getIntPtrConstant(0));
11973     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11974                                DAG.getIntPtrConstant(2));
11975     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11976     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11977     static const int ShufMask[] = {0, 2, 4, 6};
11978     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11979   }
11980
11981   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11982     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11983     if (Subtarget->hasInt256()) {
11984       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11985
11986       SmallVector<SDValue,32> pshufbMask;
11987       for (unsigned i = 0; i < 2; ++i) {
11988         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11989         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11990         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11991         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11992         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11993         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11994         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11995         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11996         for (unsigned j = 0; j < 8; ++j)
11997           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11998       }
11999       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12000       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12001       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12002
12003       static const int ShufMask[] = {0,  2,  -1,  -1};
12004       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12005                                 &ShufMask[0]);
12006       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12007                        DAG.getIntPtrConstant(0));
12008       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12009     }
12010
12011     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12012                                DAG.getIntPtrConstant(0));
12013
12014     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12015                                DAG.getIntPtrConstant(4));
12016
12017     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12018     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12019
12020     // The PSHUFB mask:
12021     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12022                                    -1, -1, -1, -1, -1, -1, -1, -1};
12023
12024     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12025     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12026     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12027
12028     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12029     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12030
12031     // The MOVLHPS Mask:
12032     static const int ShufMask2[] = {0, 1, 4, 5};
12033     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12034     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12035   }
12036
12037   // Handle truncation of V256 to V128 using shuffles.
12038   if (!VT.is128BitVector() || !InVT.is256BitVector())
12039     return SDValue();
12040
12041   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12042
12043   unsigned NumElems = VT.getVectorNumElements();
12044   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12045
12046   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12047   // Prepare truncation shuffle mask
12048   for (unsigned i = 0; i != NumElems; ++i)
12049     MaskVec[i] = i * 2;
12050   SDValue V = DAG.getVectorShuffle(NVT, DL,
12051                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12052                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12053   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12054                      DAG.getIntPtrConstant(0));
12055 }
12056
12057 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12058                                            SelectionDAG &DAG) const {
12059   assert(!Op.getSimpleValueType().isVector());
12060
12061   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12062     /*IsSigned=*/ true, /*IsReplace=*/ false);
12063   SDValue FIST = Vals.first, StackSlot = Vals.second;
12064   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12065   if (!FIST.getNode()) return Op;
12066
12067   if (StackSlot.getNode())
12068     // Load the result.
12069     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12070                        FIST, StackSlot, MachinePointerInfo(),
12071                        false, false, false, 0);
12072
12073   // The node is the result.
12074   return FIST;
12075 }
12076
12077 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12078                                            SelectionDAG &DAG) const {
12079   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12080     /*IsSigned=*/ false, /*IsReplace=*/ false);
12081   SDValue FIST = Vals.first, StackSlot = Vals.second;
12082   assert(FIST.getNode() && "Unexpected failure");
12083
12084   if (StackSlot.getNode())
12085     // Load the result.
12086     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12087                        FIST, StackSlot, MachinePointerInfo(),
12088                        false, false, false, 0);
12089
12090   // The node is the result.
12091   return FIST;
12092 }
12093
12094 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12095   SDLoc DL(Op);
12096   MVT VT = Op.getSimpleValueType();
12097   SDValue In = Op.getOperand(0);
12098   MVT SVT = In.getSimpleValueType();
12099
12100   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12101
12102   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12103                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12104                                  In, DAG.getUNDEF(SVT)));
12105 }
12106
12107 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
12108   LLVMContext *Context = DAG.getContext();
12109   SDLoc dl(Op);
12110   MVT VT = Op.getSimpleValueType();
12111   MVT EltVT = VT;
12112   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12113   if (VT.isVector()) {
12114     EltVT = VT.getVectorElementType();
12115     NumElts = VT.getVectorNumElements();
12116   }
12117   Constant *C;
12118   if (EltVT == MVT::f64)
12119     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12120                                           APInt(64, ~(1ULL << 63))));
12121   else
12122     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12123                                           APInt(32, ~(1U << 31))));
12124   C = ConstantVector::getSplat(NumElts, C);
12125   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12126   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12127   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12128   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12129                              MachinePointerInfo::getConstantPool(),
12130                              false, false, false, Alignment);
12131   if (VT.isVector()) {
12132     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12133     return DAG.getNode(ISD::BITCAST, dl, VT,
12134                        DAG.getNode(ISD::AND, dl, ANDVT,
12135                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
12136                                                Op.getOperand(0)),
12137                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
12138   }
12139   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
12140 }
12141
12142 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
12143   LLVMContext *Context = DAG.getContext();
12144   SDLoc dl(Op);
12145   MVT VT = Op.getSimpleValueType();
12146   MVT EltVT = VT;
12147   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12148   if (VT.isVector()) {
12149     EltVT = VT.getVectorElementType();
12150     NumElts = VT.getVectorNumElements();
12151   }
12152   Constant *C;
12153   if (EltVT == MVT::f64)
12154     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12155                                           APInt(64, 1ULL << 63)));
12156   else
12157     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12158                                           APInt(32, 1U << 31)));
12159   C = ConstantVector::getSplat(NumElts, C);
12160   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12161   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12162   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12163   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12164                              MachinePointerInfo::getConstantPool(),
12165                              false, false, false, Alignment);
12166   if (VT.isVector()) {
12167     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
12168     return DAG.getNode(ISD::BITCAST, dl, VT,
12169                        DAG.getNode(ISD::XOR, dl, XORVT,
12170                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
12171                                                Op.getOperand(0)),
12172                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
12173   }
12174
12175   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
12176 }
12177
12178 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12179   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12180   LLVMContext *Context = DAG.getContext();
12181   SDValue Op0 = Op.getOperand(0);
12182   SDValue Op1 = Op.getOperand(1);
12183   SDLoc dl(Op);
12184   MVT VT = Op.getSimpleValueType();
12185   MVT SrcVT = Op1.getSimpleValueType();
12186
12187   // If second operand is smaller, extend it first.
12188   if (SrcVT.bitsLT(VT)) {
12189     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12190     SrcVT = VT;
12191   }
12192   // And if it is bigger, shrink it first.
12193   if (SrcVT.bitsGT(VT)) {
12194     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12195     SrcVT = VT;
12196   }
12197
12198   // At this point the operands and the result should have the same
12199   // type, and that won't be f80 since that is not custom lowered.
12200
12201   // First get the sign bit of second operand.
12202   SmallVector<Constant*,4> CV;
12203   if (SrcVT == MVT::f64) {
12204     const fltSemantics &Sem = APFloat::IEEEdouble;
12205     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
12206     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12207   } else {
12208     const fltSemantics &Sem = APFloat::IEEEsingle;
12209     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
12210     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12211     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12212     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12213   }
12214   Constant *C = ConstantVector::get(CV);
12215   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12216   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12217                               MachinePointerInfo::getConstantPool(),
12218                               false, false, false, 16);
12219   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12220
12221   // Shift sign bit right or left if the two operands have different types.
12222   if (SrcVT.bitsGT(VT)) {
12223     // Op0 is MVT::f32, Op1 is MVT::f64.
12224     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
12225     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
12226                           DAG.getConstant(32, MVT::i32));
12227     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
12228     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
12229                           DAG.getIntPtrConstant(0));
12230   }
12231
12232   // Clear first operand sign bit.
12233   CV.clear();
12234   if (VT == MVT::f64) {
12235     const fltSemantics &Sem = APFloat::IEEEdouble;
12236     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12237                                                    APInt(64, ~(1ULL << 63)))));
12238     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12239   } else {
12240     const fltSemantics &Sem = APFloat::IEEEsingle;
12241     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12242                                                    APInt(32, ~(1U << 31)))));
12243     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12244     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12245     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12246   }
12247   C = ConstantVector::get(CV);
12248   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12249   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12250                               MachinePointerInfo::getConstantPool(),
12251                               false, false, false, 16);
12252   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
12253
12254   // Or the value with the sign bit.
12255   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12256 }
12257
12258 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12259   SDValue N0 = Op.getOperand(0);
12260   SDLoc dl(Op);
12261   MVT VT = Op.getSimpleValueType();
12262
12263   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12264   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12265                                   DAG.getConstant(1, VT));
12266   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12267 }
12268
12269 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
12270 //
12271 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12272                                       SelectionDAG &DAG) {
12273   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12274
12275   if (!Subtarget->hasSSE41())
12276     return SDValue();
12277
12278   if (!Op->hasOneUse())
12279     return SDValue();
12280
12281   SDNode *N = Op.getNode();
12282   SDLoc DL(N);
12283
12284   SmallVector<SDValue, 8> Opnds;
12285   DenseMap<SDValue, unsigned> VecInMap;
12286   SmallVector<SDValue, 8> VecIns;
12287   EVT VT = MVT::Other;
12288
12289   // Recognize a special case where a vector is casted into wide integer to
12290   // test all 0s.
12291   Opnds.push_back(N->getOperand(0));
12292   Opnds.push_back(N->getOperand(1));
12293
12294   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12295     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12296     // BFS traverse all OR'd operands.
12297     if (I->getOpcode() == ISD::OR) {
12298       Opnds.push_back(I->getOperand(0));
12299       Opnds.push_back(I->getOperand(1));
12300       // Re-evaluate the number of nodes to be traversed.
12301       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12302       continue;
12303     }
12304
12305     // Quit if a non-EXTRACT_VECTOR_ELT
12306     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12307       return SDValue();
12308
12309     // Quit if without a constant index.
12310     SDValue Idx = I->getOperand(1);
12311     if (!isa<ConstantSDNode>(Idx))
12312       return SDValue();
12313
12314     SDValue ExtractedFromVec = I->getOperand(0);
12315     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12316     if (M == VecInMap.end()) {
12317       VT = ExtractedFromVec.getValueType();
12318       // Quit if not 128/256-bit vector.
12319       if (!VT.is128BitVector() && !VT.is256BitVector())
12320         return SDValue();
12321       // Quit if not the same type.
12322       if (VecInMap.begin() != VecInMap.end() &&
12323           VT != VecInMap.begin()->first.getValueType())
12324         return SDValue();
12325       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12326       VecIns.push_back(ExtractedFromVec);
12327     }
12328     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12329   }
12330
12331   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12332          "Not extracted from 128-/256-bit vector.");
12333
12334   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12335
12336   for (DenseMap<SDValue, unsigned>::const_iterator
12337         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12338     // Quit if not all elements are used.
12339     if (I->second != FullMask)
12340       return SDValue();
12341   }
12342
12343   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12344
12345   // Cast all vectors into TestVT for PTEST.
12346   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12347     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12348
12349   // If more than one full vectors are evaluated, OR them first before PTEST.
12350   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12351     // Each iteration will OR 2 nodes and append the result until there is only
12352     // 1 node left, i.e. the final OR'd value of all vectors.
12353     SDValue LHS = VecIns[Slot];
12354     SDValue RHS = VecIns[Slot + 1];
12355     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12356   }
12357
12358   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12359                      VecIns.back(), VecIns.back());
12360 }
12361
12362 /// \brief return true if \c Op has a use that doesn't just read flags.
12363 static bool hasNonFlagsUse(SDValue Op) {
12364   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12365        ++UI) {
12366     SDNode *User = *UI;
12367     unsigned UOpNo = UI.getOperandNo();
12368     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12369       // Look pass truncate.
12370       UOpNo = User->use_begin().getOperandNo();
12371       User = *User->use_begin();
12372     }
12373
12374     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12375         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12376       return true;
12377   }
12378   return false;
12379 }
12380
12381 /// Emit nodes that will be selected as "test Op0,Op0", or something
12382 /// equivalent.
12383 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12384                                     SelectionDAG &DAG) const {
12385   if (Op.getValueType() == MVT::i1)
12386     // KORTEST instruction should be selected
12387     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12388                        DAG.getConstant(0, Op.getValueType()));
12389
12390   // CF and OF aren't always set the way we want. Determine which
12391   // of these we need.
12392   bool NeedCF = false;
12393   bool NeedOF = false;
12394   switch (X86CC) {
12395   default: break;
12396   case X86::COND_A: case X86::COND_AE:
12397   case X86::COND_B: case X86::COND_BE:
12398     NeedCF = true;
12399     break;
12400   case X86::COND_G: case X86::COND_GE:
12401   case X86::COND_L: case X86::COND_LE:
12402   case X86::COND_O: case X86::COND_NO: {
12403     // Check if we really need to set the
12404     // Overflow flag. If NoSignedWrap is present
12405     // that is not actually needed.
12406     switch (Op->getOpcode()) {
12407     case ISD::ADD:
12408     case ISD::SUB:
12409     case ISD::MUL:
12410     case ISD::SHL: {
12411       const BinaryWithFlagsSDNode *BinNode =
12412           cast<BinaryWithFlagsSDNode>(Op.getNode());
12413       if (BinNode->hasNoSignedWrap())
12414         break;
12415     }
12416     default:
12417       NeedOF = true;
12418       break;
12419     }
12420     break;
12421   }
12422   }
12423   // See if we can use the EFLAGS value from the operand instead of
12424   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12425   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12426   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12427     // Emit a CMP with 0, which is the TEST pattern.
12428     //if (Op.getValueType() == MVT::i1)
12429     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12430     //                     DAG.getConstant(0, MVT::i1));
12431     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12432                        DAG.getConstant(0, Op.getValueType()));
12433   }
12434   unsigned Opcode = 0;
12435   unsigned NumOperands = 0;
12436
12437   // Truncate operations may prevent the merge of the SETCC instruction
12438   // and the arithmetic instruction before it. Attempt to truncate the operands
12439   // of the arithmetic instruction and use a reduced bit-width instruction.
12440   bool NeedTruncation = false;
12441   SDValue ArithOp = Op;
12442   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12443     SDValue Arith = Op->getOperand(0);
12444     // Both the trunc and the arithmetic op need to have one user each.
12445     if (Arith->hasOneUse())
12446       switch (Arith.getOpcode()) {
12447         default: break;
12448         case ISD::ADD:
12449         case ISD::SUB:
12450         case ISD::AND:
12451         case ISD::OR:
12452         case ISD::XOR: {
12453           NeedTruncation = true;
12454           ArithOp = Arith;
12455         }
12456       }
12457   }
12458
12459   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12460   // which may be the result of a CAST.  We use the variable 'Op', which is the
12461   // non-casted variable when we check for possible users.
12462   switch (ArithOp.getOpcode()) {
12463   case ISD::ADD:
12464     // Due to an isel shortcoming, be conservative if this add is likely to be
12465     // selected as part of a load-modify-store instruction. When the root node
12466     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12467     // uses of other nodes in the match, such as the ADD in this case. This
12468     // leads to the ADD being left around and reselected, with the result being
12469     // two adds in the output.  Alas, even if none our users are stores, that
12470     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12471     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12472     // climbing the DAG back to the root, and it doesn't seem to be worth the
12473     // effort.
12474     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12475          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12476       if (UI->getOpcode() != ISD::CopyToReg &&
12477           UI->getOpcode() != ISD::SETCC &&
12478           UI->getOpcode() != ISD::STORE)
12479         goto default_case;
12480
12481     if (ConstantSDNode *C =
12482         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12483       // An add of one will be selected as an INC.
12484       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12485         Opcode = X86ISD::INC;
12486         NumOperands = 1;
12487         break;
12488       }
12489
12490       // An add of negative one (subtract of one) will be selected as a DEC.
12491       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12492         Opcode = X86ISD::DEC;
12493         NumOperands = 1;
12494         break;
12495       }
12496     }
12497
12498     // Otherwise use a regular EFLAGS-setting add.
12499     Opcode = X86ISD::ADD;
12500     NumOperands = 2;
12501     break;
12502   case ISD::SHL:
12503   case ISD::SRL:
12504     // If we have a constant logical shift that's only used in a comparison
12505     // against zero turn it into an equivalent AND. This allows turning it into
12506     // a TEST instruction later.
12507     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12508         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12509       EVT VT = Op.getValueType();
12510       unsigned BitWidth = VT.getSizeInBits();
12511       unsigned ShAmt = Op->getConstantOperandVal(1);
12512       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12513         break;
12514       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12515                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12516                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12517       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12518         break;
12519       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12520                                 DAG.getConstant(Mask, VT));
12521       DAG.ReplaceAllUsesWith(Op, New);
12522       Op = New;
12523     }
12524     break;
12525
12526   case ISD::AND:
12527     // If the primary and result isn't used, don't bother using X86ISD::AND,
12528     // because a TEST instruction will be better.
12529     if (!hasNonFlagsUse(Op))
12530       break;
12531     // FALL THROUGH
12532   case ISD::SUB:
12533   case ISD::OR:
12534   case ISD::XOR:
12535     // Due to the ISEL shortcoming noted above, be conservative if this op is
12536     // likely to be selected as part of a load-modify-store instruction.
12537     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12538            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12539       if (UI->getOpcode() == ISD::STORE)
12540         goto default_case;
12541
12542     // Otherwise use a regular EFLAGS-setting instruction.
12543     switch (ArithOp.getOpcode()) {
12544     default: llvm_unreachable("unexpected operator!");
12545     case ISD::SUB: Opcode = X86ISD::SUB; break;
12546     case ISD::XOR: Opcode = X86ISD::XOR; break;
12547     case ISD::AND: Opcode = X86ISD::AND; break;
12548     case ISD::OR: {
12549       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12550         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12551         if (EFLAGS.getNode())
12552           return EFLAGS;
12553       }
12554       Opcode = X86ISD::OR;
12555       break;
12556     }
12557     }
12558
12559     NumOperands = 2;
12560     break;
12561   case X86ISD::ADD:
12562   case X86ISD::SUB:
12563   case X86ISD::INC:
12564   case X86ISD::DEC:
12565   case X86ISD::OR:
12566   case X86ISD::XOR:
12567   case X86ISD::AND:
12568     return SDValue(Op.getNode(), 1);
12569   default:
12570   default_case:
12571     break;
12572   }
12573
12574   // If we found that truncation is beneficial, perform the truncation and
12575   // update 'Op'.
12576   if (NeedTruncation) {
12577     EVT VT = Op.getValueType();
12578     SDValue WideVal = Op->getOperand(0);
12579     EVT WideVT = WideVal.getValueType();
12580     unsigned ConvertedOp = 0;
12581     // Use a target machine opcode to prevent further DAGCombine
12582     // optimizations that may separate the arithmetic operations
12583     // from the setcc node.
12584     switch (WideVal.getOpcode()) {
12585       default: break;
12586       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12587       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12588       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12589       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12590       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12591     }
12592
12593     if (ConvertedOp) {
12594       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12595       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12596         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12597         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12598         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12599       }
12600     }
12601   }
12602
12603   if (Opcode == 0)
12604     // Emit a CMP with 0, which is the TEST pattern.
12605     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12606                        DAG.getConstant(0, Op.getValueType()));
12607
12608   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12609   SmallVector<SDValue, 4> Ops;
12610   for (unsigned i = 0; i != NumOperands; ++i)
12611     Ops.push_back(Op.getOperand(i));
12612
12613   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12614   DAG.ReplaceAllUsesWith(Op, New);
12615   return SDValue(New.getNode(), 1);
12616 }
12617
12618 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12619 /// equivalent.
12620 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12621                                    SDLoc dl, SelectionDAG &DAG) const {
12622   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12623     if (C->getAPIntValue() == 0)
12624       return EmitTest(Op0, X86CC, dl, DAG);
12625
12626      if (Op0.getValueType() == MVT::i1)
12627        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12628   }
12629  
12630   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12631        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12632     // Do the comparison at i32 if it's smaller, besides the Atom case. 
12633     // This avoids subregister aliasing issues. Keep the smaller reference 
12634     // if we're optimizing for size, however, as that'll allow better folding 
12635     // of memory operations.
12636     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12637         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12638              AttributeSet::FunctionIndex, Attribute::MinSize) &&
12639         !Subtarget->isAtom()) {
12640       unsigned ExtendOp =
12641           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12642       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12643       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12644     }
12645     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12646     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12647     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12648                               Op0, Op1);
12649     return SDValue(Sub.getNode(), 1);
12650   }
12651   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12652 }
12653
12654 /// Convert a comparison if required by the subtarget.
12655 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12656                                                  SelectionDAG &DAG) const {
12657   // If the subtarget does not support the FUCOMI instruction, floating-point
12658   // comparisons have to be converted.
12659   if (Subtarget->hasCMov() ||
12660       Cmp.getOpcode() != X86ISD::CMP ||
12661       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12662       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12663     return Cmp;
12664
12665   // The instruction selector will select an FUCOM instruction instead of
12666   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12667   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12668   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12669   SDLoc dl(Cmp);
12670   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12671   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12672   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12673                             DAG.getConstant(8, MVT::i8));
12674   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12675   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12676 }
12677
12678 static bool isAllOnes(SDValue V) {
12679   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12680   return C && C->isAllOnesValue();
12681 }
12682
12683 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12684 /// if it's possible.
12685 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12686                                      SDLoc dl, SelectionDAG &DAG) const {
12687   SDValue Op0 = And.getOperand(0);
12688   SDValue Op1 = And.getOperand(1);
12689   if (Op0.getOpcode() == ISD::TRUNCATE)
12690     Op0 = Op0.getOperand(0);
12691   if (Op1.getOpcode() == ISD::TRUNCATE)
12692     Op1 = Op1.getOperand(0);
12693
12694   SDValue LHS, RHS;
12695   if (Op1.getOpcode() == ISD::SHL)
12696     std::swap(Op0, Op1);
12697   if (Op0.getOpcode() == ISD::SHL) {
12698     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12699       if (And00C->getZExtValue() == 1) {
12700         // If we looked past a truncate, check that it's only truncating away
12701         // known zeros.
12702         unsigned BitWidth = Op0.getValueSizeInBits();
12703         unsigned AndBitWidth = And.getValueSizeInBits();
12704         if (BitWidth > AndBitWidth) {
12705           APInt Zeros, Ones;
12706           DAG.computeKnownBits(Op0, Zeros, Ones);
12707           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12708             return SDValue();
12709         }
12710         LHS = Op1;
12711         RHS = Op0.getOperand(1);
12712       }
12713   } else if (Op1.getOpcode() == ISD::Constant) {
12714     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12715     uint64_t AndRHSVal = AndRHS->getZExtValue();
12716     SDValue AndLHS = Op0;
12717
12718     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12719       LHS = AndLHS.getOperand(0);
12720       RHS = AndLHS.getOperand(1);
12721     }
12722
12723     // Use BT if the immediate can't be encoded in a TEST instruction.
12724     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12725       LHS = AndLHS;
12726       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12727     }
12728   }
12729
12730   if (LHS.getNode()) {
12731     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12732     // instruction.  Since the shift amount is in-range-or-undefined, we know
12733     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12734     // the encoding for the i16 version is larger than the i32 version.
12735     // Also promote i16 to i32 for performance / code size reason.
12736     if (LHS.getValueType() == MVT::i8 ||
12737         LHS.getValueType() == MVT::i16)
12738       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12739
12740     // If the operand types disagree, extend the shift amount to match.  Since
12741     // BT ignores high bits (like shifts) we can use anyextend.
12742     if (LHS.getValueType() != RHS.getValueType())
12743       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12744
12745     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12746     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12747     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12748                        DAG.getConstant(Cond, MVT::i8), BT);
12749   }
12750
12751   return SDValue();
12752 }
12753
12754 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12755 /// mask CMPs.
12756 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12757                               SDValue &Op1) {
12758   unsigned SSECC;
12759   bool Swap = false;
12760
12761   // SSE Condition code mapping:
12762   //  0 - EQ
12763   //  1 - LT
12764   //  2 - LE
12765   //  3 - UNORD
12766   //  4 - NEQ
12767   //  5 - NLT
12768   //  6 - NLE
12769   //  7 - ORD
12770   switch (SetCCOpcode) {
12771   default: llvm_unreachable("Unexpected SETCC condition");
12772   case ISD::SETOEQ:
12773   case ISD::SETEQ:  SSECC = 0; break;
12774   case ISD::SETOGT:
12775   case ISD::SETGT:  Swap = true; // Fallthrough
12776   case ISD::SETLT:
12777   case ISD::SETOLT: SSECC = 1; break;
12778   case ISD::SETOGE:
12779   case ISD::SETGE:  Swap = true; // Fallthrough
12780   case ISD::SETLE:
12781   case ISD::SETOLE: SSECC = 2; break;
12782   case ISD::SETUO:  SSECC = 3; break;
12783   case ISD::SETUNE:
12784   case ISD::SETNE:  SSECC = 4; break;
12785   case ISD::SETULE: Swap = true; // Fallthrough
12786   case ISD::SETUGE: SSECC = 5; break;
12787   case ISD::SETULT: Swap = true; // Fallthrough
12788   case ISD::SETUGT: SSECC = 6; break;
12789   case ISD::SETO:   SSECC = 7; break;
12790   case ISD::SETUEQ:
12791   case ISD::SETONE: SSECC = 8; break;
12792   }
12793   if (Swap)
12794     std::swap(Op0, Op1);
12795
12796   return SSECC;
12797 }
12798
12799 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12800 // ones, and then concatenate the result back.
12801 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12802   MVT VT = Op.getSimpleValueType();
12803
12804   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12805          "Unsupported value type for operation");
12806
12807   unsigned NumElems = VT.getVectorNumElements();
12808   SDLoc dl(Op);
12809   SDValue CC = Op.getOperand(2);
12810
12811   // Extract the LHS vectors
12812   SDValue LHS = Op.getOperand(0);
12813   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12814   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12815
12816   // Extract the RHS vectors
12817   SDValue RHS = Op.getOperand(1);
12818   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12819   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12820
12821   // Issue the operation on the smaller types and concatenate the result back
12822   MVT EltVT = VT.getVectorElementType();
12823   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12824   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12825                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12826                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12827 }
12828
12829 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12830                                      const X86Subtarget *Subtarget) {
12831   SDValue Op0 = Op.getOperand(0);
12832   SDValue Op1 = Op.getOperand(1);
12833   SDValue CC = Op.getOperand(2);
12834   MVT VT = Op.getSimpleValueType();
12835   SDLoc dl(Op);
12836
12837   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12838          Op.getValueType().getScalarType() == MVT::i1 &&
12839          "Cannot set masked compare for this operation");
12840
12841   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12842   unsigned  Opc = 0;
12843   bool Unsigned = false;
12844   bool Swap = false;
12845   unsigned SSECC;
12846   switch (SetCCOpcode) {
12847   default: llvm_unreachable("Unexpected SETCC condition");
12848   case ISD::SETNE:  SSECC = 4; break;
12849   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12850   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12851   case ISD::SETLT:  Swap = true; //fall-through
12852   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12853   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12854   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12855   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12856   case ISD::SETULE: Unsigned = true; //fall-through
12857   case ISD::SETLE:  SSECC = 2; break;
12858   }
12859
12860   if (Swap)
12861     std::swap(Op0, Op1);
12862   if (Opc)
12863     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12864   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12865   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12866                      DAG.getConstant(SSECC, MVT::i8));
12867 }
12868
12869 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12870 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12871 /// return an empty value.
12872 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12873 {
12874   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12875   if (!BV)
12876     return SDValue();
12877
12878   MVT VT = Op1.getSimpleValueType();
12879   MVT EVT = VT.getVectorElementType();
12880   unsigned n = VT.getVectorNumElements();
12881   SmallVector<SDValue, 8> ULTOp1;
12882
12883   for (unsigned i = 0; i < n; ++i) {
12884     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12885     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12886       return SDValue();
12887
12888     // Avoid underflow.
12889     APInt Val = Elt->getAPIntValue();
12890     if (Val == 0)
12891       return SDValue();
12892
12893     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12894   }
12895
12896   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12897 }
12898
12899 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12900                            SelectionDAG &DAG) {
12901   SDValue Op0 = Op.getOperand(0);
12902   SDValue Op1 = Op.getOperand(1);
12903   SDValue CC = Op.getOperand(2);
12904   MVT VT = Op.getSimpleValueType();
12905   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12906   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12907   SDLoc dl(Op);
12908
12909   if (isFP) {
12910 #ifndef NDEBUG
12911     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12912     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12913 #endif
12914
12915     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12916     unsigned Opc = X86ISD::CMPP;
12917     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12918       assert(VT.getVectorNumElements() <= 16);
12919       Opc = X86ISD::CMPM;
12920     }
12921     // In the two special cases we can't handle, emit two comparisons.
12922     if (SSECC == 8) {
12923       unsigned CC0, CC1;
12924       unsigned CombineOpc;
12925       if (SetCCOpcode == ISD::SETUEQ) {
12926         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12927       } else {
12928         assert(SetCCOpcode == ISD::SETONE);
12929         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12930       }
12931
12932       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12933                                  DAG.getConstant(CC0, MVT::i8));
12934       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12935                                  DAG.getConstant(CC1, MVT::i8));
12936       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12937     }
12938     // Handle all other FP comparisons here.
12939     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12940                        DAG.getConstant(SSECC, MVT::i8));
12941   }
12942
12943   // Break 256-bit integer vector compare into smaller ones.
12944   if (VT.is256BitVector() && !Subtarget->hasInt256())
12945     return Lower256IntVSETCC(Op, DAG);
12946
12947   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12948   EVT OpVT = Op1.getValueType();
12949   if (Subtarget->hasAVX512()) {
12950     if (Op1.getValueType().is512BitVector() ||
12951         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12952       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12953
12954     // In AVX-512 architecture setcc returns mask with i1 elements,
12955     // But there is no compare instruction for i8 and i16 elements.
12956     // We are not talking about 512-bit operands in this case, these
12957     // types are illegal.
12958     if (MaskResult &&
12959         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12960          OpVT.getVectorElementType().getSizeInBits() >= 8))
12961       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12962                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12963   }
12964
12965   // We are handling one of the integer comparisons here.  Since SSE only has
12966   // GT and EQ comparisons for integer, swapping operands and multiple
12967   // operations may be required for some comparisons.
12968   unsigned Opc;
12969   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12970   bool Subus = false;
12971
12972   switch (SetCCOpcode) {
12973   default: llvm_unreachable("Unexpected SETCC condition");
12974   case ISD::SETNE:  Invert = true;
12975   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12976   case ISD::SETLT:  Swap = true;
12977   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12978   case ISD::SETGE:  Swap = true;
12979   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12980                     Invert = true; break;
12981   case ISD::SETULT: Swap = true;
12982   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12983                     FlipSigns = true; break;
12984   case ISD::SETUGE: Swap = true;
12985   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12986                     FlipSigns = true; Invert = true; break;
12987   }
12988
12989   // Special case: Use min/max operations for SETULE/SETUGE
12990   MVT VET = VT.getVectorElementType();
12991   bool hasMinMax =
12992        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12993     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12994
12995   if (hasMinMax) {
12996     switch (SetCCOpcode) {
12997     default: break;
12998     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12999     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13000     }
13001
13002     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13003   }
13004
13005   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13006   if (!MinMax && hasSubus) {
13007     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13008     // Op0 u<= Op1:
13009     //   t = psubus Op0, Op1
13010     //   pcmpeq t, <0..0>
13011     switch (SetCCOpcode) {
13012     default: break;
13013     case ISD::SETULT: {
13014       // If the comparison is against a constant we can turn this into a
13015       // setule.  With psubus, setule does not require a swap.  This is
13016       // beneficial because the constant in the register is no longer
13017       // destructed as the destination so it can be hoisted out of a loop.
13018       // Only do this pre-AVX since vpcmp* is no longer destructive.
13019       if (Subtarget->hasAVX())
13020         break;
13021       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13022       if (ULEOp1.getNode()) {
13023         Op1 = ULEOp1;
13024         Subus = true; Invert = false; Swap = false;
13025       }
13026       break;
13027     }
13028     // Psubus is better than flip-sign because it requires no inversion.
13029     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13030     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13031     }
13032
13033     if (Subus) {
13034       Opc = X86ISD::SUBUS;
13035       FlipSigns = false;
13036     }
13037   }
13038
13039   if (Swap)
13040     std::swap(Op0, Op1);
13041
13042   // Check that the operation in question is available (most are plain SSE2,
13043   // but PCMPGTQ and PCMPEQQ have different requirements).
13044   if (VT == MVT::v2i64) {
13045     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13046       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13047
13048       // First cast everything to the right type.
13049       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13050       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13051
13052       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13053       // bits of the inputs before performing those operations. The lower
13054       // compare is always unsigned.
13055       SDValue SB;
13056       if (FlipSigns) {
13057         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13058       } else {
13059         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13060         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13061         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13062                          Sign, Zero, Sign, Zero);
13063       }
13064       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13065       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13066
13067       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13068       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13069       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13070
13071       // Create masks for only the low parts/high parts of the 64 bit integers.
13072       static const int MaskHi[] = { 1, 1, 3, 3 };
13073       static const int MaskLo[] = { 0, 0, 2, 2 };
13074       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13075       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13076       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13077
13078       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13079       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13080
13081       if (Invert)
13082         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13083
13084       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13085     }
13086
13087     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13088       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13089       // pcmpeqd + pshufd + pand.
13090       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13091
13092       // First cast everything to the right type.
13093       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13094       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13095
13096       // Do the compare.
13097       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13098
13099       // Make sure the lower and upper halves are both all-ones.
13100       static const int Mask[] = { 1, 0, 3, 2 };
13101       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13102       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13103
13104       if (Invert)
13105         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13106
13107       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13108     }
13109   }
13110
13111   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13112   // bits of the inputs before performing those operations.
13113   if (FlipSigns) {
13114     EVT EltVT = VT.getVectorElementType();
13115     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13116     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13117     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13118   }
13119
13120   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13121
13122   // If the logical-not of the result is required, perform that now.
13123   if (Invert)
13124     Result = DAG.getNOT(dl, Result, VT);
13125
13126   if (MinMax)
13127     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13128
13129   if (Subus)
13130     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13131                          getZeroVector(VT, Subtarget, DAG, dl));
13132
13133   return Result;
13134 }
13135
13136 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13137
13138   MVT VT = Op.getSimpleValueType();
13139
13140   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13141
13142   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13143          && "SetCC type must be 8-bit or 1-bit integer");
13144   SDValue Op0 = Op.getOperand(0);
13145   SDValue Op1 = Op.getOperand(1);
13146   SDLoc dl(Op);
13147   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13148
13149   // Optimize to BT if possible.
13150   // Lower (X & (1 << N)) == 0 to BT(X, N).
13151   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13152   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13153   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13154       Op1.getOpcode() == ISD::Constant &&
13155       cast<ConstantSDNode>(Op1)->isNullValue() &&
13156       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13157     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13158     if (NewSetCC.getNode())
13159       return NewSetCC;
13160   }
13161
13162   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13163   // these.
13164   if (Op1.getOpcode() == ISD::Constant &&
13165       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13166        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13167       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13168
13169     // If the input is a setcc, then reuse the input setcc or use a new one with
13170     // the inverted condition.
13171     if (Op0.getOpcode() == X86ISD::SETCC) {
13172       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13173       bool Invert = (CC == ISD::SETNE) ^
13174         cast<ConstantSDNode>(Op1)->isNullValue();
13175       if (!Invert)
13176         return Op0;
13177
13178       CCode = X86::GetOppositeBranchCondition(CCode);
13179       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13180                                   DAG.getConstant(CCode, MVT::i8),
13181                                   Op0.getOperand(1));
13182       if (VT == MVT::i1)
13183         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13184       return SetCC;
13185     }
13186   }
13187   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13188       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13189       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13190
13191     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13192     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13193   }
13194
13195   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13196   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13197   if (X86CC == X86::COND_INVALID)
13198     return SDValue();
13199
13200   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13201   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13202   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13203                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13204   if (VT == MVT::i1)
13205     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13206   return SetCC;
13207 }
13208
13209 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13210 static bool isX86LogicalCmp(SDValue Op) {
13211   unsigned Opc = Op.getNode()->getOpcode();
13212   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13213       Opc == X86ISD::SAHF)
13214     return true;
13215   if (Op.getResNo() == 1 &&
13216       (Opc == X86ISD::ADD ||
13217        Opc == X86ISD::SUB ||
13218        Opc == X86ISD::ADC ||
13219        Opc == X86ISD::SBB ||
13220        Opc == X86ISD::SMUL ||
13221        Opc == X86ISD::UMUL ||
13222        Opc == X86ISD::INC ||
13223        Opc == X86ISD::DEC ||
13224        Opc == X86ISD::OR ||
13225        Opc == X86ISD::XOR ||
13226        Opc == X86ISD::AND))
13227     return true;
13228
13229   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13230     return true;
13231
13232   return false;
13233 }
13234
13235 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13236   if (V.getOpcode() != ISD::TRUNCATE)
13237     return false;
13238
13239   SDValue VOp0 = V.getOperand(0);
13240   unsigned InBits = VOp0.getValueSizeInBits();
13241   unsigned Bits = V.getValueSizeInBits();
13242   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13243 }
13244
13245 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13246   bool addTest = true;
13247   SDValue Cond  = Op.getOperand(0);
13248   SDValue Op1 = Op.getOperand(1);
13249   SDValue Op2 = Op.getOperand(2);
13250   SDLoc DL(Op);
13251   EVT VT = Op1.getValueType();
13252   SDValue CC;
13253
13254   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13255   // are available. Otherwise fp cmovs get lowered into a less efficient branch
13256   // sequence later on.
13257   if (Cond.getOpcode() == ISD::SETCC &&
13258       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13259        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13260       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13261     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13262     int SSECC = translateX86FSETCC(
13263         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13264
13265     if (SSECC != 8) {
13266       if (Subtarget->hasAVX512()) {
13267         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13268                                   DAG.getConstant(SSECC, MVT::i8));
13269         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13270       }
13271       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13272                                 DAG.getConstant(SSECC, MVT::i8));
13273       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13274       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13275       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13276     }
13277   }
13278
13279   if (Cond.getOpcode() == ISD::SETCC) {
13280     SDValue NewCond = LowerSETCC(Cond, DAG);
13281     if (NewCond.getNode())
13282       Cond = NewCond;
13283   }
13284
13285   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13286   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13287   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13288   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13289   if (Cond.getOpcode() == X86ISD::SETCC &&
13290       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13291       isZero(Cond.getOperand(1).getOperand(1))) {
13292     SDValue Cmp = Cond.getOperand(1);
13293
13294     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13295
13296     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13297         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13298       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13299
13300       SDValue CmpOp0 = Cmp.getOperand(0);
13301       // Apply further optimizations for special cases
13302       // (select (x != 0), -1, 0) -> neg & sbb
13303       // (select (x == 0), 0, -1) -> neg & sbb
13304       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13305         if (YC->isNullValue() &&
13306             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13307           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13308           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13309                                     DAG.getConstant(0, CmpOp0.getValueType()),
13310                                     CmpOp0);
13311           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13312                                     DAG.getConstant(X86::COND_B, MVT::i8),
13313                                     SDValue(Neg.getNode(), 1));
13314           return Res;
13315         }
13316
13317       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13318                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13319       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13320
13321       SDValue Res =   // Res = 0 or -1.
13322         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13323                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13324
13325       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13326         Res = DAG.getNOT(DL, Res, Res.getValueType());
13327
13328       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13329       if (!N2C || !N2C->isNullValue())
13330         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13331       return Res;
13332     }
13333   }
13334
13335   // Look past (and (setcc_carry (cmp ...)), 1).
13336   if (Cond.getOpcode() == ISD::AND &&
13337       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13338     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13339     if (C && C->getAPIntValue() == 1)
13340       Cond = Cond.getOperand(0);
13341   }
13342
13343   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13344   // setting operand in place of the X86ISD::SETCC.
13345   unsigned CondOpcode = Cond.getOpcode();
13346   if (CondOpcode == X86ISD::SETCC ||
13347       CondOpcode == X86ISD::SETCC_CARRY) {
13348     CC = Cond.getOperand(0);
13349
13350     SDValue Cmp = Cond.getOperand(1);
13351     unsigned Opc = Cmp.getOpcode();
13352     MVT VT = Op.getSimpleValueType();
13353
13354     bool IllegalFPCMov = false;
13355     if (VT.isFloatingPoint() && !VT.isVector() &&
13356         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13357       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13358
13359     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13360         Opc == X86ISD::BT) { // FIXME
13361       Cond = Cmp;
13362       addTest = false;
13363     }
13364   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13365              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13366              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13367               Cond.getOperand(0).getValueType() != MVT::i8)) {
13368     SDValue LHS = Cond.getOperand(0);
13369     SDValue RHS = Cond.getOperand(1);
13370     unsigned X86Opcode;
13371     unsigned X86Cond;
13372     SDVTList VTs;
13373     switch (CondOpcode) {
13374     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13375     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13376     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13377     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13378     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13379     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13380     default: llvm_unreachable("unexpected overflowing operator");
13381     }
13382     if (CondOpcode == ISD::UMULO)
13383       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13384                           MVT::i32);
13385     else
13386       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13387
13388     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13389
13390     if (CondOpcode == ISD::UMULO)
13391       Cond = X86Op.getValue(2);
13392     else
13393       Cond = X86Op.getValue(1);
13394
13395     CC = DAG.getConstant(X86Cond, MVT::i8);
13396     addTest = false;
13397   }
13398
13399   if (addTest) {
13400     // Look pass the truncate if the high bits are known zero.
13401     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13402         Cond = Cond.getOperand(0);
13403
13404     // We know the result of AND is compared against zero. Try to match
13405     // it to BT.
13406     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13407       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13408       if (NewSetCC.getNode()) {
13409         CC = NewSetCC.getOperand(0);
13410         Cond = NewSetCC.getOperand(1);
13411         addTest = false;
13412       }
13413     }
13414   }
13415
13416   if (addTest) {
13417     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13418     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13419   }
13420
13421   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13422   // a <  b ?  0 : -1 -> RES = setcc_carry
13423   // a >= b ? -1 :  0 -> RES = setcc_carry
13424   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13425   if (Cond.getOpcode() == X86ISD::SUB) {
13426     Cond = ConvertCmpIfNecessary(Cond, DAG);
13427     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13428
13429     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13430         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13431       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13432                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13433       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13434         return DAG.getNOT(DL, Res, Res.getValueType());
13435       return Res;
13436     }
13437   }
13438
13439   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13440   // widen the cmov and push the truncate through. This avoids introducing a new
13441   // branch during isel and doesn't add any extensions.
13442   if (Op.getValueType() == MVT::i8 &&
13443       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13444     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13445     if (T1.getValueType() == T2.getValueType() &&
13446         // Blacklist CopyFromReg to avoid partial register stalls.
13447         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13448       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13449       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13450       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13451     }
13452   }
13453
13454   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13455   // condition is true.
13456   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13457   SDValue Ops[] = { Op2, Op1, CC, Cond };
13458   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13459 }
13460
13461 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13462   MVT VT = Op->getSimpleValueType(0);
13463   SDValue In = Op->getOperand(0);
13464   MVT InVT = In.getSimpleValueType();
13465   SDLoc dl(Op);
13466
13467   unsigned int NumElts = VT.getVectorNumElements();
13468   if (NumElts != 8 && NumElts != 16)
13469     return SDValue();
13470
13471   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13472     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13473
13474   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13475   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13476
13477   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13478   Constant *C = ConstantInt::get(*DAG.getContext(),
13479     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13480
13481   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13482   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13483   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13484                           MachinePointerInfo::getConstantPool(),
13485                           false, false, false, Alignment);
13486   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13487   if (VT.is512BitVector())
13488     return Brcst;
13489   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13490 }
13491
13492 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13493                                 SelectionDAG &DAG) {
13494   MVT VT = Op->getSimpleValueType(0);
13495   SDValue In = Op->getOperand(0);
13496   MVT InVT = In.getSimpleValueType();
13497   SDLoc dl(Op);
13498
13499   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13500     return LowerSIGN_EXTEND_AVX512(Op, DAG);
13501
13502   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13503       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13504       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13505     return SDValue();
13506
13507   if (Subtarget->hasInt256())
13508     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13509
13510   // Optimize vectors in AVX mode
13511   // Sign extend  v8i16 to v8i32 and
13512   //              v4i32 to v4i64
13513   //
13514   // Divide input vector into two parts
13515   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13516   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13517   // concat the vectors to original VT
13518
13519   unsigned NumElems = InVT.getVectorNumElements();
13520   SDValue Undef = DAG.getUNDEF(InVT);
13521
13522   SmallVector<int,8> ShufMask1(NumElems, -1);
13523   for (unsigned i = 0; i != NumElems/2; ++i)
13524     ShufMask1[i] = i;
13525
13526   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13527
13528   SmallVector<int,8> ShufMask2(NumElems, -1);
13529   for (unsigned i = 0; i != NumElems/2; ++i)
13530     ShufMask2[i] = i + NumElems/2;
13531
13532   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13533
13534   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13535                                 VT.getVectorNumElements()/2);
13536
13537   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13538   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13539
13540   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13541 }
13542
13543 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13544 // may emit an illegal shuffle but the expansion is still better than scalar
13545 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13546 // we'll emit a shuffle and a arithmetic shift.
13547 // TODO: It is possible to support ZExt by zeroing the undef values during
13548 // the shuffle phase or after the shuffle.
13549 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13550                                  SelectionDAG &DAG) {
13551   MVT RegVT = Op.getSimpleValueType();
13552   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13553   assert(RegVT.isInteger() &&
13554          "We only custom lower integer vector sext loads.");
13555
13556   // Nothing useful we can do without SSE2 shuffles.
13557   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13558
13559   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13560   SDLoc dl(Ld);
13561   EVT MemVT = Ld->getMemoryVT();
13562   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13563   unsigned RegSz = RegVT.getSizeInBits();
13564
13565   ISD::LoadExtType Ext = Ld->getExtensionType();
13566
13567   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13568          && "Only anyext and sext are currently implemented.");
13569   assert(MemVT != RegVT && "Cannot extend to the same type");
13570   assert(MemVT.isVector() && "Must load a vector from memory");
13571
13572   unsigned NumElems = RegVT.getVectorNumElements();
13573   unsigned MemSz = MemVT.getSizeInBits();
13574   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13575
13576   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13577     // The only way in which we have a legal 256-bit vector result but not the
13578     // integer 256-bit operations needed to directly lower a sextload is if we
13579     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13580     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13581     // correctly legalized. We do this late to allow the canonical form of
13582     // sextload to persist throughout the rest of the DAG combiner -- it wants
13583     // to fold together any extensions it can, and so will fuse a sign_extend
13584     // of an sextload into a sextload targeting a wider value.
13585     SDValue Load;
13586     if (MemSz == 128) {
13587       // Just switch this to a normal load.
13588       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13589                                        "it must be a legal 128-bit vector "
13590                                        "type!");
13591       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13592                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13593                   Ld->isInvariant(), Ld->getAlignment());
13594     } else {
13595       assert(MemSz < 128 &&
13596              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13597       // Do an sext load to a 128-bit vector type. We want to use the same
13598       // number of elements, but elements half as wide. This will end up being
13599       // recursively lowered by this routine, but will succeed as we definitely
13600       // have all the necessary features if we're using AVX1.
13601       EVT HalfEltVT =
13602           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13603       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13604       Load =
13605           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13606                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13607                          Ld->isNonTemporal(), Ld->isInvariant(),
13608                          Ld->getAlignment());
13609     }
13610
13611     // Replace chain users with the new chain.
13612     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13613     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13614
13615     // Finally, do a normal sign-extend to the desired register.
13616     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13617   }
13618
13619   // All sizes must be a power of two.
13620   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13621          "Non-power-of-two elements are not custom lowered!");
13622
13623   // Attempt to load the original value using scalar loads.
13624   // Find the largest scalar type that divides the total loaded size.
13625   MVT SclrLoadTy = MVT::i8;
13626   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13627        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13628     MVT Tp = (MVT::SimpleValueType)tp;
13629     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13630       SclrLoadTy = Tp;
13631     }
13632   }
13633
13634   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13635   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13636       (64 <= MemSz))
13637     SclrLoadTy = MVT::f64;
13638
13639   // Calculate the number of scalar loads that we need to perform
13640   // in order to load our vector from memory.
13641   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13642
13643   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13644          "Can only lower sext loads with a single scalar load!");
13645
13646   unsigned loadRegZize = RegSz;
13647   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13648     loadRegZize /= 2;
13649
13650   // Represent our vector as a sequence of elements which are the
13651   // largest scalar that we can load.
13652   EVT LoadUnitVecVT = EVT::getVectorVT(
13653       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13654
13655   // Represent the data using the same element type that is stored in
13656   // memory. In practice, we ''widen'' MemVT.
13657   EVT WideVecVT =
13658       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13659                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13660
13661   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13662          "Invalid vector type");
13663
13664   // We can't shuffle using an illegal type.
13665   assert(TLI.isTypeLegal(WideVecVT) &&
13666          "We only lower types that form legal widened vector types");
13667
13668   SmallVector<SDValue, 8> Chains;
13669   SDValue Ptr = Ld->getBasePtr();
13670   SDValue Increment =
13671       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13672   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13673
13674   for (unsigned i = 0; i < NumLoads; ++i) {
13675     // Perform a single load.
13676     SDValue ScalarLoad =
13677         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13678                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13679                     Ld->getAlignment());
13680     Chains.push_back(ScalarLoad.getValue(1));
13681     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13682     // another round of DAGCombining.
13683     if (i == 0)
13684       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13685     else
13686       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13687                         ScalarLoad, DAG.getIntPtrConstant(i));
13688
13689     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13690   }
13691
13692   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13693
13694   // Bitcast the loaded value to a vector of the original element type, in
13695   // the size of the target vector type.
13696   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13697   unsigned SizeRatio = RegSz / MemSz;
13698
13699   if (Ext == ISD::SEXTLOAD) {
13700     // If we have SSE4.1, we can directly emit a VSEXT node.
13701     if (Subtarget->hasSSE41()) {
13702       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13703       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13704       return Sext;
13705     }
13706
13707     // Otherwise we'll shuffle the small elements in the high bits of the
13708     // larger type and perform an arithmetic shift. If the shift is not legal
13709     // it's better to scalarize.
13710     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13711            "We can't implement a sext load without an arithmetic right shift!");
13712
13713     // Redistribute the loaded elements into the different locations.
13714     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13715     for (unsigned i = 0; i != NumElems; ++i)
13716       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13717
13718     SDValue Shuff = DAG.getVectorShuffle(
13719         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13720
13721     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13722
13723     // Build the arithmetic shift.
13724     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13725                    MemVT.getVectorElementType().getSizeInBits();
13726     Shuff =
13727         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13728
13729     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13730     return Shuff;
13731   }
13732
13733   // Redistribute the loaded elements into the different locations.
13734   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13735   for (unsigned i = 0; i != NumElems; ++i)
13736     ShuffleVec[i * SizeRatio] = i;
13737
13738   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13739                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13740
13741   // Bitcast to the requested type.
13742   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13743   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13744   return Shuff;
13745 }
13746
13747 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13748 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13749 // from the AND / OR.
13750 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13751   Opc = Op.getOpcode();
13752   if (Opc != ISD::OR && Opc != ISD::AND)
13753     return false;
13754   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13755           Op.getOperand(0).hasOneUse() &&
13756           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13757           Op.getOperand(1).hasOneUse());
13758 }
13759
13760 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13761 // 1 and that the SETCC node has a single use.
13762 static bool isXor1OfSetCC(SDValue Op) {
13763   if (Op.getOpcode() != ISD::XOR)
13764     return false;
13765   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13766   if (N1C && N1C->getAPIntValue() == 1) {
13767     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13768       Op.getOperand(0).hasOneUse();
13769   }
13770   return false;
13771 }
13772
13773 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13774   bool addTest = true;
13775   SDValue Chain = Op.getOperand(0);
13776   SDValue Cond  = Op.getOperand(1);
13777   SDValue Dest  = Op.getOperand(2);
13778   SDLoc dl(Op);
13779   SDValue CC;
13780   bool Inverted = false;
13781
13782   if (Cond.getOpcode() == ISD::SETCC) {
13783     // Check for setcc([su]{add,sub,mul}o == 0).
13784     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13785         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13786         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13787         Cond.getOperand(0).getResNo() == 1 &&
13788         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13789          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13790          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13791          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13792          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13793          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13794       Inverted = true;
13795       Cond = Cond.getOperand(0);
13796     } else {
13797       SDValue NewCond = LowerSETCC(Cond, DAG);
13798       if (NewCond.getNode())
13799         Cond = NewCond;
13800     }
13801   }
13802 #if 0
13803   // FIXME: LowerXALUO doesn't handle these!!
13804   else if (Cond.getOpcode() == X86ISD::ADD  ||
13805            Cond.getOpcode() == X86ISD::SUB  ||
13806            Cond.getOpcode() == X86ISD::SMUL ||
13807            Cond.getOpcode() == X86ISD::UMUL)
13808     Cond = LowerXALUO(Cond, DAG);
13809 #endif
13810
13811   // Look pass (and (setcc_carry (cmp ...)), 1).
13812   if (Cond.getOpcode() == ISD::AND &&
13813       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13814     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13815     if (C && C->getAPIntValue() == 1)
13816       Cond = Cond.getOperand(0);
13817   }
13818
13819   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13820   // setting operand in place of the X86ISD::SETCC.
13821   unsigned CondOpcode = Cond.getOpcode();
13822   if (CondOpcode == X86ISD::SETCC ||
13823       CondOpcode == X86ISD::SETCC_CARRY) {
13824     CC = Cond.getOperand(0);
13825
13826     SDValue Cmp = Cond.getOperand(1);
13827     unsigned Opc = Cmp.getOpcode();
13828     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13829     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13830       Cond = Cmp;
13831       addTest = false;
13832     } else {
13833       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13834       default: break;
13835       case X86::COND_O:
13836       case X86::COND_B:
13837         // These can only come from an arithmetic instruction with overflow,
13838         // e.g. SADDO, UADDO.
13839         Cond = Cond.getNode()->getOperand(1);
13840         addTest = false;
13841         break;
13842       }
13843     }
13844   }
13845   CondOpcode = Cond.getOpcode();
13846   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13847       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13848       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13849        Cond.getOperand(0).getValueType() != MVT::i8)) {
13850     SDValue LHS = Cond.getOperand(0);
13851     SDValue RHS = Cond.getOperand(1);
13852     unsigned X86Opcode;
13853     unsigned X86Cond;
13854     SDVTList VTs;
13855     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13856     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13857     // X86ISD::INC).
13858     switch (CondOpcode) {
13859     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13860     case ISD::SADDO:
13861       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13862         if (C->isOne()) {
13863           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13864           break;
13865         }
13866       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13867     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13868     case ISD::SSUBO:
13869       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13870         if (C->isOne()) {
13871           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13872           break;
13873         }
13874       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13875     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13876     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13877     default: llvm_unreachable("unexpected overflowing operator");
13878     }
13879     if (Inverted)
13880       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13881     if (CondOpcode == ISD::UMULO)
13882       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13883                           MVT::i32);
13884     else
13885       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13886
13887     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13888
13889     if (CondOpcode == ISD::UMULO)
13890       Cond = X86Op.getValue(2);
13891     else
13892       Cond = X86Op.getValue(1);
13893
13894     CC = DAG.getConstant(X86Cond, MVT::i8);
13895     addTest = false;
13896   } else {
13897     unsigned CondOpc;
13898     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13899       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13900       if (CondOpc == ISD::OR) {
13901         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13902         // two branches instead of an explicit OR instruction with a
13903         // separate test.
13904         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13905             isX86LogicalCmp(Cmp)) {
13906           CC = Cond.getOperand(0).getOperand(0);
13907           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13908                               Chain, Dest, CC, Cmp);
13909           CC = Cond.getOperand(1).getOperand(0);
13910           Cond = Cmp;
13911           addTest = false;
13912         }
13913       } else { // ISD::AND
13914         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13915         // two branches instead of an explicit AND instruction with a
13916         // separate test. However, we only do this if this block doesn't
13917         // have a fall-through edge, because this requires an explicit
13918         // jmp when the condition is false.
13919         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13920             isX86LogicalCmp(Cmp) &&
13921             Op.getNode()->hasOneUse()) {
13922           X86::CondCode CCode =
13923             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13924           CCode = X86::GetOppositeBranchCondition(CCode);
13925           CC = DAG.getConstant(CCode, MVT::i8);
13926           SDNode *User = *Op.getNode()->use_begin();
13927           // Look for an unconditional branch following this conditional branch.
13928           // We need this because we need to reverse the successors in order
13929           // to implement FCMP_OEQ.
13930           if (User->getOpcode() == ISD::BR) {
13931             SDValue FalseBB = User->getOperand(1);
13932             SDNode *NewBR =
13933               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13934             assert(NewBR == User);
13935             (void)NewBR;
13936             Dest = FalseBB;
13937
13938             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13939                                 Chain, Dest, CC, Cmp);
13940             X86::CondCode CCode =
13941               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13942             CCode = X86::GetOppositeBranchCondition(CCode);
13943             CC = DAG.getConstant(CCode, MVT::i8);
13944             Cond = Cmp;
13945             addTest = false;
13946           }
13947         }
13948       }
13949     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13950       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13951       // It should be transformed during dag combiner except when the condition
13952       // is set by a arithmetics with overflow node.
13953       X86::CondCode CCode =
13954         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13955       CCode = X86::GetOppositeBranchCondition(CCode);
13956       CC = DAG.getConstant(CCode, MVT::i8);
13957       Cond = Cond.getOperand(0).getOperand(1);
13958       addTest = false;
13959     } else if (Cond.getOpcode() == ISD::SETCC &&
13960                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13961       // For FCMP_OEQ, we can emit
13962       // two branches instead of an explicit AND instruction with a
13963       // separate test. However, we only do this if this block doesn't
13964       // have a fall-through edge, because this requires an explicit
13965       // jmp when the condition is false.
13966       if (Op.getNode()->hasOneUse()) {
13967         SDNode *User = *Op.getNode()->use_begin();
13968         // Look for an unconditional branch following this conditional branch.
13969         // We need this because we need to reverse the successors in order
13970         // to implement FCMP_OEQ.
13971         if (User->getOpcode() == ISD::BR) {
13972           SDValue FalseBB = User->getOperand(1);
13973           SDNode *NewBR =
13974             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13975           assert(NewBR == User);
13976           (void)NewBR;
13977           Dest = FalseBB;
13978
13979           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13980                                     Cond.getOperand(0), Cond.getOperand(1));
13981           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13982           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13983           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13984                               Chain, Dest, CC, Cmp);
13985           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13986           Cond = Cmp;
13987           addTest = false;
13988         }
13989       }
13990     } else if (Cond.getOpcode() == ISD::SETCC &&
13991                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13992       // For FCMP_UNE, we can emit
13993       // two branches instead of an explicit AND instruction with a
13994       // separate test. However, we only do this if this block doesn't
13995       // have a fall-through edge, because this requires an explicit
13996       // jmp when the condition is false.
13997       if (Op.getNode()->hasOneUse()) {
13998         SDNode *User = *Op.getNode()->use_begin();
13999         // Look for an unconditional branch following this conditional branch.
14000         // We need this because we need to reverse the successors in order
14001         // to implement FCMP_UNE.
14002         if (User->getOpcode() == ISD::BR) {
14003           SDValue FalseBB = User->getOperand(1);
14004           SDNode *NewBR =
14005             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14006           assert(NewBR == User);
14007           (void)NewBR;
14008
14009           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14010                                     Cond.getOperand(0), Cond.getOperand(1));
14011           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14012           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14013           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14014                               Chain, Dest, CC, Cmp);
14015           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14016           Cond = Cmp;
14017           addTest = false;
14018           Dest = FalseBB;
14019         }
14020       }
14021     }
14022   }
14023
14024   if (addTest) {
14025     // Look pass the truncate if the high bits are known zero.
14026     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14027         Cond = Cond.getOperand(0);
14028
14029     // We know the result of AND is compared against zero. Try to match
14030     // it to BT.
14031     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14032       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14033       if (NewSetCC.getNode()) {
14034         CC = NewSetCC.getOperand(0);
14035         Cond = NewSetCC.getOperand(1);
14036         addTest = false;
14037       }
14038     }
14039   }
14040
14041   if (addTest) {
14042     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14043     CC = DAG.getConstant(X86Cond, MVT::i8);
14044     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14045   }
14046   Cond = ConvertCmpIfNecessary(Cond, DAG);
14047   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14048                      Chain, Dest, CC, Cond);
14049 }
14050
14051 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14052 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14053 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14054 // that the guard pages used by the OS virtual memory manager are allocated in
14055 // correct sequence.
14056 SDValue
14057 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14058                                            SelectionDAG &DAG) const {
14059   MachineFunction &MF = DAG.getMachineFunction();
14060   bool SplitStack = MF.shouldSplitStack();
14061   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
14062                SplitStack;
14063   SDLoc dl(Op);
14064
14065   if (!Lower) {
14066     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14067     SDNode* Node = Op.getNode();
14068
14069     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14070     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14071         " not tell us which reg is the stack pointer!");
14072     EVT VT = Node->getValueType(0);
14073     SDValue Tmp1 = SDValue(Node, 0);
14074     SDValue Tmp2 = SDValue(Node, 1);
14075     SDValue Tmp3 = Node->getOperand(2);
14076     SDValue Chain = Tmp1.getOperand(0);
14077
14078     // Chain the dynamic stack allocation so that it doesn't modify the stack
14079     // pointer when other instructions are using the stack.
14080     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14081         SDLoc(Node));
14082
14083     SDValue Size = Tmp2.getOperand(1);
14084     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14085     Chain = SP.getValue(1);
14086     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14087     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
14088     unsigned StackAlign = TFI.getStackAlignment();
14089     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14090     if (Align > StackAlign)
14091       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14092           DAG.getConstant(-(uint64_t)Align, VT));
14093     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14094
14095     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14096         DAG.getIntPtrConstant(0, true), SDValue(),
14097         SDLoc(Node));
14098
14099     SDValue Ops[2] = { Tmp1, Tmp2 };
14100     return DAG.getMergeValues(Ops, dl);
14101   }
14102
14103   // Get the inputs.
14104   SDValue Chain = Op.getOperand(0);
14105   SDValue Size  = Op.getOperand(1);
14106   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14107   EVT VT = Op.getNode()->getValueType(0);
14108
14109   bool Is64Bit = Subtarget->is64Bit();
14110   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
14111
14112   if (SplitStack) {
14113     MachineRegisterInfo &MRI = MF.getRegInfo();
14114
14115     if (Is64Bit) {
14116       // The 64 bit implementation of segmented stacks needs to clobber both r10
14117       // r11. This makes it impossible to use it along with nested parameters.
14118       const Function *F = MF.getFunction();
14119
14120       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14121            I != E; ++I)
14122         if (I->hasNestAttr())
14123           report_fatal_error("Cannot use segmented stacks with functions that "
14124                              "have nested arguments.");
14125     }
14126
14127     const TargetRegisterClass *AddrRegClass =
14128       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
14129     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14130     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14131     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14132                                 DAG.getRegister(Vreg, SPTy));
14133     SDValue Ops1[2] = { Value, Chain };
14134     return DAG.getMergeValues(Ops1, dl);
14135   } else {
14136     SDValue Flag;
14137     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
14138
14139     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14140     Flag = Chain.getValue(1);
14141     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14142
14143     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14144
14145     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
14146         DAG.getSubtarget().getRegisterInfo());
14147     unsigned SPReg = RegInfo->getStackRegister();
14148     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14149     Chain = SP.getValue(1);
14150
14151     if (Align) {
14152       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14153                        DAG.getConstant(-(uint64_t)Align, VT));
14154       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14155     }
14156
14157     SDValue Ops1[2] = { SP, Chain };
14158     return DAG.getMergeValues(Ops1, dl);
14159   }
14160 }
14161
14162 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14163   MachineFunction &MF = DAG.getMachineFunction();
14164   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14165
14166   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14167   SDLoc DL(Op);
14168
14169   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14170     // vastart just stores the address of the VarArgsFrameIndex slot into the
14171     // memory location argument.
14172     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14173                                    getPointerTy());
14174     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14175                         MachinePointerInfo(SV), false, false, 0);
14176   }
14177
14178   // __va_list_tag:
14179   //   gp_offset         (0 - 6 * 8)
14180   //   fp_offset         (48 - 48 + 8 * 16)
14181   //   overflow_arg_area (point to parameters coming in memory).
14182   //   reg_save_area
14183   SmallVector<SDValue, 8> MemOps;
14184   SDValue FIN = Op.getOperand(1);
14185   // Store gp_offset
14186   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14187                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14188                                                MVT::i32),
14189                                FIN, MachinePointerInfo(SV), false, false, 0);
14190   MemOps.push_back(Store);
14191
14192   // Store fp_offset
14193   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14194                     FIN, DAG.getIntPtrConstant(4));
14195   Store = DAG.getStore(Op.getOperand(0), DL,
14196                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14197                                        MVT::i32),
14198                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14199   MemOps.push_back(Store);
14200
14201   // Store ptr to overflow_arg_area
14202   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14203                     FIN, DAG.getIntPtrConstant(4));
14204   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14205                                     getPointerTy());
14206   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14207                        MachinePointerInfo(SV, 8),
14208                        false, false, 0);
14209   MemOps.push_back(Store);
14210
14211   // Store ptr to reg_save_area.
14212   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14213                     FIN, DAG.getIntPtrConstant(8));
14214   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14215                                     getPointerTy());
14216   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14217                        MachinePointerInfo(SV, 16), false, false, 0);
14218   MemOps.push_back(Store);
14219   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14220 }
14221
14222 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14223   assert(Subtarget->is64Bit() &&
14224          "LowerVAARG only handles 64-bit va_arg!");
14225   assert((Subtarget->isTargetLinux() ||
14226           Subtarget->isTargetDarwin()) &&
14227           "Unhandled target in LowerVAARG");
14228   assert(Op.getNode()->getNumOperands() == 4);
14229   SDValue Chain = Op.getOperand(0);
14230   SDValue SrcPtr = Op.getOperand(1);
14231   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14232   unsigned Align = Op.getConstantOperandVal(3);
14233   SDLoc dl(Op);
14234
14235   EVT ArgVT = Op.getNode()->getValueType(0);
14236   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14237   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14238   uint8_t ArgMode;
14239
14240   // Decide which area this value should be read from.
14241   // TODO: Implement the AMD64 ABI in its entirety. This simple
14242   // selection mechanism works only for the basic types.
14243   if (ArgVT == MVT::f80) {
14244     llvm_unreachable("va_arg for f80 not yet implemented");
14245   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14246     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14247   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14248     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14249   } else {
14250     llvm_unreachable("Unhandled argument type in LowerVAARG");
14251   }
14252
14253   if (ArgMode == 2) {
14254     // Sanity Check: Make sure using fp_offset makes sense.
14255     assert(!DAG.getTarget().Options.UseSoftFloat &&
14256            !(DAG.getMachineFunction()
14257                 .getFunction()->getAttributes()
14258                 .hasAttribute(AttributeSet::FunctionIndex,
14259                               Attribute::NoImplicitFloat)) &&
14260            Subtarget->hasSSE1());
14261   }
14262
14263   // Insert VAARG_64 node into the DAG
14264   // VAARG_64 returns two values: Variable Argument Address, Chain
14265   SmallVector<SDValue, 11> InstOps;
14266   InstOps.push_back(Chain);
14267   InstOps.push_back(SrcPtr);
14268   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
14269   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
14270   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
14271   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14272   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14273                                           VTs, InstOps, MVT::i64,
14274                                           MachinePointerInfo(SV),
14275                                           /*Align=*/0,
14276                                           /*Volatile=*/false,
14277                                           /*ReadMem=*/true,
14278                                           /*WriteMem=*/true);
14279   Chain = VAARG.getValue(1);
14280
14281   // Load the next argument and return it
14282   return DAG.getLoad(ArgVT, dl,
14283                      Chain,
14284                      VAARG,
14285                      MachinePointerInfo(),
14286                      false, false, false, 0);
14287 }
14288
14289 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14290                            SelectionDAG &DAG) {
14291   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14292   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14293   SDValue Chain = Op.getOperand(0);
14294   SDValue DstPtr = Op.getOperand(1);
14295   SDValue SrcPtr = Op.getOperand(2);
14296   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14297   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14298   SDLoc DL(Op);
14299
14300   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14301                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14302                        false,
14303                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14304 }
14305
14306 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14307 // amount is a constant. Takes immediate version of shift as input.
14308 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14309                                           SDValue SrcOp, uint64_t ShiftAmt,
14310                                           SelectionDAG &DAG) {
14311   MVT ElementType = VT.getVectorElementType();
14312
14313   // Fold this packed shift into its first operand if ShiftAmt is 0.
14314   if (ShiftAmt == 0)
14315     return SrcOp;
14316
14317   // Check for ShiftAmt >= element width
14318   if (ShiftAmt >= ElementType.getSizeInBits()) {
14319     if (Opc == X86ISD::VSRAI)
14320       ShiftAmt = ElementType.getSizeInBits() - 1;
14321     else
14322       return DAG.getConstant(0, VT);
14323   }
14324
14325   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14326          && "Unknown target vector shift-by-constant node");
14327
14328   // Fold this packed vector shift into a build vector if SrcOp is a
14329   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14330   if (VT == SrcOp.getSimpleValueType() &&
14331       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14332     SmallVector<SDValue, 8> Elts;
14333     unsigned NumElts = SrcOp->getNumOperands();
14334     ConstantSDNode *ND;
14335
14336     switch(Opc) {
14337     default: llvm_unreachable(nullptr);
14338     case X86ISD::VSHLI:
14339       for (unsigned i=0; i!=NumElts; ++i) {
14340         SDValue CurrentOp = SrcOp->getOperand(i);
14341         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14342           Elts.push_back(CurrentOp);
14343           continue;
14344         }
14345         ND = cast<ConstantSDNode>(CurrentOp);
14346         const APInt &C = ND->getAPIntValue();
14347         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14348       }
14349       break;
14350     case X86ISD::VSRLI:
14351       for (unsigned i=0; i!=NumElts; ++i) {
14352         SDValue CurrentOp = SrcOp->getOperand(i);
14353         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14354           Elts.push_back(CurrentOp);
14355           continue;
14356         }
14357         ND = cast<ConstantSDNode>(CurrentOp);
14358         const APInt &C = ND->getAPIntValue();
14359         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14360       }
14361       break;
14362     case X86ISD::VSRAI:
14363       for (unsigned i=0; i!=NumElts; ++i) {
14364         SDValue CurrentOp = SrcOp->getOperand(i);
14365         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14366           Elts.push_back(CurrentOp);
14367           continue;
14368         }
14369         ND = cast<ConstantSDNode>(CurrentOp);
14370         const APInt &C = ND->getAPIntValue();
14371         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14372       }
14373       break;
14374     }
14375
14376     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14377   }
14378
14379   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14380 }
14381
14382 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14383 // may or may not be a constant. Takes immediate version of shift as input.
14384 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14385                                    SDValue SrcOp, SDValue ShAmt,
14386                                    SelectionDAG &DAG) {
14387   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14388
14389   // Catch shift-by-constant.
14390   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14391     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14392                                       CShAmt->getZExtValue(), DAG);
14393
14394   // Change opcode to non-immediate version
14395   switch (Opc) {
14396     default: llvm_unreachable("Unknown target vector shift node");
14397     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14398     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14399     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14400   }
14401
14402   // Need to build a vector containing shift amount
14403   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14404   SDValue ShOps[4];
14405   ShOps[0] = ShAmt;
14406   ShOps[1] = DAG.getConstant(0, MVT::i32);
14407   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14408   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14409
14410   // The return type has to be a 128-bit type with the same element
14411   // type as the input type.
14412   MVT EltVT = VT.getVectorElementType();
14413   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14414
14415   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14416   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14417 }
14418
14419 /// \brief Return (vselect \p Mask, \p Op, \p PreservedSrc) along with the
14420 /// necessary casting for \p Mask when lowering masking intrinsics.
14421 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14422                                     SDValue PreservedSrc, SelectionDAG &DAG) {
14423     EVT VT = Op.getValueType();
14424     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14425                                   MVT::i1, VT.getVectorNumElements());
14426     SDLoc dl(Op);
14427
14428     assert(MaskVT.isSimple() && "invalid mask type");
14429     return DAG.getNode(ISD::VSELECT, dl, VT,
14430                        DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask),
14431                        Op, PreservedSrc);
14432 }
14433
14434 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
14435     switch (IntNo) {
14436     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14437     case Intrinsic::x86_fma_vfmadd_ps:
14438     case Intrinsic::x86_fma_vfmadd_pd:
14439     case Intrinsic::x86_fma_vfmadd_ps_256:
14440     case Intrinsic::x86_fma_vfmadd_pd_256:
14441     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14442     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14443       return X86ISD::FMADD;
14444     case Intrinsic::x86_fma_vfmsub_ps:
14445     case Intrinsic::x86_fma_vfmsub_pd:
14446     case Intrinsic::x86_fma_vfmsub_ps_256:
14447     case Intrinsic::x86_fma_vfmsub_pd_256:
14448     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14449     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14450       return X86ISD::FMSUB;
14451     case Intrinsic::x86_fma_vfnmadd_ps:
14452     case Intrinsic::x86_fma_vfnmadd_pd:
14453     case Intrinsic::x86_fma_vfnmadd_ps_256:
14454     case Intrinsic::x86_fma_vfnmadd_pd_256:
14455     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14456     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14457       return X86ISD::FNMADD;
14458     case Intrinsic::x86_fma_vfnmsub_ps:
14459     case Intrinsic::x86_fma_vfnmsub_pd:
14460     case Intrinsic::x86_fma_vfnmsub_ps_256:
14461     case Intrinsic::x86_fma_vfnmsub_pd_256:
14462     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14463     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14464       return X86ISD::FNMSUB;
14465     case Intrinsic::x86_fma_vfmaddsub_ps:
14466     case Intrinsic::x86_fma_vfmaddsub_pd:
14467     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14468     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14469     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14470     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14471       return X86ISD::FMADDSUB;
14472     case Intrinsic::x86_fma_vfmsubadd_ps:
14473     case Intrinsic::x86_fma_vfmsubadd_pd:
14474     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14475     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14476     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14477     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
14478       return X86ISD::FMSUBADD;
14479     }
14480 }
14481
14482 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14483   SDLoc dl(Op);
14484   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14485   switch (IntNo) {
14486   default: return SDValue();    // Don't custom lower most intrinsics.
14487   // Comparison intrinsics.
14488   case Intrinsic::x86_sse_comieq_ss:
14489   case Intrinsic::x86_sse_comilt_ss:
14490   case Intrinsic::x86_sse_comile_ss:
14491   case Intrinsic::x86_sse_comigt_ss:
14492   case Intrinsic::x86_sse_comige_ss:
14493   case Intrinsic::x86_sse_comineq_ss:
14494   case Intrinsic::x86_sse_ucomieq_ss:
14495   case Intrinsic::x86_sse_ucomilt_ss:
14496   case Intrinsic::x86_sse_ucomile_ss:
14497   case Intrinsic::x86_sse_ucomigt_ss:
14498   case Intrinsic::x86_sse_ucomige_ss:
14499   case Intrinsic::x86_sse_ucomineq_ss:
14500   case Intrinsic::x86_sse2_comieq_sd:
14501   case Intrinsic::x86_sse2_comilt_sd:
14502   case Intrinsic::x86_sse2_comile_sd:
14503   case Intrinsic::x86_sse2_comigt_sd:
14504   case Intrinsic::x86_sse2_comige_sd:
14505   case Intrinsic::x86_sse2_comineq_sd:
14506   case Intrinsic::x86_sse2_ucomieq_sd:
14507   case Intrinsic::x86_sse2_ucomilt_sd:
14508   case Intrinsic::x86_sse2_ucomile_sd:
14509   case Intrinsic::x86_sse2_ucomigt_sd:
14510   case Intrinsic::x86_sse2_ucomige_sd:
14511   case Intrinsic::x86_sse2_ucomineq_sd: {
14512     unsigned Opc;
14513     ISD::CondCode CC;
14514     switch (IntNo) {
14515     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14516     case Intrinsic::x86_sse_comieq_ss:
14517     case Intrinsic::x86_sse2_comieq_sd:
14518       Opc = X86ISD::COMI;
14519       CC = ISD::SETEQ;
14520       break;
14521     case Intrinsic::x86_sse_comilt_ss:
14522     case Intrinsic::x86_sse2_comilt_sd:
14523       Opc = X86ISD::COMI;
14524       CC = ISD::SETLT;
14525       break;
14526     case Intrinsic::x86_sse_comile_ss:
14527     case Intrinsic::x86_sse2_comile_sd:
14528       Opc = X86ISD::COMI;
14529       CC = ISD::SETLE;
14530       break;
14531     case Intrinsic::x86_sse_comigt_ss:
14532     case Intrinsic::x86_sse2_comigt_sd:
14533       Opc = X86ISD::COMI;
14534       CC = ISD::SETGT;
14535       break;
14536     case Intrinsic::x86_sse_comige_ss:
14537     case Intrinsic::x86_sse2_comige_sd:
14538       Opc = X86ISD::COMI;
14539       CC = ISD::SETGE;
14540       break;
14541     case Intrinsic::x86_sse_comineq_ss:
14542     case Intrinsic::x86_sse2_comineq_sd:
14543       Opc = X86ISD::COMI;
14544       CC = ISD::SETNE;
14545       break;
14546     case Intrinsic::x86_sse_ucomieq_ss:
14547     case Intrinsic::x86_sse2_ucomieq_sd:
14548       Opc = X86ISD::UCOMI;
14549       CC = ISD::SETEQ;
14550       break;
14551     case Intrinsic::x86_sse_ucomilt_ss:
14552     case Intrinsic::x86_sse2_ucomilt_sd:
14553       Opc = X86ISD::UCOMI;
14554       CC = ISD::SETLT;
14555       break;
14556     case Intrinsic::x86_sse_ucomile_ss:
14557     case Intrinsic::x86_sse2_ucomile_sd:
14558       Opc = X86ISD::UCOMI;
14559       CC = ISD::SETLE;
14560       break;
14561     case Intrinsic::x86_sse_ucomigt_ss:
14562     case Intrinsic::x86_sse2_ucomigt_sd:
14563       Opc = X86ISD::UCOMI;
14564       CC = ISD::SETGT;
14565       break;
14566     case Intrinsic::x86_sse_ucomige_ss:
14567     case Intrinsic::x86_sse2_ucomige_sd:
14568       Opc = X86ISD::UCOMI;
14569       CC = ISD::SETGE;
14570       break;
14571     case Intrinsic::x86_sse_ucomineq_ss:
14572     case Intrinsic::x86_sse2_ucomineq_sd:
14573       Opc = X86ISD::UCOMI;
14574       CC = ISD::SETNE;
14575       break;
14576     }
14577
14578     SDValue LHS = Op.getOperand(1);
14579     SDValue RHS = Op.getOperand(2);
14580     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14581     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14582     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
14583     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14584                                 DAG.getConstant(X86CC, MVT::i8), Cond);
14585     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14586   }
14587
14588   // Arithmetic intrinsics.
14589   case Intrinsic::x86_sse2_pmulu_dq:
14590   case Intrinsic::x86_avx2_pmulu_dq:
14591     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14592                        Op.getOperand(1), Op.getOperand(2));
14593
14594   case Intrinsic::x86_sse41_pmuldq:
14595   case Intrinsic::x86_avx2_pmul_dq:
14596     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14597                        Op.getOperand(1), Op.getOperand(2));
14598
14599   case Intrinsic::x86_sse2_pmulhu_w:
14600   case Intrinsic::x86_avx2_pmulhu_w:
14601     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14602                        Op.getOperand(1), Op.getOperand(2));
14603
14604   case Intrinsic::x86_sse2_pmulh_w:
14605   case Intrinsic::x86_avx2_pmulh_w:
14606     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14607                        Op.getOperand(1), Op.getOperand(2));
14608
14609   // SSE2/AVX2 sub with unsigned saturation intrinsics
14610   case Intrinsic::x86_sse2_psubus_b:
14611   case Intrinsic::x86_sse2_psubus_w:
14612   case Intrinsic::x86_avx2_psubus_b:
14613   case Intrinsic::x86_avx2_psubus_w:
14614     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
14615                        Op.getOperand(1), Op.getOperand(2));
14616
14617   // SSE3/AVX horizontal add/sub intrinsics
14618   case Intrinsic::x86_sse3_hadd_ps:
14619   case Intrinsic::x86_sse3_hadd_pd:
14620   case Intrinsic::x86_avx_hadd_ps_256:
14621   case Intrinsic::x86_avx_hadd_pd_256:
14622   case Intrinsic::x86_sse3_hsub_ps:
14623   case Intrinsic::x86_sse3_hsub_pd:
14624   case Intrinsic::x86_avx_hsub_ps_256:
14625   case Intrinsic::x86_avx_hsub_pd_256:
14626   case Intrinsic::x86_ssse3_phadd_w_128:
14627   case Intrinsic::x86_ssse3_phadd_d_128:
14628   case Intrinsic::x86_avx2_phadd_w:
14629   case Intrinsic::x86_avx2_phadd_d:
14630   case Intrinsic::x86_ssse3_phsub_w_128:
14631   case Intrinsic::x86_ssse3_phsub_d_128:
14632   case Intrinsic::x86_avx2_phsub_w:
14633   case Intrinsic::x86_avx2_phsub_d: {
14634     unsigned Opcode;
14635     switch (IntNo) {
14636     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14637     case Intrinsic::x86_sse3_hadd_ps:
14638     case Intrinsic::x86_sse3_hadd_pd:
14639     case Intrinsic::x86_avx_hadd_ps_256:
14640     case Intrinsic::x86_avx_hadd_pd_256:
14641       Opcode = X86ISD::FHADD;
14642       break;
14643     case Intrinsic::x86_sse3_hsub_ps:
14644     case Intrinsic::x86_sse3_hsub_pd:
14645     case Intrinsic::x86_avx_hsub_ps_256:
14646     case Intrinsic::x86_avx_hsub_pd_256:
14647       Opcode = X86ISD::FHSUB;
14648       break;
14649     case Intrinsic::x86_ssse3_phadd_w_128:
14650     case Intrinsic::x86_ssse3_phadd_d_128:
14651     case Intrinsic::x86_avx2_phadd_w:
14652     case Intrinsic::x86_avx2_phadd_d:
14653       Opcode = X86ISD::HADD;
14654       break;
14655     case Intrinsic::x86_ssse3_phsub_w_128:
14656     case Intrinsic::x86_ssse3_phsub_d_128:
14657     case Intrinsic::x86_avx2_phsub_w:
14658     case Intrinsic::x86_avx2_phsub_d:
14659       Opcode = X86ISD::HSUB;
14660       break;
14661     }
14662     return DAG.getNode(Opcode, dl, Op.getValueType(),
14663                        Op.getOperand(1), Op.getOperand(2));
14664   }
14665
14666   // SSE2/SSE41/AVX2 integer max/min intrinsics.
14667   case Intrinsic::x86_sse2_pmaxu_b:
14668   case Intrinsic::x86_sse41_pmaxuw:
14669   case Intrinsic::x86_sse41_pmaxud:
14670   case Intrinsic::x86_avx2_pmaxu_b:
14671   case Intrinsic::x86_avx2_pmaxu_w:
14672   case Intrinsic::x86_avx2_pmaxu_d:
14673   case Intrinsic::x86_sse2_pminu_b:
14674   case Intrinsic::x86_sse41_pminuw:
14675   case Intrinsic::x86_sse41_pminud:
14676   case Intrinsic::x86_avx2_pminu_b:
14677   case Intrinsic::x86_avx2_pminu_w:
14678   case Intrinsic::x86_avx2_pminu_d:
14679   case Intrinsic::x86_sse41_pmaxsb:
14680   case Intrinsic::x86_sse2_pmaxs_w:
14681   case Intrinsic::x86_sse41_pmaxsd:
14682   case Intrinsic::x86_avx2_pmaxs_b:
14683   case Intrinsic::x86_avx2_pmaxs_w:
14684   case Intrinsic::x86_avx2_pmaxs_d:
14685   case Intrinsic::x86_sse41_pminsb:
14686   case Intrinsic::x86_sse2_pmins_w:
14687   case Intrinsic::x86_sse41_pminsd:
14688   case Intrinsic::x86_avx2_pmins_b:
14689   case Intrinsic::x86_avx2_pmins_w:
14690   case Intrinsic::x86_avx2_pmins_d: {
14691     unsigned Opcode;
14692     switch (IntNo) {
14693     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14694     case Intrinsic::x86_sse2_pmaxu_b:
14695     case Intrinsic::x86_sse41_pmaxuw:
14696     case Intrinsic::x86_sse41_pmaxud:
14697     case Intrinsic::x86_avx2_pmaxu_b:
14698     case Intrinsic::x86_avx2_pmaxu_w:
14699     case Intrinsic::x86_avx2_pmaxu_d:
14700       Opcode = X86ISD::UMAX;
14701       break;
14702     case Intrinsic::x86_sse2_pminu_b:
14703     case Intrinsic::x86_sse41_pminuw:
14704     case Intrinsic::x86_sse41_pminud:
14705     case Intrinsic::x86_avx2_pminu_b:
14706     case Intrinsic::x86_avx2_pminu_w:
14707     case Intrinsic::x86_avx2_pminu_d:
14708       Opcode = X86ISD::UMIN;
14709       break;
14710     case Intrinsic::x86_sse41_pmaxsb:
14711     case Intrinsic::x86_sse2_pmaxs_w:
14712     case Intrinsic::x86_sse41_pmaxsd:
14713     case Intrinsic::x86_avx2_pmaxs_b:
14714     case Intrinsic::x86_avx2_pmaxs_w:
14715     case Intrinsic::x86_avx2_pmaxs_d:
14716       Opcode = X86ISD::SMAX;
14717       break;
14718     case Intrinsic::x86_sse41_pminsb:
14719     case Intrinsic::x86_sse2_pmins_w:
14720     case Intrinsic::x86_sse41_pminsd:
14721     case Intrinsic::x86_avx2_pmins_b:
14722     case Intrinsic::x86_avx2_pmins_w:
14723     case Intrinsic::x86_avx2_pmins_d:
14724       Opcode = X86ISD::SMIN;
14725       break;
14726     }
14727     return DAG.getNode(Opcode, dl, Op.getValueType(),
14728                        Op.getOperand(1), Op.getOperand(2));
14729   }
14730
14731   // SSE/SSE2/AVX floating point max/min intrinsics.
14732   case Intrinsic::x86_sse_max_ps:
14733   case Intrinsic::x86_sse2_max_pd:
14734   case Intrinsic::x86_avx_max_ps_256:
14735   case Intrinsic::x86_avx_max_pd_256:
14736   case Intrinsic::x86_sse_min_ps:
14737   case Intrinsic::x86_sse2_min_pd:
14738   case Intrinsic::x86_avx_min_ps_256:
14739   case Intrinsic::x86_avx_min_pd_256: {
14740     unsigned Opcode;
14741     switch (IntNo) {
14742     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14743     case Intrinsic::x86_sse_max_ps:
14744     case Intrinsic::x86_sse2_max_pd:
14745     case Intrinsic::x86_avx_max_ps_256:
14746     case Intrinsic::x86_avx_max_pd_256:
14747       Opcode = X86ISD::FMAX;
14748       break;
14749     case Intrinsic::x86_sse_min_ps:
14750     case Intrinsic::x86_sse2_min_pd:
14751     case Intrinsic::x86_avx_min_ps_256:
14752     case Intrinsic::x86_avx_min_pd_256:
14753       Opcode = X86ISD::FMIN;
14754       break;
14755     }
14756     return DAG.getNode(Opcode, dl, Op.getValueType(),
14757                        Op.getOperand(1), Op.getOperand(2));
14758   }
14759
14760   // AVX2 variable shift intrinsics
14761   case Intrinsic::x86_avx2_psllv_d:
14762   case Intrinsic::x86_avx2_psllv_q:
14763   case Intrinsic::x86_avx2_psllv_d_256:
14764   case Intrinsic::x86_avx2_psllv_q_256:
14765   case Intrinsic::x86_avx2_psrlv_d:
14766   case Intrinsic::x86_avx2_psrlv_q:
14767   case Intrinsic::x86_avx2_psrlv_d_256:
14768   case Intrinsic::x86_avx2_psrlv_q_256:
14769   case Intrinsic::x86_avx2_psrav_d:
14770   case Intrinsic::x86_avx2_psrav_d_256: {
14771     unsigned Opcode;
14772     switch (IntNo) {
14773     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14774     case Intrinsic::x86_avx2_psllv_d:
14775     case Intrinsic::x86_avx2_psllv_q:
14776     case Intrinsic::x86_avx2_psllv_d_256:
14777     case Intrinsic::x86_avx2_psllv_q_256:
14778       Opcode = ISD::SHL;
14779       break;
14780     case Intrinsic::x86_avx2_psrlv_d:
14781     case Intrinsic::x86_avx2_psrlv_q:
14782     case Intrinsic::x86_avx2_psrlv_d_256:
14783     case Intrinsic::x86_avx2_psrlv_q_256:
14784       Opcode = ISD::SRL;
14785       break;
14786     case Intrinsic::x86_avx2_psrav_d:
14787     case Intrinsic::x86_avx2_psrav_d_256:
14788       Opcode = ISD::SRA;
14789       break;
14790     }
14791     return DAG.getNode(Opcode, dl, Op.getValueType(),
14792                        Op.getOperand(1), Op.getOperand(2));
14793   }
14794
14795   case Intrinsic::x86_sse2_packssdw_128:
14796   case Intrinsic::x86_sse2_packsswb_128:
14797   case Intrinsic::x86_avx2_packssdw:
14798   case Intrinsic::x86_avx2_packsswb:
14799     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14800                        Op.getOperand(1), Op.getOperand(2));
14801
14802   case Intrinsic::x86_sse2_packuswb_128:
14803   case Intrinsic::x86_sse41_packusdw:
14804   case Intrinsic::x86_avx2_packuswb:
14805   case Intrinsic::x86_avx2_packusdw:
14806     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14807                        Op.getOperand(1), Op.getOperand(2));
14808
14809   case Intrinsic::x86_ssse3_pshuf_b_128:
14810   case Intrinsic::x86_avx2_pshuf_b:
14811     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14812                        Op.getOperand(1), Op.getOperand(2));
14813
14814   case Intrinsic::x86_sse2_pshuf_d:
14815     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14816                        Op.getOperand(1), Op.getOperand(2));
14817
14818   case Intrinsic::x86_sse2_pshufl_w:
14819     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14820                        Op.getOperand(1), Op.getOperand(2));
14821
14822   case Intrinsic::x86_sse2_pshufh_w:
14823     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14824                        Op.getOperand(1), Op.getOperand(2));
14825
14826   case Intrinsic::x86_ssse3_psign_b_128:
14827   case Intrinsic::x86_ssse3_psign_w_128:
14828   case Intrinsic::x86_ssse3_psign_d_128:
14829   case Intrinsic::x86_avx2_psign_b:
14830   case Intrinsic::x86_avx2_psign_w:
14831   case Intrinsic::x86_avx2_psign_d:
14832     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14833                        Op.getOperand(1), Op.getOperand(2));
14834
14835   case Intrinsic::x86_sse41_insertps:
14836     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14837                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14838
14839   case Intrinsic::x86_avx_vperm2f128_ps_256:
14840   case Intrinsic::x86_avx_vperm2f128_pd_256:
14841   case Intrinsic::x86_avx_vperm2f128_si_256:
14842   case Intrinsic::x86_avx2_vperm2i128:
14843     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14844                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14845
14846   case Intrinsic::x86_avx2_permd:
14847   case Intrinsic::x86_avx2_permps:
14848     // Operands intentionally swapped. Mask is last operand to intrinsic,
14849     // but second operand for node/instruction.
14850     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14851                        Op.getOperand(2), Op.getOperand(1));
14852
14853   case Intrinsic::x86_sse_sqrt_ps:
14854   case Intrinsic::x86_sse2_sqrt_pd:
14855   case Intrinsic::x86_avx_sqrt_ps_256:
14856   case Intrinsic::x86_avx_sqrt_pd_256:
14857     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14858
14859   case Intrinsic::x86_avx512_mask_valign_q_512:
14860   case Intrinsic::x86_avx512_mask_valign_d_512:
14861     // Vector source operands are swapped.
14862     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14863                                             Op.getValueType(), Op.getOperand(2),
14864                                             Op.getOperand(1),
14865                                             Op.getOperand(3)),
14866                                 Op.getOperand(5), Op.getOperand(4), DAG);
14867
14868   // ptest and testp intrinsics. The intrinsic these come from are designed to
14869   // return an integer value, not just an instruction so lower it to the ptest
14870   // or testp pattern and a setcc for the result.
14871   case Intrinsic::x86_sse41_ptestz:
14872   case Intrinsic::x86_sse41_ptestc:
14873   case Intrinsic::x86_sse41_ptestnzc:
14874   case Intrinsic::x86_avx_ptestz_256:
14875   case Intrinsic::x86_avx_ptestc_256:
14876   case Intrinsic::x86_avx_ptestnzc_256:
14877   case Intrinsic::x86_avx_vtestz_ps:
14878   case Intrinsic::x86_avx_vtestc_ps:
14879   case Intrinsic::x86_avx_vtestnzc_ps:
14880   case Intrinsic::x86_avx_vtestz_pd:
14881   case Intrinsic::x86_avx_vtestc_pd:
14882   case Intrinsic::x86_avx_vtestnzc_pd:
14883   case Intrinsic::x86_avx_vtestz_ps_256:
14884   case Intrinsic::x86_avx_vtestc_ps_256:
14885   case Intrinsic::x86_avx_vtestnzc_ps_256:
14886   case Intrinsic::x86_avx_vtestz_pd_256:
14887   case Intrinsic::x86_avx_vtestc_pd_256:
14888   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14889     bool IsTestPacked = false;
14890     unsigned X86CC;
14891     switch (IntNo) {
14892     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14893     case Intrinsic::x86_avx_vtestz_ps:
14894     case Intrinsic::x86_avx_vtestz_pd:
14895     case Intrinsic::x86_avx_vtestz_ps_256:
14896     case Intrinsic::x86_avx_vtestz_pd_256:
14897       IsTestPacked = true; // Fallthrough
14898     case Intrinsic::x86_sse41_ptestz:
14899     case Intrinsic::x86_avx_ptestz_256:
14900       // ZF = 1
14901       X86CC = X86::COND_E;
14902       break;
14903     case Intrinsic::x86_avx_vtestc_ps:
14904     case Intrinsic::x86_avx_vtestc_pd:
14905     case Intrinsic::x86_avx_vtestc_ps_256:
14906     case Intrinsic::x86_avx_vtestc_pd_256:
14907       IsTestPacked = true; // Fallthrough
14908     case Intrinsic::x86_sse41_ptestc:
14909     case Intrinsic::x86_avx_ptestc_256:
14910       // CF = 1
14911       X86CC = X86::COND_B;
14912       break;
14913     case Intrinsic::x86_avx_vtestnzc_ps:
14914     case Intrinsic::x86_avx_vtestnzc_pd:
14915     case Intrinsic::x86_avx_vtestnzc_ps_256:
14916     case Intrinsic::x86_avx_vtestnzc_pd_256:
14917       IsTestPacked = true; // Fallthrough
14918     case Intrinsic::x86_sse41_ptestnzc:
14919     case Intrinsic::x86_avx_ptestnzc_256:
14920       // ZF and CF = 0
14921       X86CC = X86::COND_A;
14922       break;
14923     }
14924
14925     SDValue LHS = Op.getOperand(1);
14926     SDValue RHS = Op.getOperand(2);
14927     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14928     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14929     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14930     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14931     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14932   }
14933   case Intrinsic::x86_avx512_kortestz_w:
14934   case Intrinsic::x86_avx512_kortestc_w: {
14935     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14936     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14937     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14938     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14939     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14940     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14941     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14942   }
14943
14944   // SSE/AVX shift intrinsics
14945   case Intrinsic::x86_sse2_psll_w:
14946   case Intrinsic::x86_sse2_psll_d:
14947   case Intrinsic::x86_sse2_psll_q:
14948   case Intrinsic::x86_avx2_psll_w:
14949   case Intrinsic::x86_avx2_psll_d:
14950   case Intrinsic::x86_avx2_psll_q:
14951   case Intrinsic::x86_sse2_psrl_w:
14952   case Intrinsic::x86_sse2_psrl_d:
14953   case Intrinsic::x86_sse2_psrl_q:
14954   case Intrinsic::x86_avx2_psrl_w:
14955   case Intrinsic::x86_avx2_psrl_d:
14956   case Intrinsic::x86_avx2_psrl_q:
14957   case Intrinsic::x86_sse2_psra_w:
14958   case Intrinsic::x86_sse2_psra_d:
14959   case Intrinsic::x86_avx2_psra_w:
14960   case Intrinsic::x86_avx2_psra_d: {
14961     unsigned Opcode;
14962     switch (IntNo) {
14963     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14964     case Intrinsic::x86_sse2_psll_w:
14965     case Intrinsic::x86_sse2_psll_d:
14966     case Intrinsic::x86_sse2_psll_q:
14967     case Intrinsic::x86_avx2_psll_w:
14968     case Intrinsic::x86_avx2_psll_d:
14969     case Intrinsic::x86_avx2_psll_q:
14970       Opcode = X86ISD::VSHL;
14971       break;
14972     case Intrinsic::x86_sse2_psrl_w:
14973     case Intrinsic::x86_sse2_psrl_d:
14974     case Intrinsic::x86_sse2_psrl_q:
14975     case Intrinsic::x86_avx2_psrl_w:
14976     case Intrinsic::x86_avx2_psrl_d:
14977     case Intrinsic::x86_avx2_psrl_q:
14978       Opcode = X86ISD::VSRL;
14979       break;
14980     case Intrinsic::x86_sse2_psra_w:
14981     case Intrinsic::x86_sse2_psra_d:
14982     case Intrinsic::x86_avx2_psra_w:
14983     case Intrinsic::x86_avx2_psra_d:
14984       Opcode = X86ISD::VSRA;
14985       break;
14986     }
14987     return DAG.getNode(Opcode, dl, Op.getValueType(),
14988                        Op.getOperand(1), Op.getOperand(2));
14989   }
14990
14991   // SSE/AVX immediate shift intrinsics
14992   case Intrinsic::x86_sse2_pslli_w:
14993   case Intrinsic::x86_sse2_pslli_d:
14994   case Intrinsic::x86_sse2_pslli_q:
14995   case Intrinsic::x86_avx2_pslli_w:
14996   case Intrinsic::x86_avx2_pslli_d:
14997   case Intrinsic::x86_avx2_pslli_q:
14998   case Intrinsic::x86_sse2_psrli_w:
14999   case Intrinsic::x86_sse2_psrli_d:
15000   case Intrinsic::x86_sse2_psrli_q:
15001   case Intrinsic::x86_avx2_psrli_w:
15002   case Intrinsic::x86_avx2_psrli_d:
15003   case Intrinsic::x86_avx2_psrli_q:
15004   case Intrinsic::x86_sse2_psrai_w:
15005   case Intrinsic::x86_sse2_psrai_d:
15006   case Intrinsic::x86_avx2_psrai_w:
15007   case Intrinsic::x86_avx2_psrai_d: {
15008     unsigned Opcode;
15009     switch (IntNo) {
15010     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15011     case Intrinsic::x86_sse2_pslli_w:
15012     case Intrinsic::x86_sse2_pslli_d:
15013     case Intrinsic::x86_sse2_pslli_q:
15014     case Intrinsic::x86_avx2_pslli_w:
15015     case Intrinsic::x86_avx2_pslli_d:
15016     case Intrinsic::x86_avx2_pslli_q:
15017       Opcode = X86ISD::VSHLI;
15018       break;
15019     case Intrinsic::x86_sse2_psrli_w:
15020     case Intrinsic::x86_sse2_psrli_d:
15021     case Intrinsic::x86_sse2_psrli_q:
15022     case Intrinsic::x86_avx2_psrli_w:
15023     case Intrinsic::x86_avx2_psrli_d:
15024     case Intrinsic::x86_avx2_psrli_q:
15025       Opcode = X86ISD::VSRLI;
15026       break;
15027     case Intrinsic::x86_sse2_psrai_w:
15028     case Intrinsic::x86_sse2_psrai_d:
15029     case Intrinsic::x86_avx2_psrai_w:
15030     case Intrinsic::x86_avx2_psrai_d:
15031       Opcode = X86ISD::VSRAI;
15032       break;
15033     }
15034     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
15035                                Op.getOperand(1), Op.getOperand(2), DAG);
15036   }
15037
15038   case Intrinsic::x86_sse42_pcmpistria128:
15039   case Intrinsic::x86_sse42_pcmpestria128:
15040   case Intrinsic::x86_sse42_pcmpistric128:
15041   case Intrinsic::x86_sse42_pcmpestric128:
15042   case Intrinsic::x86_sse42_pcmpistrio128:
15043   case Intrinsic::x86_sse42_pcmpestrio128:
15044   case Intrinsic::x86_sse42_pcmpistris128:
15045   case Intrinsic::x86_sse42_pcmpestris128:
15046   case Intrinsic::x86_sse42_pcmpistriz128:
15047   case Intrinsic::x86_sse42_pcmpestriz128: {
15048     unsigned Opcode;
15049     unsigned X86CC;
15050     switch (IntNo) {
15051     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15052     case Intrinsic::x86_sse42_pcmpistria128:
15053       Opcode = X86ISD::PCMPISTRI;
15054       X86CC = X86::COND_A;
15055       break;
15056     case Intrinsic::x86_sse42_pcmpestria128:
15057       Opcode = X86ISD::PCMPESTRI;
15058       X86CC = X86::COND_A;
15059       break;
15060     case Intrinsic::x86_sse42_pcmpistric128:
15061       Opcode = X86ISD::PCMPISTRI;
15062       X86CC = X86::COND_B;
15063       break;
15064     case Intrinsic::x86_sse42_pcmpestric128:
15065       Opcode = X86ISD::PCMPESTRI;
15066       X86CC = X86::COND_B;
15067       break;
15068     case Intrinsic::x86_sse42_pcmpistrio128:
15069       Opcode = X86ISD::PCMPISTRI;
15070       X86CC = X86::COND_O;
15071       break;
15072     case Intrinsic::x86_sse42_pcmpestrio128:
15073       Opcode = X86ISD::PCMPESTRI;
15074       X86CC = X86::COND_O;
15075       break;
15076     case Intrinsic::x86_sse42_pcmpistris128:
15077       Opcode = X86ISD::PCMPISTRI;
15078       X86CC = X86::COND_S;
15079       break;
15080     case Intrinsic::x86_sse42_pcmpestris128:
15081       Opcode = X86ISD::PCMPESTRI;
15082       X86CC = X86::COND_S;
15083       break;
15084     case Intrinsic::x86_sse42_pcmpistriz128:
15085       Opcode = X86ISD::PCMPISTRI;
15086       X86CC = X86::COND_E;
15087       break;
15088     case Intrinsic::x86_sse42_pcmpestriz128:
15089       Opcode = X86ISD::PCMPESTRI;
15090       X86CC = X86::COND_E;
15091       break;
15092     }
15093     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15094     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15095     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15096     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15097                                 DAG.getConstant(X86CC, MVT::i8),
15098                                 SDValue(PCMP.getNode(), 1));
15099     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15100   }
15101
15102   case Intrinsic::x86_sse42_pcmpistri128:
15103   case Intrinsic::x86_sse42_pcmpestri128: {
15104     unsigned Opcode;
15105     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15106       Opcode = X86ISD::PCMPISTRI;
15107     else
15108       Opcode = X86ISD::PCMPESTRI;
15109
15110     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15111     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15112     return DAG.getNode(Opcode, dl, VTs, NewOps);
15113   }
15114
15115   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
15116   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
15117   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
15118   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
15119   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
15120   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
15121   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
15122   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
15123   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
15124   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
15125   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
15126   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
15127     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
15128     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
15129       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
15130                                               dl, Op.getValueType(),
15131                                               Op.getOperand(1),
15132                                               Op.getOperand(2),
15133                                               Op.getOperand(3)),
15134                                   Op.getOperand(4), Op.getOperand(1), DAG);
15135     else
15136       return SDValue();
15137   }
15138
15139   case Intrinsic::x86_fma_vfmadd_ps:
15140   case Intrinsic::x86_fma_vfmadd_pd:
15141   case Intrinsic::x86_fma_vfmsub_ps:
15142   case Intrinsic::x86_fma_vfmsub_pd:
15143   case Intrinsic::x86_fma_vfnmadd_ps:
15144   case Intrinsic::x86_fma_vfnmadd_pd:
15145   case Intrinsic::x86_fma_vfnmsub_ps:
15146   case Intrinsic::x86_fma_vfnmsub_pd:
15147   case Intrinsic::x86_fma_vfmaddsub_ps:
15148   case Intrinsic::x86_fma_vfmaddsub_pd:
15149   case Intrinsic::x86_fma_vfmsubadd_ps:
15150   case Intrinsic::x86_fma_vfmsubadd_pd:
15151   case Intrinsic::x86_fma_vfmadd_ps_256:
15152   case Intrinsic::x86_fma_vfmadd_pd_256:
15153   case Intrinsic::x86_fma_vfmsub_ps_256:
15154   case Intrinsic::x86_fma_vfmsub_pd_256:
15155   case Intrinsic::x86_fma_vfnmadd_ps_256:
15156   case Intrinsic::x86_fma_vfnmadd_pd_256:
15157   case Intrinsic::x86_fma_vfnmsub_ps_256:
15158   case Intrinsic::x86_fma_vfnmsub_pd_256:
15159   case Intrinsic::x86_fma_vfmaddsub_ps_256:
15160   case Intrinsic::x86_fma_vfmaddsub_pd_256:
15161   case Intrinsic::x86_fma_vfmsubadd_ps_256:
15162   case Intrinsic::x86_fma_vfmsubadd_pd_256:
15163     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
15164                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
15165   }
15166 }
15167
15168 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15169                               SDValue Src, SDValue Mask, SDValue Base,
15170                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15171                               const X86Subtarget * Subtarget) {
15172   SDLoc dl(Op);
15173   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15174   assert(C && "Invalid scale type");
15175   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15176   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15177                              Index.getSimpleValueType().getVectorNumElements());
15178   SDValue MaskInReg;
15179   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15180   if (MaskC)
15181     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15182   else
15183     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15184   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15185   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15186   SDValue Segment = DAG.getRegister(0, MVT::i32);
15187   if (Src.getOpcode() == ISD::UNDEF)
15188     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15189   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15190   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15191   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15192   return DAG.getMergeValues(RetOps, dl);
15193 }
15194
15195 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15196                                SDValue Src, SDValue Mask, SDValue Base,
15197                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15198   SDLoc dl(Op);
15199   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15200   assert(C && "Invalid scale type");
15201   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15202   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15203   SDValue Segment = DAG.getRegister(0, MVT::i32);
15204   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15205                              Index.getSimpleValueType().getVectorNumElements());
15206   SDValue MaskInReg;
15207   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15208   if (MaskC)
15209     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15210   else
15211     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15212   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15213   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15214   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15215   return SDValue(Res, 1);
15216 }
15217
15218 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15219                                SDValue Mask, SDValue Base, SDValue Index,
15220                                SDValue ScaleOp, SDValue Chain) {
15221   SDLoc dl(Op);
15222   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15223   assert(C && "Invalid scale type");
15224   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15225   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15226   SDValue Segment = DAG.getRegister(0, MVT::i32);
15227   EVT MaskVT =
15228     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15229   SDValue MaskInReg;
15230   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15231   if (MaskC)
15232     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15233   else
15234     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15235   //SDVTList VTs = DAG.getVTList(MVT::Other);
15236   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15237   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15238   return SDValue(Res, 0);
15239 }
15240
15241 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15242 // read performance monitor counters (x86_rdpmc).
15243 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15244                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15245                               SmallVectorImpl<SDValue> &Results) {
15246   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15247   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15248   SDValue LO, HI;
15249
15250   // The ECX register is used to select the index of the performance counter
15251   // to read.
15252   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15253                                    N->getOperand(2));
15254   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15255
15256   // Reads the content of a 64-bit performance counter and returns it in the
15257   // registers EDX:EAX.
15258   if (Subtarget->is64Bit()) {
15259     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15260     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15261                             LO.getValue(2));
15262   } else {
15263     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15264     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15265                             LO.getValue(2));
15266   }
15267   Chain = HI.getValue(1);
15268
15269   if (Subtarget->is64Bit()) {
15270     // The EAX register is loaded with the low-order 32 bits. The EDX register
15271     // is loaded with the supported high-order bits of the counter.
15272     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15273                               DAG.getConstant(32, MVT::i8));
15274     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15275     Results.push_back(Chain);
15276     return;
15277   }
15278
15279   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15280   SDValue Ops[] = { LO, HI };
15281   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15282   Results.push_back(Pair);
15283   Results.push_back(Chain);
15284 }
15285
15286 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15287 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15288 // also used to custom lower READCYCLECOUNTER nodes.
15289 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15290                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15291                               SmallVectorImpl<SDValue> &Results) {
15292   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15293   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15294   SDValue LO, HI;
15295
15296   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15297   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15298   // and the EAX register is loaded with the low-order 32 bits.
15299   if (Subtarget->is64Bit()) {
15300     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15301     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15302                             LO.getValue(2));
15303   } else {
15304     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15305     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15306                             LO.getValue(2));
15307   }
15308   SDValue Chain = HI.getValue(1);
15309
15310   if (Opcode == X86ISD::RDTSCP_DAG) {
15311     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15312
15313     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15314     // the ECX register. Add 'ecx' explicitly to the chain.
15315     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15316                                      HI.getValue(2));
15317     // Explicitly store the content of ECX at the location passed in input
15318     // to the 'rdtscp' intrinsic.
15319     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15320                          MachinePointerInfo(), false, false, 0);
15321   }
15322
15323   if (Subtarget->is64Bit()) {
15324     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15325     // the EAX register is loaded with the low-order 32 bits.
15326     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15327                               DAG.getConstant(32, MVT::i8));
15328     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15329     Results.push_back(Chain);
15330     return;
15331   }
15332
15333   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15334   SDValue Ops[] = { LO, HI };
15335   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15336   Results.push_back(Pair);
15337   Results.push_back(Chain);
15338 }
15339
15340 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15341                                      SelectionDAG &DAG) {
15342   SmallVector<SDValue, 2> Results;
15343   SDLoc DL(Op);
15344   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15345                           Results);
15346   return DAG.getMergeValues(Results, DL);
15347 }
15348
15349 enum IntrinsicType {
15350   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
15351 };
15352
15353 struct IntrinsicData {
15354   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
15355     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
15356   IntrinsicType Type;
15357   unsigned      Opc0;
15358   unsigned      Opc1;
15359 };
15360
15361 std::map < unsigned, IntrinsicData> IntrMap;
15362 static void InitIntinsicsMap() {
15363   static bool Initialized = false;
15364   if (Initialized) 
15365     return;
15366   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
15367                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
15368   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
15369                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
15370   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
15371                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
15372   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
15373                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
15374   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
15375                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
15376   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
15377                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
15378   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
15379                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
15380   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
15381                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
15382   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
15383                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
15384
15385   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
15386                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
15387   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
15388                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
15389   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
15390                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
15391   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
15392                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
15393   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
15394                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
15395   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
15396                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
15397   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
15398                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
15399   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
15400                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
15401    
15402   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
15403                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
15404                                                         X86::VGATHERPF1QPSm)));
15405   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
15406                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
15407                                                         X86::VGATHERPF1QPDm)));
15408   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
15409                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
15410                                                         X86::VGATHERPF1DPDm)));
15411   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
15412                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
15413                                                         X86::VGATHERPF1DPSm)));
15414   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
15415                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
15416                                                         X86::VSCATTERPF1QPSm)));
15417   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
15418                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
15419                                                         X86::VSCATTERPF1QPDm)));
15420   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
15421                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
15422                                                         X86::VSCATTERPF1DPDm)));
15423   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
15424                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
15425                                                         X86::VSCATTERPF1DPSm)));
15426   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
15427                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15428   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
15429                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15430   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
15431                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15432   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
15433                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15434   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
15435                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15436   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
15437                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15438   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
15439                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
15440   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
15441                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
15442   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
15443                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
15444   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
15445                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
15446   Initialized = true;
15447 }
15448
15449 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15450                                       SelectionDAG &DAG) {
15451   InitIntinsicsMap();
15452   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15453   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
15454   if (itr == IntrMap.end())
15455     return SDValue();
15456
15457   SDLoc dl(Op);
15458   IntrinsicData Intr = itr->second;
15459   switch(Intr.Type) {
15460   case RDSEED:
15461   case RDRAND: {
15462     // Emit the node with the right value type.
15463     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15464     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
15465
15466     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15467     // Otherwise return the value from Rand, which is always 0, casted to i32.
15468     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15469                       DAG.getConstant(1, Op->getValueType(1)),
15470                       DAG.getConstant(X86::COND_B, MVT::i32),
15471                       SDValue(Result.getNode(), 1) };
15472     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15473                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15474                                   Ops);
15475
15476     // Return { result, isValid, chain }.
15477     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15478                        SDValue(Result.getNode(), 2));
15479   }
15480   case GATHER: {
15481   //gather(v1, mask, index, base, scale);
15482     SDValue Chain = Op.getOperand(0);
15483     SDValue Src   = Op.getOperand(2);
15484     SDValue Base  = Op.getOperand(3);
15485     SDValue Index = Op.getOperand(4);
15486     SDValue Mask  = Op.getOperand(5);
15487     SDValue Scale = Op.getOperand(6);
15488     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15489                           Subtarget);
15490   }
15491   case SCATTER: {
15492   //scatter(base, mask, index, v1, scale);
15493     SDValue Chain = Op.getOperand(0);
15494     SDValue Base  = Op.getOperand(2);
15495     SDValue Mask  = Op.getOperand(3);
15496     SDValue Index = Op.getOperand(4);
15497     SDValue Src   = Op.getOperand(5);
15498     SDValue Scale = Op.getOperand(6);
15499     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15500   }
15501   case PREFETCH: {
15502     SDValue Hint = Op.getOperand(6);
15503     unsigned HintVal;
15504     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15505         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15506       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15507     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
15508     SDValue Chain = Op.getOperand(0);
15509     SDValue Mask  = Op.getOperand(2);
15510     SDValue Index = Op.getOperand(3);
15511     SDValue Base  = Op.getOperand(4);
15512     SDValue Scale = Op.getOperand(5);
15513     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15514   }
15515   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15516   case RDTSC: {
15517     SmallVector<SDValue, 2> Results;
15518     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
15519     return DAG.getMergeValues(Results, dl);
15520   }
15521   // Read Performance Monitoring Counters.
15522   case RDPMC: {
15523     SmallVector<SDValue, 2> Results;
15524     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15525     return DAG.getMergeValues(Results, dl);
15526   }
15527   // XTEST intrinsics.
15528   case XTEST: {
15529     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15530     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
15531     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15532                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15533                                 InTrans);
15534     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15535     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15536                        Ret, SDValue(InTrans.getNode(), 1));
15537   }
15538   }
15539   llvm_unreachable("Unknown Intrinsic Type");
15540 }
15541
15542 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15543                                            SelectionDAG &DAG) const {
15544   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15545   MFI->setReturnAddressIsTaken(true);
15546
15547   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15548     return SDValue();
15549
15550   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15551   SDLoc dl(Op);
15552   EVT PtrVT = getPointerTy();
15553
15554   if (Depth > 0) {
15555     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15556     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15557         DAG.getSubtarget().getRegisterInfo());
15558     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15559     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15560                        DAG.getNode(ISD::ADD, dl, PtrVT,
15561                                    FrameAddr, Offset),
15562                        MachinePointerInfo(), false, false, false, 0);
15563   }
15564
15565   // Just load the return address.
15566   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15567   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15568                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15569 }
15570
15571 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15572   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15573   MFI->setFrameAddressIsTaken(true);
15574
15575   EVT VT = Op.getValueType();
15576   SDLoc dl(Op);  // FIXME probably not meaningful
15577   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15578   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15579       DAG.getSubtarget().getRegisterInfo());
15580   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15581   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15582           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15583          "Invalid Frame Register!");
15584   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15585   while (Depth--)
15586     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15587                             MachinePointerInfo(),
15588                             false, false, false, 0);
15589   return FrameAddr;
15590 }
15591
15592 // FIXME? Maybe this could be a TableGen attribute on some registers and
15593 // this table could be generated automatically from RegInfo.
15594 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15595                                               EVT VT) const {
15596   unsigned Reg = StringSwitch<unsigned>(RegName)
15597                        .Case("esp", X86::ESP)
15598                        .Case("rsp", X86::RSP)
15599                        .Default(0);
15600   if (Reg)
15601     return Reg;
15602   report_fatal_error("Invalid register name global variable");
15603 }
15604
15605 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15606                                                      SelectionDAG &DAG) const {
15607   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15608       DAG.getSubtarget().getRegisterInfo());
15609   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15610 }
15611
15612 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15613   SDValue Chain     = Op.getOperand(0);
15614   SDValue Offset    = Op.getOperand(1);
15615   SDValue Handler   = Op.getOperand(2);
15616   SDLoc dl      (Op);
15617
15618   EVT PtrVT = getPointerTy();
15619   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15620       DAG.getSubtarget().getRegisterInfo());
15621   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15622   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15623           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15624          "Invalid Frame Register!");
15625   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15626   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15627
15628   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15629                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15630   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15631   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15632                        false, false, 0);
15633   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15634
15635   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15636                      DAG.getRegister(StoreAddrReg, PtrVT));
15637 }
15638
15639 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15640                                                SelectionDAG &DAG) const {
15641   SDLoc DL(Op);
15642   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15643                      DAG.getVTList(MVT::i32, MVT::Other),
15644                      Op.getOperand(0), Op.getOperand(1));
15645 }
15646
15647 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15648                                                 SelectionDAG &DAG) const {
15649   SDLoc DL(Op);
15650   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15651                      Op.getOperand(0), Op.getOperand(1));
15652 }
15653
15654 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15655   return Op.getOperand(0);
15656 }
15657
15658 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15659                                                 SelectionDAG &DAG) const {
15660   SDValue Root = Op.getOperand(0);
15661   SDValue Trmp = Op.getOperand(1); // trampoline
15662   SDValue FPtr = Op.getOperand(2); // nested function
15663   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15664   SDLoc dl (Op);
15665
15666   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15667   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15668
15669   if (Subtarget->is64Bit()) {
15670     SDValue OutChains[6];
15671
15672     // Large code-model.
15673     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15674     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15675
15676     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15677     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15678
15679     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15680
15681     // Load the pointer to the nested function into R11.
15682     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15683     SDValue Addr = Trmp;
15684     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15685                                 Addr, MachinePointerInfo(TrmpAddr),
15686                                 false, false, 0);
15687
15688     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15689                        DAG.getConstant(2, MVT::i64));
15690     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15691                                 MachinePointerInfo(TrmpAddr, 2),
15692                                 false, false, 2);
15693
15694     // Load the 'nest' parameter value into R10.
15695     // R10 is specified in X86CallingConv.td
15696     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15697     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15698                        DAG.getConstant(10, MVT::i64));
15699     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15700                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15701                                 false, false, 0);
15702
15703     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15704                        DAG.getConstant(12, MVT::i64));
15705     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15706                                 MachinePointerInfo(TrmpAddr, 12),
15707                                 false, false, 2);
15708
15709     // Jump to the nested function.
15710     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15711     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15712                        DAG.getConstant(20, MVT::i64));
15713     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15714                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15715                                 false, false, 0);
15716
15717     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15718     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15719                        DAG.getConstant(22, MVT::i64));
15720     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15721                                 MachinePointerInfo(TrmpAddr, 22),
15722                                 false, false, 0);
15723
15724     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15725   } else {
15726     const Function *Func =
15727       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15728     CallingConv::ID CC = Func->getCallingConv();
15729     unsigned NestReg;
15730
15731     switch (CC) {
15732     default:
15733       llvm_unreachable("Unsupported calling convention");
15734     case CallingConv::C:
15735     case CallingConv::X86_StdCall: {
15736       // Pass 'nest' parameter in ECX.
15737       // Must be kept in sync with X86CallingConv.td
15738       NestReg = X86::ECX;
15739
15740       // Check that ECX wasn't needed by an 'inreg' parameter.
15741       FunctionType *FTy = Func->getFunctionType();
15742       const AttributeSet &Attrs = Func->getAttributes();
15743
15744       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15745         unsigned InRegCount = 0;
15746         unsigned Idx = 1;
15747
15748         for (FunctionType::param_iterator I = FTy->param_begin(),
15749              E = FTy->param_end(); I != E; ++I, ++Idx)
15750           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15751             // FIXME: should only count parameters that are lowered to integers.
15752             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15753
15754         if (InRegCount > 2) {
15755           report_fatal_error("Nest register in use - reduce number of inreg"
15756                              " parameters!");
15757         }
15758       }
15759       break;
15760     }
15761     case CallingConv::X86_FastCall:
15762     case CallingConv::X86_ThisCall:
15763     case CallingConv::Fast:
15764       // Pass 'nest' parameter in EAX.
15765       // Must be kept in sync with X86CallingConv.td
15766       NestReg = X86::EAX;
15767       break;
15768     }
15769
15770     SDValue OutChains[4];
15771     SDValue Addr, Disp;
15772
15773     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15774                        DAG.getConstant(10, MVT::i32));
15775     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15776
15777     // This is storing the opcode for MOV32ri.
15778     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15779     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15780     OutChains[0] = DAG.getStore(Root, dl,
15781                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15782                                 Trmp, MachinePointerInfo(TrmpAddr),
15783                                 false, false, 0);
15784
15785     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15786                        DAG.getConstant(1, MVT::i32));
15787     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15788                                 MachinePointerInfo(TrmpAddr, 1),
15789                                 false, false, 1);
15790
15791     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15792     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15793                        DAG.getConstant(5, MVT::i32));
15794     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15795                                 MachinePointerInfo(TrmpAddr, 5),
15796                                 false, false, 1);
15797
15798     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15799                        DAG.getConstant(6, MVT::i32));
15800     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15801                                 MachinePointerInfo(TrmpAddr, 6),
15802                                 false, false, 1);
15803
15804     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15805   }
15806 }
15807
15808 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15809                                             SelectionDAG &DAG) const {
15810   /*
15811    The rounding mode is in bits 11:10 of FPSR, and has the following
15812    settings:
15813      00 Round to nearest
15814      01 Round to -inf
15815      10 Round to +inf
15816      11 Round to 0
15817
15818   FLT_ROUNDS, on the other hand, expects the following:
15819     -1 Undefined
15820      0 Round to 0
15821      1 Round to nearest
15822      2 Round to +inf
15823      3 Round to -inf
15824
15825   To perform the conversion, we do:
15826     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15827   */
15828
15829   MachineFunction &MF = DAG.getMachineFunction();
15830   const TargetMachine &TM = MF.getTarget();
15831   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15832   unsigned StackAlignment = TFI.getStackAlignment();
15833   MVT VT = Op.getSimpleValueType();
15834   SDLoc DL(Op);
15835
15836   // Save FP Control Word to stack slot
15837   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15838   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15839
15840   MachineMemOperand *MMO =
15841    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15842                            MachineMemOperand::MOStore, 2, 2);
15843
15844   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15845   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15846                                           DAG.getVTList(MVT::Other),
15847                                           Ops, MVT::i16, MMO);
15848
15849   // Load FP Control Word from stack slot
15850   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15851                             MachinePointerInfo(), false, false, false, 0);
15852
15853   // Transform as necessary
15854   SDValue CWD1 =
15855     DAG.getNode(ISD::SRL, DL, MVT::i16,
15856                 DAG.getNode(ISD::AND, DL, MVT::i16,
15857                             CWD, DAG.getConstant(0x800, MVT::i16)),
15858                 DAG.getConstant(11, MVT::i8));
15859   SDValue CWD2 =
15860     DAG.getNode(ISD::SRL, DL, MVT::i16,
15861                 DAG.getNode(ISD::AND, DL, MVT::i16,
15862                             CWD, DAG.getConstant(0x400, MVT::i16)),
15863                 DAG.getConstant(9, MVT::i8));
15864
15865   SDValue RetVal =
15866     DAG.getNode(ISD::AND, DL, MVT::i16,
15867                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15868                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15869                             DAG.getConstant(1, MVT::i16)),
15870                 DAG.getConstant(3, MVT::i16));
15871
15872   return DAG.getNode((VT.getSizeInBits() < 16 ?
15873                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15874 }
15875
15876 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15877   MVT VT = Op.getSimpleValueType();
15878   EVT OpVT = VT;
15879   unsigned NumBits = VT.getSizeInBits();
15880   SDLoc dl(Op);
15881
15882   Op = Op.getOperand(0);
15883   if (VT == MVT::i8) {
15884     // Zero extend to i32 since there is not an i8 bsr.
15885     OpVT = MVT::i32;
15886     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15887   }
15888
15889   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15890   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15891   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15892
15893   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15894   SDValue Ops[] = {
15895     Op,
15896     DAG.getConstant(NumBits+NumBits-1, OpVT),
15897     DAG.getConstant(X86::COND_E, MVT::i8),
15898     Op.getValue(1)
15899   };
15900   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15901
15902   // Finally xor with NumBits-1.
15903   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15904
15905   if (VT == MVT::i8)
15906     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15907   return Op;
15908 }
15909
15910 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15911   MVT VT = Op.getSimpleValueType();
15912   EVT OpVT = VT;
15913   unsigned NumBits = VT.getSizeInBits();
15914   SDLoc dl(Op);
15915
15916   Op = Op.getOperand(0);
15917   if (VT == MVT::i8) {
15918     // Zero extend to i32 since there is not an i8 bsr.
15919     OpVT = MVT::i32;
15920     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15921   }
15922
15923   // Issue a bsr (scan bits in reverse).
15924   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15925   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15926
15927   // And xor with NumBits-1.
15928   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15929
15930   if (VT == MVT::i8)
15931     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15932   return Op;
15933 }
15934
15935 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15936   MVT VT = Op.getSimpleValueType();
15937   unsigned NumBits = VT.getSizeInBits();
15938   SDLoc dl(Op);
15939   Op = Op.getOperand(0);
15940
15941   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15942   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15943   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15944
15945   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15946   SDValue Ops[] = {
15947     Op,
15948     DAG.getConstant(NumBits, VT),
15949     DAG.getConstant(X86::COND_E, MVT::i8),
15950     Op.getValue(1)
15951   };
15952   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15953 }
15954
15955 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15956 // ones, and then concatenate the result back.
15957 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15958   MVT VT = Op.getSimpleValueType();
15959
15960   assert(VT.is256BitVector() && VT.isInteger() &&
15961          "Unsupported value type for operation");
15962
15963   unsigned NumElems = VT.getVectorNumElements();
15964   SDLoc dl(Op);
15965
15966   // Extract the LHS vectors
15967   SDValue LHS = Op.getOperand(0);
15968   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15969   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15970
15971   // Extract the RHS vectors
15972   SDValue RHS = Op.getOperand(1);
15973   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15974   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15975
15976   MVT EltVT = VT.getVectorElementType();
15977   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15978
15979   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15980                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15981                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15982 }
15983
15984 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15985   assert(Op.getSimpleValueType().is256BitVector() &&
15986          Op.getSimpleValueType().isInteger() &&
15987          "Only handle AVX 256-bit vector integer operation");
15988   return Lower256IntArith(Op, DAG);
15989 }
15990
15991 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15992   assert(Op.getSimpleValueType().is256BitVector() &&
15993          Op.getSimpleValueType().isInteger() &&
15994          "Only handle AVX 256-bit vector integer operation");
15995   return Lower256IntArith(Op, DAG);
15996 }
15997
15998 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15999                         SelectionDAG &DAG) {
16000   SDLoc dl(Op);
16001   MVT VT = Op.getSimpleValueType();
16002
16003   // Decompose 256-bit ops into smaller 128-bit ops.
16004   if (VT.is256BitVector() && !Subtarget->hasInt256())
16005     return Lower256IntArith(Op, DAG);
16006
16007   SDValue A = Op.getOperand(0);
16008   SDValue B = Op.getOperand(1);
16009
16010   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16011   if (VT == MVT::v4i32) {
16012     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16013            "Should not custom lower when pmuldq is available!");
16014
16015     // Extract the odd parts.
16016     static const int UnpackMask[] = { 1, -1, 3, -1 };
16017     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16018     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16019
16020     // Multiply the even parts.
16021     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16022     // Now multiply odd parts.
16023     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16024
16025     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16026     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16027
16028     // Merge the two vectors back together with a shuffle. This expands into 2
16029     // shuffles.
16030     static const int ShufMask[] = { 0, 4, 2, 6 };
16031     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16032   }
16033
16034   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16035          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16036
16037   //  Ahi = psrlqi(a, 32);
16038   //  Bhi = psrlqi(b, 32);
16039   //
16040   //  AloBlo = pmuludq(a, b);
16041   //  AloBhi = pmuludq(a, Bhi);
16042   //  AhiBlo = pmuludq(Ahi, b);
16043
16044   //  AloBhi = psllqi(AloBhi, 32);
16045   //  AhiBlo = psllqi(AhiBlo, 32);
16046   //  return AloBlo + AloBhi + AhiBlo;
16047
16048   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16049   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16050
16051   // Bit cast to 32-bit vectors for MULUDQ
16052   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16053                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16054   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16055   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16056   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16057   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16058
16059   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16060   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16061   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16062
16063   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16064   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16065
16066   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16067   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16068 }
16069
16070 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16071   assert(Subtarget->isTargetWin64() && "Unexpected target");
16072   EVT VT = Op.getValueType();
16073   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16074          "Unexpected return type for lowering");
16075
16076   RTLIB::Libcall LC;
16077   bool isSigned;
16078   switch (Op->getOpcode()) {
16079   default: llvm_unreachable("Unexpected request for libcall!");
16080   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16081   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16082   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16083   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16084   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16085   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16086   }
16087
16088   SDLoc dl(Op);
16089   SDValue InChain = DAG.getEntryNode();
16090
16091   TargetLowering::ArgListTy Args;
16092   TargetLowering::ArgListEntry Entry;
16093   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16094     EVT ArgVT = Op->getOperand(i).getValueType();
16095     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16096            "Unexpected argument type for lowering");
16097     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16098     Entry.Node = StackPtr;
16099     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16100                            false, false, 16);
16101     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16102     Entry.Ty = PointerType::get(ArgTy,0);
16103     Entry.isSExt = false;
16104     Entry.isZExt = false;
16105     Args.push_back(Entry);
16106   }
16107
16108   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16109                                          getPointerTy());
16110
16111   TargetLowering::CallLoweringInfo CLI(DAG);
16112   CLI.setDebugLoc(dl).setChain(InChain)
16113     .setCallee(getLibcallCallingConv(LC),
16114                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16115                Callee, std::move(Args), 0)
16116     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16117
16118   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16119   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16120 }
16121
16122 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16123                              SelectionDAG &DAG) {
16124   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16125   EVT VT = Op0.getValueType();
16126   SDLoc dl(Op);
16127
16128   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16129          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16130
16131   // PMULxD operations multiply each even value (starting at 0) of LHS with
16132   // the related value of RHS and produce a widen result.
16133   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16134   // => <2 x i64> <ae|cg>
16135   //
16136   // In other word, to have all the results, we need to perform two PMULxD:
16137   // 1. one with the even values.
16138   // 2. one with the odd values.
16139   // To achieve #2, with need to place the odd values at an even position.
16140   //
16141   // Place the odd value at an even position (basically, shift all values 1
16142   // step to the left):
16143   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16144   // <a|b|c|d> => <b|undef|d|undef>
16145   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16146   // <e|f|g|h> => <f|undef|h|undef>
16147   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16148
16149   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16150   // ints.
16151   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16152   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16153   unsigned Opcode =
16154       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16155   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16156   // => <2 x i64> <ae|cg>
16157   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16158                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16159   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16160   // => <2 x i64> <bf|dh>
16161   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16162                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16163
16164   // Shuffle it back into the right order.
16165   SDValue Highs, Lows;
16166   if (VT == MVT::v8i32) {
16167     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16168     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16169     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16170     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16171   } else {
16172     const int HighMask[] = {1, 5, 3, 7};
16173     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16174     const int LowMask[] = {0, 4, 2, 6};
16175     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16176   }
16177
16178   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16179   // unsigned multiply.
16180   if (IsSigned && !Subtarget->hasSSE41()) {
16181     SDValue ShAmt =
16182         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16183     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16184                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16185     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16186                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16187
16188     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16189     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16190   }
16191
16192   // The first result of MUL_LOHI is actually the low value, followed by the
16193   // high value.
16194   SDValue Ops[] = {Lows, Highs};
16195   return DAG.getMergeValues(Ops, dl);
16196 }
16197
16198 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16199                                          const X86Subtarget *Subtarget) {
16200   MVT VT = Op.getSimpleValueType();
16201   SDLoc dl(Op);
16202   SDValue R = Op.getOperand(0);
16203   SDValue Amt = Op.getOperand(1);
16204
16205   // Optimize shl/srl/sra with constant shift amount.
16206   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16207     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16208       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16209
16210       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16211           (Subtarget->hasInt256() &&
16212            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16213           (Subtarget->hasAVX512() &&
16214            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16215         if (Op.getOpcode() == ISD::SHL)
16216           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16217                                             DAG);
16218         if (Op.getOpcode() == ISD::SRL)
16219           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16220                                             DAG);
16221         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16222           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16223                                             DAG);
16224       }
16225
16226       if (VT == MVT::v16i8) {
16227         if (Op.getOpcode() == ISD::SHL) {
16228           // Make a large shift.
16229           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16230                                                    MVT::v8i16, R, ShiftAmt,
16231                                                    DAG);
16232           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16233           // Zero out the rightmost bits.
16234           SmallVector<SDValue, 16> V(16,
16235                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
16236                                                      MVT::i8));
16237           return DAG.getNode(ISD::AND, dl, VT, SHL,
16238                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16239         }
16240         if (Op.getOpcode() == ISD::SRL) {
16241           // Make a large shift.
16242           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16243                                                    MVT::v8i16, R, ShiftAmt,
16244                                                    DAG);
16245           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16246           // Zero out the leftmost bits.
16247           SmallVector<SDValue, 16> V(16,
16248                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16249                                                      MVT::i8));
16250           return DAG.getNode(ISD::AND, dl, VT, SRL,
16251                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16252         }
16253         if (Op.getOpcode() == ISD::SRA) {
16254           if (ShiftAmt == 7) {
16255             // R s>> 7  ===  R s< 0
16256             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16257             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16258           }
16259
16260           // R s>> a === ((R u>> a) ^ m) - m
16261           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16262           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
16263                                                          MVT::i8));
16264           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16265           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16266           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16267           return Res;
16268         }
16269         llvm_unreachable("Unknown shift opcode.");
16270       }
16271
16272       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
16273         if (Op.getOpcode() == ISD::SHL) {
16274           // Make a large shift.
16275           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16276                                                    MVT::v16i16, R, ShiftAmt,
16277                                                    DAG);
16278           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16279           // Zero out the rightmost bits.
16280           SmallVector<SDValue, 32> V(32,
16281                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
16282                                                      MVT::i8));
16283           return DAG.getNode(ISD::AND, dl, VT, SHL,
16284                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16285         }
16286         if (Op.getOpcode() == ISD::SRL) {
16287           // Make a large shift.
16288           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16289                                                    MVT::v16i16, R, ShiftAmt,
16290                                                    DAG);
16291           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16292           // Zero out the leftmost bits.
16293           SmallVector<SDValue, 32> V(32,
16294                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16295                                                      MVT::i8));
16296           return DAG.getNode(ISD::AND, dl, VT, SRL,
16297                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16298         }
16299         if (Op.getOpcode() == ISD::SRA) {
16300           if (ShiftAmt == 7) {
16301             // R s>> 7  ===  R s< 0
16302             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16303             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16304           }
16305
16306           // R s>> a === ((R u>> a) ^ m) - m
16307           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16308           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
16309                                                          MVT::i8));
16310           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16311           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16312           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16313           return Res;
16314         }
16315         llvm_unreachable("Unknown shift opcode.");
16316       }
16317     }
16318   }
16319
16320   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16321   if (!Subtarget->is64Bit() &&
16322       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16323       Amt.getOpcode() == ISD::BITCAST &&
16324       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16325     Amt = Amt.getOperand(0);
16326     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16327                      VT.getVectorNumElements();
16328     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16329     uint64_t ShiftAmt = 0;
16330     for (unsigned i = 0; i != Ratio; ++i) {
16331       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16332       if (!C)
16333         return SDValue();
16334       // 6 == Log2(64)
16335       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16336     }
16337     // Check remaining shift amounts.
16338     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16339       uint64_t ShAmt = 0;
16340       for (unsigned j = 0; j != Ratio; ++j) {
16341         ConstantSDNode *C =
16342           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16343         if (!C)
16344           return SDValue();
16345         // 6 == Log2(64)
16346         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16347       }
16348       if (ShAmt != ShiftAmt)
16349         return SDValue();
16350     }
16351     switch (Op.getOpcode()) {
16352     default:
16353       llvm_unreachable("Unknown shift opcode!");
16354     case ISD::SHL:
16355       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16356                                         DAG);
16357     case ISD::SRL:
16358       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16359                                         DAG);
16360     case ISD::SRA:
16361       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16362                                         DAG);
16363     }
16364   }
16365
16366   return SDValue();
16367 }
16368
16369 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16370                                         const X86Subtarget* Subtarget) {
16371   MVT VT = Op.getSimpleValueType();
16372   SDLoc dl(Op);
16373   SDValue R = Op.getOperand(0);
16374   SDValue Amt = Op.getOperand(1);
16375
16376   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16377       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16378       (Subtarget->hasInt256() &&
16379        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16380         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16381        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16382     SDValue BaseShAmt;
16383     EVT EltVT = VT.getVectorElementType();
16384
16385     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16386       unsigned NumElts = VT.getVectorNumElements();
16387       unsigned i, j;
16388       for (i = 0; i != NumElts; ++i) {
16389         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
16390           continue;
16391         break;
16392       }
16393       for (j = i; j != NumElts; ++j) {
16394         SDValue Arg = Amt.getOperand(j);
16395         if (Arg.getOpcode() == ISD::UNDEF) continue;
16396         if (Arg != Amt.getOperand(i))
16397           break;
16398       }
16399       if (i != NumElts && j == NumElts)
16400         BaseShAmt = Amt.getOperand(i);
16401     } else {
16402       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16403         Amt = Amt.getOperand(0);
16404       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
16405                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
16406         SDValue InVec = Amt.getOperand(0);
16407         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16408           unsigned NumElts = InVec.getValueType().getVectorNumElements();
16409           unsigned i = 0;
16410           for (; i != NumElts; ++i) {
16411             SDValue Arg = InVec.getOperand(i);
16412             if (Arg.getOpcode() == ISD::UNDEF) continue;
16413             BaseShAmt = Arg;
16414             break;
16415           }
16416         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16417            if (ConstantSDNode *C =
16418                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16419              unsigned SplatIdx =
16420                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16421              if (C->getZExtValue() == SplatIdx)
16422                BaseShAmt = InVec.getOperand(1);
16423            }
16424         }
16425         if (!BaseShAmt.getNode())
16426           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16427                                   DAG.getIntPtrConstant(0));
16428       }
16429     }
16430
16431     if (BaseShAmt.getNode()) {
16432       if (EltVT.bitsGT(MVT::i32))
16433         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16434       else if (EltVT.bitsLT(MVT::i32))
16435         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16436
16437       switch (Op.getOpcode()) {
16438       default:
16439         llvm_unreachable("Unknown shift opcode!");
16440       case ISD::SHL:
16441         switch (VT.SimpleTy) {
16442         default: return SDValue();
16443         case MVT::v2i64:
16444         case MVT::v4i32:
16445         case MVT::v8i16:
16446         case MVT::v4i64:
16447         case MVT::v8i32:
16448         case MVT::v16i16:
16449         case MVT::v16i32:
16450         case MVT::v8i64:
16451           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16452         }
16453       case ISD::SRA:
16454         switch (VT.SimpleTy) {
16455         default: return SDValue();
16456         case MVT::v4i32:
16457         case MVT::v8i16:
16458         case MVT::v8i32:
16459         case MVT::v16i16:
16460         case MVT::v16i32:
16461         case MVT::v8i64:
16462           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16463         }
16464       case ISD::SRL:
16465         switch (VT.SimpleTy) {
16466         default: return SDValue();
16467         case MVT::v2i64:
16468         case MVT::v4i32:
16469         case MVT::v8i16:
16470         case MVT::v4i64:
16471         case MVT::v8i32:
16472         case MVT::v16i16:
16473         case MVT::v16i32:
16474         case MVT::v8i64:
16475           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16476         }
16477       }
16478     }
16479   }
16480
16481   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16482   if (!Subtarget->is64Bit() &&
16483       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16484       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16485       Amt.getOpcode() == ISD::BITCAST &&
16486       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16487     Amt = Amt.getOperand(0);
16488     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16489                      VT.getVectorNumElements();
16490     std::vector<SDValue> Vals(Ratio);
16491     for (unsigned i = 0; i != Ratio; ++i)
16492       Vals[i] = Amt.getOperand(i);
16493     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16494       for (unsigned j = 0; j != Ratio; ++j)
16495         if (Vals[j] != Amt.getOperand(i + j))
16496           return SDValue();
16497     }
16498     switch (Op.getOpcode()) {
16499     default:
16500       llvm_unreachable("Unknown shift opcode!");
16501     case ISD::SHL:
16502       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16503     case ISD::SRL:
16504       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16505     case ISD::SRA:
16506       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16507     }
16508   }
16509
16510   return SDValue();
16511 }
16512
16513 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16514                           SelectionDAG &DAG) {
16515   MVT VT = Op.getSimpleValueType();
16516   SDLoc dl(Op);
16517   SDValue R = Op.getOperand(0);
16518   SDValue Amt = Op.getOperand(1);
16519   SDValue V;
16520
16521   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16522   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16523
16524   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16525   if (V.getNode())
16526     return V;
16527
16528   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16529   if (V.getNode())
16530       return V;
16531
16532   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16533     return Op;
16534   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16535   if (Subtarget->hasInt256()) {
16536     if (Op.getOpcode() == ISD::SRL &&
16537         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16538          VT == MVT::v4i64 || VT == MVT::v8i32))
16539       return Op;
16540     if (Op.getOpcode() == ISD::SHL &&
16541         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16542          VT == MVT::v4i64 || VT == MVT::v8i32))
16543       return Op;
16544     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16545       return Op;
16546   }
16547
16548   // If possible, lower this packed shift into a vector multiply instead of
16549   // expanding it into a sequence of scalar shifts.
16550   // Do this only if the vector shift count is a constant build_vector.
16551   if (Op.getOpcode() == ISD::SHL && 
16552       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16553        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16554       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16555     SmallVector<SDValue, 8> Elts;
16556     EVT SVT = VT.getScalarType();
16557     unsigned SVTBits = SVT.getSizeInBits();
16558     const APInt &One = APInt(SVTBits, 1);
16559     unsigned NumElems = VT.getVectorNumElements();
16560
16561     for (unsigned i=0; i !=NumElems; ++i) {
16562       SDValue Op = Amt->getOperand(i);
16563       if (Op->getOpcode() == ISD::UNDEF) {
16564         Elts.push_back(Op);
16565         continue;
16566       }
16567
16568       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16569       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16570       uint64_t ShAmt = C.getZExtValue();
16571       if (ShAmt >= SVTBits) {
16572         Elts.push_back(DAG.getUNDEF(SVT));
16573         continue;
16574       }
16575       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16576     }
16577     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16578     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16579   }
16580
16581   // Lower SHL with variable shift amount.
16582   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16583     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16584
16585     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16586     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16587     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16588     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16589   }
16590
16591   // If possible, lower this shift as a sequence of two shifts by
16592   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16593   // Example:
16594   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16595   //
16596   // Could be rewritten as:
16597   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16598   //
16599   // The advantage is that the two shifts from the example would be
16600   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16601   // the vector shift into four scalar shifts plus four pairs of vector
16602   // insert/extract.
16603   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16604       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16605     unsigned TargetOpcode = X86ISD::MOVSS;
16606     bool CanBeSimplified;
16607     // The splat value for the first packed shift (the 'X' from the example).
16608     SDValue Amt1 = Amt->getOperand(0);
16609     // The splat value for the second packed shift (the 'Y' from the example).
16610     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16611                                         Amt->getOperand(2);
16612
16613     // See if it is possible to replace this node with a sequence of
16614     // two shifts followed by a MOVSS/MOVSD
16615     if (VT == MVT::v4i32) {
16616       // Check if it is legal to use a MOVSS.
16617       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16618                         Amt2 == Amt->getOperand(3);
16619       if (!CanBeSimplified) {
16620         // Otherwise, check if we can still simplify this node using a MOVSD.
16621         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16622                           Amt->getOperand(2) == Amt->getOperand(3);
16623         TargetOpcode = X86ISD::MOVSD;
16624         Amt2 = Amt->getOperand(2);
16625       }
16626     } else {
16627       // Do similar checks for the case where the machine value type
16628       // is MVT::v8i16.
16629       CanBeSimplified = Amt1 == Amt->getOperand(1);
16630       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16631         CanBeSimplified = Amt2 == Amt->getOperand(i);
16632
16633       if (!CanBeSimplified) {
16634         TargetOpcode = X86ISD::MOVSD;
16635         CanBeSimplified = true;
16636         Amt2 = Amt->getOperand(4);
16637         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16638           CanBeSimplified = Amt1 == Amt->getOperand(i);
16639         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16640           CanBeSimplified = Amt2 == Amt->getOperand(j);
16641       }
16642     }
16643     
16644     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16645         isa<ConstantSDNode>(Amt2)) {
16646       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16647       EVT CastVT = MVT::v4i32;
16648       SDValue Splat1 = 
16649         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16650       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16651       SDValue Splat2 = 
16652         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16653       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16654       if (TargetOpcode == X86ISD::MOVSD)
16655         CastVT = MVT::v2i64;
16656       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16657       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16658       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16659                                             BitCast1, DAG);
16660       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16661     }
16662   }
16663
16664   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16665     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16666
16667     // a = a << 5;
16668     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16669     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16670
16671     // Turn 'a' into a mask suitable for VSELECT
16672     SDValue VSelM = DAG.getConstant(0x80, VT);
16673     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16674     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16675
16676     SDValue CM1 = DAG.getConstant(0x0f, VT);
16677     SDValue CM2 = DAG.getConstant(0x3f, VT);
16678
16679     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16680     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16681     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16682     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16683     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16684
16685     // a += a
16686     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16687     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16688     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16689
16690     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16691     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16692     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16693     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16694     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16695
16696     // a += a
16697     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16698     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16699     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16700
16701     // return VSELECT(r, r+r, a);
16702     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16703                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16704     return R;
16705   }
16706
16707   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16708   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16709   // solution better.
16710   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16711     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16712     unsigned ExtOpc =
16713         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16714     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16715     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16716     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16717                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16718     }
16719
16720   // Decompose 256-bit shifts into smaller 128-bit shifts.
16721   if (VT.is256BitVector()) {
16722     unsigned NumElems = VT.getVectorNumElements();
16723     MVT EltVT = VT.getVectorElementType();
16724     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16725
16726     // Extract the two vectors
16727     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16728     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16729
16730     // Recreate the shift amount vectors
16731     SDValue Amt1, Amt2;
16732     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16733       // Constant shift amount
16734       SmallVector<SDValue, 4> Amt1Csts;
16735       SmallVector<SDValue, 4> Amt2Csts;
16736       for (unsigned i = 0; i != NumElems/2; ++i)
16737         Amt1Csts.push_back(Amt->getOperand(i));
16738       for (unsigned i = NumElems/2; i != NumElems; ++i)
16739         Amt2Csts.push_back(Amt->getOperand(i));
16740
16741       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16742       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16743     } else {
16744       // Variable shift amount
16745       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16746       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16747     }
16748
16749     // Issue new vector shifts for the smaller types
16750     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16751     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16752
16753     // Concatenate the result back
16754     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16755   }
16756
16757   return SDValue();
16758 }
16759
16760 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16761   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16762   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16763   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16764   // has only one use.
16765   SDNode *N = Op.getNode();
16766   SDValue LHS = N->getOperand(0);
16767   SDValue RHS = N->getOperand(1);
16768   unsigned BaseOp = 0;
16769   unsigned Cond = 0;
16770   SDLoc DL(Op);
16771   switch (Op.getOpcode()) {
16772   default: llvm_unreachable("Unknown ovf instruction!");
16773   case ISD::SADDO:
16774     // A subtract of one will be selected as a INC. Note that INC doesn't
16775     // set CF, so we can't do this for UADDO.
16776     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16777       if (C->isOne()) {
16778         BaseOp = X86ISD::INC;
16779         Cond = X86::COND_O;
16780         break;
16781       }
16782     BaseOp = X86ISD::ADD;
16783     Cond = X86::COND_O;
16784     break;
16785   case ISD::UADDO:
16786     BaseOp = X86ISD::ADD;
16787     Cond = X86::COND_B;
16788     break;
16789   case ISD::SSUBO:
16790     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16791     // set CF, so we can't do this for USUBO.
16792     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16793       if (C->isOne()) {
16794         BaseOp = X86ISD::DEC;
16795         Cond = X86::COND_O;
16796         break;
16797       }
16798     BaseOp = X86ISD::SUB;
16799     Cond = X86::COND_O;
16800     break;
16801   case ISD::USUBO:
16802     BaseOp = X86ISD::SUB;
16803     Cond = X86::COND_B;
16804     break;
16805   case ISD::SMULO:
16806     BaseOp = X86ISD::SMUL;
16807     Cond = X86::COND_O;
16808     break;
16809   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16810     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16811                                  MVT::i32);
16812     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16813
16814     SDValue SetCC =
16815       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16816                   DAG.getConstant(X86::COND_O, MVT::i32),
16817                   SDValue(Sum.getNode(), 2));
16818
16819     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16820   }
16821   }
16822
16823   // Also sets EFLAGS.
16824   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16825   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16826
16827   SDValue SetCC =
16828     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16829                 DAG.getConstant(Cond, MVT::i32),
16830                 SDValue(Sum.getNode(), 1));
16831
16832   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16833 }
16834
16835 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16836                                                   SelectionDAG &DAG) const {
16837   SDLoc dl(Op);
16838   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16839   MVT VT = Op.getSimpleValueType();
16840
16841   if (!Subtarget->hasSSE2() || !VT.isVector())
16842     return SDValue();
16843
16844   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16845                       ExtraVT.getScalarType().getSizeInBits();
16846
16847   switch (VT.SimpleTy) {
16848     default: return SDValue();
16849     case MVT::v8i32:
16850     case MVT::v16i16:
16851       if (!Subtarget->hasFp256())
16852         return SDValue();
16853       if (!Subtarget->hasInt256()) {
16854         // needs to be split
16855         unsigned NumElems = VT.getVectorNumElements();
16856
16857         // Extract the LHS vectors
16858         SDValue LHS = Op.getOperand(0);
16859         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16860         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16861
16862         MVT EltVT = VT.getVectorElementType();
16863         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16864
16865         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16866         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16867         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16868                                    ExtraNumElems/2);
16869         SDValue Extra = DAG.getValueType(ExtraVT);
16870
16871         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16872         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16873
16874         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16875       }
16876       // fall through
16877     case MVT::v4i32:
16878     case MVT::v8i16: {
16879       SDValue Op0 = Op.getOperand(0);
16880       SDValue Op00 = Op0.getOperand(0);
16881       SDValue Tmp1;
16882       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16883       if (Op0.getOpcode() == ISD::BITCAST &&
16884           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16885         // (sext (vzext x)) -> (vsext x)
16886         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16887         if (Tmp1.getNode()) {
16888           EVT ExtraEltVT = ExtraVT.getVectorElementType();
16889           // This folding is only valid when the in-reg type is a vector of i8,
16890           // i16, or i32.
16891           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16892               ExtraEltVT == MVT::i32) {
16893             SDValue Tmp1Op0 = Tmp1.getOperand(0);
16894             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16895                    "This optimization is invalid without a VZEXT.");
16896             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16897           }
16898           Op0 = Tmp1;
16899         }
16900       }
16901
16902       // If the above didn't work, then just use Shift-Left + Shift-Right.
16903       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16904                                         DAG);
16905       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16906                                         DAG);
16907     }
16908   }
16909 }
16910
16911 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16912                                  SelectionDAG &DAG) {
16913   SDLoc dl(Op);
16914   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16915     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16916   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16917     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16918
16919   // The only fence that needs an instruction is a sequentially-consistent
16920   // cross-thread fence.
16921   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16922     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16923     // no-sse2). There isn't any reason to disable it if the target processor
16924     // supports it.
16925     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16926       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16927
16928     SDValue Chain = Op.getOperand(0);
16929     SDValue Zero = DAG.getConstant(0, MVT::i32);
16930     SDValue Ops[] = {
16931       DAG.getRegister(X86::ESP, MVT::i32), // Base
16932       DAG.getTargetConstant(1, MVT::i8),   // Scale
16933       DAG.getRegister(0, MVT::i32),        // Index
16934       DAG.getTargetConstant(0, MVT::i32),  // Disp
16935       DAG.getRegister(0, MVT::i32),        // Segment.
16936       Zero,
16937       Chain
16938     };
16939     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16940     return SDValue(Res, 0);
16941   }
16942
16943   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16944   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16945 }
16946
16947 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16948                              SelectionDAG &DAG) {
16949   MVT T = Op.getSimpleValueType();
16950   SDLoc DL(Op);
16951   unsigned Reg = 0;
16952   unsigned size = 0;
16953   switch(T.SimpleTy) {
16954   default: llvm_unreachable("Invalid value type!");
16955   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16956   case MVT::i16: Reg = X86::AX;  size = 2; break;
16957   case MVT::i32: Reg = X86::EAX; size = 4; break;
16958   case MVT::i64:
16959     assert(Subtarget->is64Bit() && "Node not type legal!");
16960     Reg = X86::RAX; size = 8;
16961     break;
16962   }
16963   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16964                                   Op.getOperand(2), SDValue());
16965   SDValue Ops[] = { cpIn.getValue(0),
16966                     Op.getOperand(1),
16967                     Op.getOperand(3),
16968                     DAG.getTargetConstant(size, MVT::i8),
16969                     cpIn.getValue(1) };
16970   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16971   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16972   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16973                                            Ops, T, MMO);
16974
16975   SDValue cpOut =
16976     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16977   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16978                                       MVT::i32, cpOut.getValue(2));
16979   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16980                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16981
16982   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16983   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16984   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16985   return SDValue();
16986 }
16987
16988 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16989                             SelectionDAG &DAG) {
16990   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16991   MVT DstVT = Op.getSimpleValueType();
16992
16993   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16994     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16995     if (DstVT != MVT::f64)
16996       // This conversion needs to be expanded.
16997       return SDValue();
16998
16999     SDValue InVec = Op->getOperand(0);
17000     SDLoc dl(Op);
17001     unsigned NumElts = SrcVT.getVectorNumElements();
17002     EVT SVT = SrcVT.getVectorElementType();
17003
17004     // Widen the vector in input in the case of MVT::v2i32.
17005     // Example: from MVT::v2i32 to MVT::v4i32.
17006     SmallVector<SDValue, 16> Elts;
17007     for (unsigned i = 0, e = NumElts; i != e; ++i)
17008       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17009                                  DAG.getIntPtrConstant(i)));
17010
17011     // Explicitly mark the extra elements as Undef.
17012     SDValue Undef = DAG.getUNDEF(SVT);
17013     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
17014       Elts.push_back(Undef);
17015
17016     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17017     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17018     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17019     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17020                        DAG.getIntPtrConstant(0));
17021   }
17022
17023   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17024          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17025   assert((DstVT == MVT::i64 ||
17026           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17027          "Unexpected custom BITCAST");
17028   // i64 <=> MMX conversions are Legal.
17029   if (SrcVT==MVT::i64 && DstVT.isVector())
17030     return Op;
17031   if (DstVT==MVT::i64 && SrcVT.isVector())
17032     return Op;
17033   // MMX <=> MMX conversions are Legal.
17034   if (SrcVT.isVector() && DstVT.isVector())
17035     return Op;
17036   // All other conversions need to be expanded.
17037   return SDValue();
17038 }
17039
17040 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17041   SDNode *Node = Op.getNode();
17042   SDLoc dl(Node);
17043   EVT T = Node->getValueType(0);
17044   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17045                               DAG.getConstant(0, T), Node->getOperand(2));
17046   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17047                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17048                        Node->getOperand(0),
17049                        Node->getOperand(1), negOp,
17050                        cast<AtomicSDNode>(Node)->getMemOperand(),
17051                        cast<AtomicSDNode>(Node)->getOrdering(),
17052                        cast<AtomicSDNode>(Node)->getSynchScope());
17053 }
17054
17055 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17056   SDNode *Node = Op.getNode();
17057   SDLoc dl(Node);
17058   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17059
17060   // Convert seq_cst store -> xchg
17061   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17062   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17063   //        (The only way to get a 16-byte store is cmpxchg16b)
17064   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17065   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17066       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17067     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17068                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17069                                  Node->getOperand(0),
17070                                  Node->getOperand(1), Node->getOperand(2),
17071                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17072                                  cast<AtomicSDNode>(Node)->getOrdering(),
17073                                  cast<AtomicSDNode>(Node)->getSynchScope());
17074     return Swap.getValue(1);
17075   }
17076   // Other atomic stores have a simple pattern.
17077   return Op;
17078 }
17079
17080 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17081   EVT VT = Op.getNode()->getSimpleValueType(0);
17082
17083   // Let legalize expand this if it isn't a legal type yet.
17084   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17085     return SDValue();
17086
17087   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17088
17089   unsigned Opc;
17090   bool ExtraOp = false;
17091   switch (Op.getOpcode()) {
17092   default: llvm_unreachable("Invalid code");
17093   case ISD::ADDC: Opc = X86ISD::ADD; break;
17094   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17095   case ISD::SUBC: Opc = X86ISD::SUB; break;
17096   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17097   }
17098
17099   if (!ExtraOp)
17100     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17101                        Op.getOperand(1));
17102   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17103                      Op.getOperand(1), Op.getOperand(2));
17104 }
17105
17106 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17107                             SelectionDAG &DAG) {
17108   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17109
17110   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17111   // which returns the values as { float, float } (in XMM0) or
17112   // { double, double } (which is returned in XMM0, XMM1).
17113   SDLoc dl(Op);
17114   SDValue Arg = Op.getOperand(0);
17115   EVT ArgVT = Arg.getValueType();
17116   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17117
17118   TargetLowering::ArgListTy Args;
17119   TargetLowering::ArgListEntry Entry;
17120
17121   Entry.Node = Arg;
17122   Entry.Ty = ArgTy;
17123   Entry.isSExt = false;
17124   Entry.isZExt = false;
17125   Args.push_back(Entry);
17126
17127   bool isF64 = ArgVT == MVT::f64;
17128   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17129   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17130   // the results are returned via SRet in memory.
17131   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17132   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17133   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17134
17135   Type *RetTy = isF64
17136     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
17137     : (Type*)VectorType::get(ArgTy, 4);
17138
17139   TargetLowering::CallLoweringInfo CLI(DAG);
17140   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17141     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17142
17143   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17144
17145   if (isF64)
17146     // Returned in xmm0 and xmm1.
17147     return CallResult.first;
17148
17149   // Returned in bits 0:31 and 32:64 xmm0.
17150   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17151                                CallResult.first, DAG.getIntPtrConstant(0));
17152   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17153                                CallResult.first, DAG.getIntPtrConstant(1));
17154   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17155   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17156 }
17157
17158 /// LowerOperation - Provide custom lowering hooks for some operations.
17159 ///
17160 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17161   switch (Op.getOpcode()) {
17162   default: llvm_unreachable("Should not custom lower this!");
17163   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
17164   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17165   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17166     return LowerCMP_SWAP(Op, Subtarget, DAG);
17167   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17168   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17169   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17170   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
17171   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
17172   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17173   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17174   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17175   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17176   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17177   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17178   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17179   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17180   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17181   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17182   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17183   case ISD::SHL_PARTS:
17184   case ISD::SRA_PARTS:
17185   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17186   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17187   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17188   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17189   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17190   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17191   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17192   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17193   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17194   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17195   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17196   case ISD::FABS:               return LowerFABS(Op, DAG);
17197   case ISD::FNEG:               return LowerFNEG(Op, DAG);
17198   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17199   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17200   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17201   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17202   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17203   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17204   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17205   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17206   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17207   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
17208   case ISD::INTRINSIC_VOID:
17209   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17210   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17211   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17212   case ISD::FRAME_TO_ARGS_OFFSET:
17213                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17214   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17215   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17216   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17217   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17218   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17219   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17220   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17221   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17222   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17223   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17224   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17225   case ISD::UMUL_LOHI:
17226   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17227   case ISD::SRA:
17228   case ISD::SRL:
17229   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17230   case ISD::SADDO:
17231   case ISD::UADDO:
17232   case ISD::SSUBO:
17233   case ISD::USUBO:
17234   case ISD::SMULO:
17235   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17236   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17237   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17238   case ISD::ADDC:
17239   case ISD::ADDE:
17240   case ISD::SUBC:
17241   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17242   case ISD::ADD:                return LowerADD(Op, DAG);
17243   case ISD::SUB:                return LowerSUB(Op, DAG);
17244   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17245   }
17246 }
17247
17248 static void ReplaceATOMIC_LOAD(SDNode *Node,
17249                                SmallVectorImpl<SDValue> &Results,
17250                                SelectionDAG &DAG) {
17251   SDLoc dl(Node);
17252   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17253
17254   // Convert wide load -> cmpxchg8b/cmpxchg16b
17255   // FIXME: On 32-bit, load -> fild or movq would be more efficient
17256   //        (The only way to get a 16-byte load is cmpxchg16b)
17257   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
17258   SDValue Zero = DAG.getConstant(0, VT);
17259   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
17260   SDValue Swap =
17261       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
17262                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
17263                            cast<AtomicSDNode>(Node)->getMemOperand(),
17264                            cast<AtomicSDNode>(Node)->getOrdering(),
17265                            cast<AtomicSDNode>(Node)->getOrdering(),
17266                            cast<AtomicSDNode>(Node)->getSynchScope());
17267   Results.push_back(Swap.getValue(0));
17268   Results.push_back(Swap.getValue(2));
17269 }
17270
17271 /// ReplaceNodeResults - Replace a node with an illegal result type
17272 /// with a new node built out of custom code.
17273 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17274                                            SmallVectorImpl<SDValue>&Results,
17275                                            SelectionDAG &DAG) const {
17276   SDLoc dl(N);
17277   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17278   switch (N->getOpcode()) {
17279   default:
17280     llvm_unreachable("Do not know how to custom type legalize this operation!");
17281   case ISD::SIGN_EXTEND_INREG:
17282   case ISD::ADDC:
17283   case ISD::ADDE:
17284   case ISD::SUBC:
17285   case ISD::SUBE:
17286     // We don't want to expand or promote these.
17287     return;
17288   case ISD::SDIV:
17289   case ISD::UDIV:
17290   case ISD::SREM:
17291   case ISD::UREM:
17292   case ISD::SDIVREM:
17293   case ISD::UDIVREM: {
17294     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17295     Results.push_back(V);
17296     return;
17297   }
17298   case ISD::FP_TO_SINT:
17299   case ISD::FP_TO_UINT: {
17300     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17301
17302     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17303       return;
17304
17305     std::pair<SDValue,SDValue> Vals =
17306         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17307     SDValue FIST = Vals.first, StackSlot = Vals.second;
17308     if (FIST.getNode()) {
17309       EVT VT = N->getValueType(0);
17310       // Return a load from the stack slot.
17311       if (StackSlot.getNode())
17312         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17313                                       MachinePointerInfo(),
17314                                       false, false, false, 0));
17315       else
17316         Results.push_back(FIST);
17317     }
17318     return;
17319   }
17320   case ISD::UINT_TO_FP: {
17321     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17322     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17323         N->getValueType(0) != MVT::v2f32)
17324       return;
17325     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17326                                  N->getOperand(0));
17327     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17328                                      MVT::f64);
17329     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17330     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17331                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17332     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17333     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17334     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17335     return;
17336   }
17337   case ISD::FP_ROUND: {
17338     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17339         return;
17340     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17341     Results.push_back(V);
17342     return;
17343   }
17344   case ISD::INTRINSIC_W_CHAIN: {
17345     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17346     switch (IntNo) {
17347     default : llvm_unreachable("Do not know how to custom type "
17348                                "legalize this intrinsic operation!");
17349     case Intrinsic::x86_rdtsc:
17350       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17351                                      Results);
17352     case Intrinsic::x86_rdtscp:
17353       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17354                                      Results);
17355     case Intrinsic::x86_rdpmc:
17356       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17357     }
17358   }
17359   case ISD::READCYCLECOUNTER: {
17360     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17361                                    Results);
17362   }
17363   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17364     EVT T = N->getValueType(0);
17365     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17366     bool Regs64bit = T == MVT::i128;
17367     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17368     SDValue cpInL, cpInH;
17369     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17370                         DAG.getConstant(0, HalfT));
17371     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17372                         DAG.getConstant(1, HalfT));
17373     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17374                              Regs64bit ? X86::RAX : X86::EAX,
17375                              cpInL, SDValue());
17376     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17377                              Regs64bit ? X86::RDX : X86::EDX,
17378                              cpInH, cpInL.getValue(1));
17379     SDValue swapInL, swapInH;
17380     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17381                           DAG.getConstant(0, HalfT));
17382     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17383                           DAG.getConstant(1, HalfT));
17384     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17385                                Regs64bit ? X86::RBX : X86::EBX,
17386                                swapInL, cpInH.getValue(1));
17387     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17388                                Regs64bit ? X86::RCX : X86::ECX,
17389                                swapInH, swapInL.getValue(1));
17390     SDValue Ops[] = { swapInH.getValue(0),
17391                       N->getOperand(1),
17392                       swapInH.getValue(1) };
17393     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17394     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17395     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17396                                   X86ISD::LCMPXCHG8_DAG;
17397     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17398     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17399                                         Regs64bit ? X86::RAX : X86::EAX,
17400                                         HalfT, Result.getValue(1));
17401     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17402                                         Regs64bit ? X86::RDX : X86::EDX,
17403                                         HalfT, cpOutL.getValue(2));
17404     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17405
17406     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17407                                         MVT::i32, cpOutH.getValue(2));
17408     SDValue Success =
17409         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17410                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17411     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17412
17413     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17414     Results.push_back(Success);
17415     Results.push_back(EFLAGS.getValue(1));
17416     return;
17417   }
17418   case ISD::ATOMIC_SWAP:
17419   case ISD::ATOMIC_LOAD_ADD:
17420   case ISD::ATOMIC_LOAD_SUB:
17421   case ISD::ATOMIC_LOAD_AND:
17422   case ISD::ATOMIC_LOAD_OR:
17423   case ISD::ATOMIC_LOAD_XOR:
17424   case ISD::ATOMIC_LOAD_NAND:
17425   case ISD::ATOMIC_LOAD_MIN:
17426   case ISD::ATOMIC_LOAD_MAX:
17427   case ISD::ATOMIC_LOAD_UMIN:
17428   case ISD::ATOMIC_LOAD_UMAX:
17429     // Delegate to generic TypeLegalization. Situations we can really handle
17430     // should have already been dealt with by X86AtomicExpandPass.cpp.
17431     break;
17432   case ISD::ATOMIC_LOAD: {
17433     ReplaceATOMIC_LOAD(N, Results, DAG);
17434     return;
17435   }
17436   case ISD::BITCAST: {
17437     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17438     EVT DstVT = N->getValueType(0);
17439     EVT SrcVT = N->getOperand(0)->getValueType(0);
17440
17441     if (SrcVT != MVT::f64 ||
17442         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17443       return;
17444
17445     unsigned NumElts = DstVT.getVectorNumElements();
17446     EVT SVT = DstVT.getVectorElementType();
17447     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17448     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17449                                    MVT::v2f64, N->getOperand(0));
17450     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17451
17452     if (ExperimentalVectorWideningLegalization) {
17453       // If we are legalizing vectors by widening, we already have the desired
17454       // legal vector type, just return it.
17455       Results.push_back(ToVecInt);
17456       return;
17457     }
17458
17459     SmallVector<SDValue, 8> Elts;
17460     for (unsigned i = 0, e = NumElts; i != e; ++i)
17461       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17462                                    ToVecInt, DAG.getIntPtrConstant(i)));
17463
17464     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17465   }
17466   }
17467 }
17468
17469 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17470   switch (Opcode) {
17471   default: return nullptr;
17472   case X86ISD::BSF:                return "X86ISD::BSF";
17473   case X86ISD::BSR:                return "X86ISD::BSR";
17474   case X86ISD::SHLD:               return "X86ISD::SHLD";
17475   case X86ISD::SHRD:               return "X86ISD::SHRD";
17476   case X86ISD::FAND:               return "X86ISD::FAND";
17477   case X86ISD::FANDN:              return "X86ISD::FANDN";
17478   case X86ISD::FOR:                return "X86ISD::FOR";
17479   case X86ISD::FXOR:               return "X86ISD::FXOR";
17480   case X86ISD::FSRL:               return "X86ISD::FSRL";
17481   case X86ISD::FILD:               return "X86ISD::FILD";
17482   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17483   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17484   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17485   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17486   case X86ISD::FLD:                return "X86ISD::FLD";
17487   case X86ISD::FST:                return "X86ISD::FST";
17488   case X86ISD::CALL:               return "X86ISD::CALL";
17489   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17490   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17491   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17492   case X86ISD::BT:                 return "X86ISD::BT";
17493   case X86ISD::CMP:                return "X86ISD::CMP";
17494   case X86ISD::COMI:               return "X86ISD::COMI";
17495   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17496   case X86ISD::CMPM:               return "X86ISD::CMPM";
17497   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17498   case X86ISD::SETCC:              return "X86ISD::SETCC";
17499   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17500   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17501   case X86ISD::CMOV:               return "X86ISD::CMOV";
17502   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17503   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17504   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17505   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17506   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17507   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17508   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17509   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17510   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17511   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17512   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17513   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17514   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17515   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17516   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17517   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
17518   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17519   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17520   case X86ISD::HADD:               return "X86ISD::HADD";
17521   case X86ISD::HSUB:               return "X86ISD::HSUB";
17522   case X86ISD::FHADD:              return "X86ISD::FHADD";
17523   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17524   case X86ISD::UMAX:               return "X86ISD::UMAX";
17525   case X86ISD::UMIN:               return "X86ISD::UMIN";
17526   case X86ISD::SMAX:               return "X86ISD::SMAX";
17527   case X86ISD::SMIN:               return "X86ISD::SMIN";
17528   case X86ISD::FMAX:               return "X86ISD::FMAX";
17529   case X86ISD::FMIN:               return "X86ISD::FMIN";
17530   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17531   case X86ISD::FMINC:              return "X86ISD::FMINC";
17532   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17533   case X86ISD::FRCP:               return "X86ISD::FRCP";
17534   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17535   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17536   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17537   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17538   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17539   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17540   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17541   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17542   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17543   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17544   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17545   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17546   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17547   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17548   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17549   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17550   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17551   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17552   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17553   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17554   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17555   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17556   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17557   case X86ISD::VSHL:               return "X86ISD::VSHL";
17558   case X86ISD::VSRL:               return "X86ISD::VSRL";
17559   case X86ISD::VSRA:               return "X86ISD::VSRA";
17560   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17561   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17562   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17563   case X86ISD::CMPP:               return "X86ISD::CMPP";
17564   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17565   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17566   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17567   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17568   case X86ISD::ADD:                return "X86ISD::ADD";
17569   case X86ISD::SUB:                return "X86ISD::SUB";
17570   case X86ISD::ADC:                return "X86ISD::ADC";
17571   case X86ISD::SBB:                return "X86ISD::SBB";
17572   case X86ISD::SMUL:               return "X86ISD::SMUL";
17573   case X86ISD::UMUL:               return "X86ISD::UMUL";
17574   case X86ISD::INC:                return "X86ISD::INC";
17575   case X86ISD::DEC:                return "X86ISD::DEC";
17576   case X86ISD::OR:                 return "X86ISD::OR";
17577   case X86ISD::XOR:                return "X86ISD::XOR";
17578   case X86ISD::AND:                return "X86ISD::AND";
17579   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17580   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17581   case X86ISD::PTEST:              return "X86ISD::PTEST";
17582   case X86ISD::TESTP:              return "X86ISD::TESTP";
17583   case X86ISD::TESTM:              return "X86ISD::TESTM";
17584   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17585   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17586   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17587   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17588   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17589   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17590   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17591   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17592   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17593   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17594   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17595   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17596   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17597   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17598   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17599   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17600   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17601   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17602   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17603   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17604   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17605   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17606   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17607   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17608   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17609   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
17610   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17611   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17612   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17613   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17614   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17615   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17616   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17617   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17618   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17619   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17620   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17621   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17622   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17623   case X86ISD::SAHF:               return "X86ISD::SAHF";
17624   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17625   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17626   case X86ISD::FMADD:              return "X86ISD::FMADD";
17627   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17628   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17629   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17630   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17631   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17632   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17633   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17634   case X86ISD::XTEST:              return "X86ISD::XTEST";
17635   }
17636 }
17637
17638 // isLegalAddressingMode - Return true if the addressing mode represented
17639 // by AM is legal for this target, for a load/store of the specified type.
17640 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17641                                               Type *Ty) const {
17642   // X86 supports extremely general addressing modes.
17643   CodeModel::Model M = getTargetMachine().getCodeModel();
17644   Reloc::Model R = getTargetMachine().getRelocationModel();
17645
17646   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17647   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17648     return false;
17649
17650   if (AM.BaseGV) {
17651     unsigned GVFlags =
17652       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17653
17654     // If a reference to this global requires an extra load, we can't fold it.
17655     if (isGlobalStubReference(GVFlags))
17656       return false;
17657
17658     // If BaseGV requires a register for the PIC base, we cannot also have a
17659     // BaseReg specified.
17660     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17661       return false;
17662
17663     // If lower 4G is not available, then we must use rip-relative addressing.
17664     if ((M != CodeModel::Small || R != Reloc::Static) &&
17665         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17666       return false;
17667   }
17668
17669   switch (AM.Scale) {
17670   case 0:
17671   case 1:
17672   case 2:
17673   case 4:
17674   case 8:
17675     // These scales always work.
17676     break;
17677   case 3:
17678   case 5:
17679   case 9:
17680     // These scales are formed with basereg+scalereg.  Only accept if there is
17681     // no basereg yet.
17682     if (AM.HasBaseReg)
17683       return false;
17684     break;
17685   default:  // Other stuff never works.
17686     return false;
17687   }
17688
17689   return true;
17690 }
17691
17692 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17693   unsigned Bits = Ty->getScalarSizeInBits();
17694
17695   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17696   // particularly cheaper than those without.
17697   if (Bits == 8)
17698     return false;
17699
17700   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17701   // variable shifts just as cheap as scalar ones.
17702   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17703     return false;
17704
17705   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17706   // fully general vector.
17707   return true;
17708 }
17709
17710 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17711   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17712     return false;
17713   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17714   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17715   return NumBits1 > NumBits2;
17716 }
17717
17718 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17719   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17720     return false;
17721
17722   if (!isTypeLegal(EVT::getEVT(Ty1)))
17723     return false;
17724
17725   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17726
17727   // Assuming the caller doesn't have a zeroext or signext return parameter,
17728   // truncation all the way down to i1 is valid.
17729   return true;
17730 }
17731
17732 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17733   return isInt<32>(Imm);
17734 }
17735
17736 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17737   // Can also use sub to handle negated immediates.
17738   return isInt<32>(Imm);
17739 }
17740
17741 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17742   if (!VT1.isInteger() || !VT2.isInteger())
17743     return false;
17744   unsigned NumBits1 = VT1.getSizeInBits();
17745   unsigned NumBits2 = VT2.getSizeInBits();
17746   return NumBits1 > NumBits2;
17747 }
17748
17749 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17750   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17751   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17752 }
17753
17754 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17755   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17756   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17757 }
17758
17759 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17760   EVT VT1 = Val.getValueType();
17761   if (isZExtFree(VT1, VT2))
17762     return true;
17763
17764   if (Val.getOpcode() != ISD::LOAD)
17765     return false;
17766
17767   if (!VT1.isSimple() || !VT1.isInteger() ||
17768       !VT2.isSimple() || !VT2.isInteger())
17769     return false;
17770
17771   switch (VT1.getSimpleVT().SimpleTy) {
17772   default: break;
17773   case MVT::i8:
17774   case MVT::i16:
17775   case MVT::i32:
17776     // X86 has 8, 16, and 32-bit zero-extending loads.
17777     return true;
17778   }
17779
17780   return false;
17781 }
17782
17783 bool
17784 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17785   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17786     return false;
17787
17788   VT = VT.getScalarType();
17789
17790   if (!VT.isSimple())
17791     return false;
17792
17793   switch (VT.getSimpleVT().SimpleTy) {
17794   case MVT::f32:
17795   case MVT::f64:
17796     return true;
17797   default:
17798     break;
17799   }
17800
17801   return false;
17802 }
17803
17804 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17805   // i16 instructions are longer (0x66 prefix) and potentially slower.
17806   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17807 }
17808
17809 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17810 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17811 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17812 /// are assumed to be legal.
17813 bool
17814 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17815                                       EVT VT) const {
17816   if (!VT.isSimple())
17817     return false;
17818
17819   MVT SVT = VT.getSimpleVT();
17820
17821   // Very little shuffling can be done for 64-bit vectors right now.
17822   if (VT.getSizeInBits() == 64)
17823     return false;
17824
17825   // If this is a single-input shuffle with no 128 bit lane crossings we can
17826   // lower it into pshufb.
17827   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17828       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17829     bool isLegal = true;
17830     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17831       if (M[I] >= (int)SVT.getVectorNumElements() ||
17832           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17833         isLegal = false;
17834         break;
17835       }
17836     }
17837     if (isLegal)
17838       return true;
17839   }
17840
17841   // FIXME: blends, shifts.
17842   return (SVT.getVectorNumElements() == 2 ||
17843           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17844           isMOVLMask(M, SVT) ||
17845           isMOVHLPSMask(M, SVT) ||
17846           isSHUFPMask(M, SVT) ||
17847           isPSHUFDMask(M, SVT) ||
17848           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17849           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17850           isPALIGNRMask(M, SVT, Subtarget) ||
17851           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17852           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17853           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17854           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17855           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17856 }
17857
17858 bool
17859 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17860                                           EVT VT) const {
17861   if (!VT.isSimple())
17862     return false;
17863
17864   MVT SVT = VT.getSimpleVT();
17865   unsigned NumElts = SVT.getVectorNumElements();
17866   // FIXME: This collection of masks seems suspect.
17867   if (NumElts == 2)
17868     return true;
17869   if (NumElts == 4 && SVT.is128BitVector()) {
17870     return (isMOVLMask(Mask, SVT)  ||
17871             isCommutedMOVLMask(Mask, SVT, true) ||
17872             isSHUFPMask(Mask, SVT) ||
17873             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17874   }
17875   return false;
17876 }
17877
17878 //===----------------------------------------------------------------------===//
17879 //                           X86 Scheduler Hooks
17880 //===----------------------------------------------------------------------===//
17881
17882 /// Utility function to emit xbegin specifying the start of an RTM region.
17883 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17884                                      const TargetInstrInfo *TII) {
17885   DebugLoc DL = MI->getDebugLoc();
17886
17887   const BasicBlock *BB = MBB->getBasicBlock();
17888   MachineFunction::iterator I = MBB;
17889   ++I;
17890
17891   // For the v = xbegin(), we generate
17892   //
17893   // thisMBB:
17894   //  xbegin sinkMBB
17895   //
17896   // mainMBB:
17897   //  eax = -1
17898   //
17899   // sinkMBB:
17900   //  v = eax
17901
17902   MachineBasicBlock *thisMBB = MBB;
17903   MachineFunction *MF = MBB->getParent();
17904   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17905   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17906   MF->insert(I, mainMBB);
17907   MF->insert(I, sinkMBB);
17908
17909   // Transfer the remainder of BB and its successor edges to sinkMBB.
17910   sinkMBB->splice(sinkMBB->begin(), MBB,
17911                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17912   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17913
17914   // thisMBB:
17915   //  xbegin sinkMBB
17916   //  # fallthrough to mainMBB
17917   //  # abortion to sinkMBB
17918   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17919   thisMBB->addSuccessor(mainMBB);
17920   thisMBB->addSuccessor(sinkMBB);
17921
17922   // mainMBB:
17923   //  EAX = -1
17924   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17925   mainMBB->addSuccessor(sinkMBB);
17926
17927   // sinkMBB:
17928   // EAX is live into the sinkMBB
17929   sinkMBB->addLiveIn(X86::EAX);
17930   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17931           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17932     .addReg(X86::EAX);
17933
17934   MI->eraseFromParent();
17935   return sinkMBB;
17936 }
17937
17938 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17939 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17940 // in the .td file.
17941 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17942                                        const TargetInstrInfo *TII) {
17943   unsigned Opc;
17944   switch (MI->getOpcode()) {
17945   default: llvm_unreachable("illegal opcode!");
17946   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17947   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17948   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17949   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17950   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17951   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17952   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17953   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17954   }
17955
17956   DebugLoc dl = MI->getDebugLoc();
17957   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17958
17959   unsigned NumArgs = MI->getNumOperands();
17960   for (unsigned i = 1; i < NumArgs; ++i) {
17961     MachineOperand &Op = MI->getOperand(i);
17962     if (!(Op.isReg() && Op.isImplicit()))
17963       MIB.addOperand(Op);
17964   }
17965   if (MI->hasOneMemOperand())
17966     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17967
17968   BuildMI(*BB, MI, dl,
17969     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17970     .addReg(X86::XMM0);
17971
17972   MI->eraseFromParent();
17973   return BB;
17974 }
17975
17976 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17977 // defs in an instruction pattern
17978 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17979                                        const TargetInstrInfo *TII) {
17980   unsigned Opc;
17981   switch (MI->getOpcode()) {
17982   default: llvm_unreachable("illegal opcode!");
17983   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17984   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17985   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17986   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17987   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17988   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17989   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17990   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17991   }
17992
17993   DebugLoc dl = MI->getDebugLoc();
17994   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17995
17996   unsigned NumArgs = MI->getNumOperands(); // remove the results
17997   for (unsigned i = 1; i < NumArgs; ++i) {
17998     MachineOperand &Op = MI->getOperand(i);
17999     if (!(Op.isReg() && Op.isImplicit()))
18000       MIB.addOperand(Op);
18001   }
18002   if (MI->hasOneMemOperand())
18003     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18004
18005   BuildMI(*BB, MI, dl,
18006     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18007     .addReg(X86::ECX);
18008
18009   MI->eraseFromParent();
18010   return BB;
18011 }
18012
18013 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18014                                        const TargetInstrInfo *TII,
18015                                        const X86Subtarget* Subtarget) {
18016   DebugLoc dl = MI->getDebugLoc();
18017
18018   // Address into RAX/EAX, other two args into ECX, EDX.
18019   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18020   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18021   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18022   for (int i = 0; i < X86::AddrNumOperands; ++i)
18023     MIB.addOperand(MI->getOperand(i));
18024
18025   unsigned ValOps = X86::AddrNumOperands;
18026   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18027     .addReg(MI->getOperand(ValOps).getReg());
18028   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18029     .addReg(MI->getOperand(ValOps+1).getReg());
18030
18031   // The instruction doesn't actually take any operands though.
18032   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18033
18034   MI->eraseFromParent(); // The pseudo is gone now.
18035   return BB;
18036 }
18037
18038 MachineBasicBlock *
18039 X86TargetLowering::EmitVAARG64WithCustomInserter(
18040                    MachineInstr *MI,
18041                    MachineBasicBlock *MBB) const {
18042   // Emit va_arg instruction on X86-64.
18043
18044   // Operands to this pseudo-instruction:
18045   // 0  ) Output        : destination address (reg)
18046   // 1-5) Input         : va_list address (addr, i64mem)
18047   // 6  ) ArgSize       : Size (in bytes) of vararg type
18048   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18049   // 8  ) Align         : Alignment of type
18050   // 9  ) EFLAGS (implicit-def)
18051
18052   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18053   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
18054
18055   unsigned DestReg = MI->getOperand(0).getReg();
18056   MachineOperand &Base = MI->getOperand(1);
18057   MachineOperand &Scale = MI->getOperand(2);
18058   MachineOperand &Index = MI->getOperand(3);
18059   MachineOperand &Disp = MI->getOperand(4);
18060   MachineOperand &Segment = MI->getOperand(5);
18061   unsigned ArgSize = MI->getOperand(6).getImm();
18062   unsigned ArgMode = MI->getOperand(7).getImm();
18063   unsigned Align = MI->getOperand(8).getImm();
18064
18065   // Memory Reference
18066   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18067   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18068   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18069
18070   // Machine Information
18071   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18072   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18073   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18074   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18075   DebugLoc DL = MI->getDebugLoc();
18076
18077   // struct va_list {
18078   //   i32   gp_offset
18079   //   i32   fp_offset
18080   //   i64   overflow_area (address)
18081   //   i64   reg_save_area (address)
18082   // }
18083   // sizeof(va_list) = 24
18084   // alignment(va_list) = 8
18085
18086   unsigned TotalNumIntRegs = 6;
18087   unsigned TotalNumXMMRegs = 8;
18088   bool UseGPOffset = (ArgMode == 1);
18089   bool UseFPOffset = (ArgMode == 2);
18090   unsigned MaxOffset = TotalNumIntRegs * 8 +
18091                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18092
18093   /* Align ArgSize to a multiple of 8 */
18094   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18095   bool NeedsAlign = (Align > 8);
18096
18097   MachineBasicBlock *thisMBB = MBB;
18098   MachineBasicBlock *overflowMBB;
18099   MachineBasicBlock *offsetMBB;
18100   MachineBasicBlock *endMBB;
18101
18102   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18103   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18104   unsigned OffsetReg = 0;
18105
18106   if (!UseGPOffset && !UseFPOffset) {
18107     // If we only pull from the overflow region, we don't create a branch.
18108     // We don't need to alter control flow.
18109     OffsetDestReg = 0; // unused
18110     OverflowDestReg = DestReg;
18111
18112     offsetMBB = nullptr;
18113     overflowMBB = thisMBB;
18114     endMBB = thisMBB;
18115   } else {
18116     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18117     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18118     // If not, pull from overflow_area. (branch to overflowMBB)
18119     //
18120     //       thisMBB
18121     //         |     .
18122     //         |        .
18123     //     offsetMBB   overflowMBB
18124     //         |        .
18125     //         |     .
18126     //        endMBB
18127
18128     // Registers for the PHI in endMBB
18129     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18130     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18131
18132     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18133     MachineFunction *MF = MBB->getParent();
18134     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18135     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18136     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18137
18138     MachineFunction::iterator MBBIter = MBB;
18139     ++MBBIter;
18140
18141     // Insert the new basic blocks
18142     MF->insert(MBBIter, offsetMBB);
18143     MF->insert(MBBIter, overflowMBB);
18144     MF->insert(MBBIter, endMBB);
18145
18146     // Transfer the remainder of MBB and its successor edges to endMBB.
18147     endMBB->splice(endMBB->begin(), thisMBB,
18148                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18149     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18150
18151     // Make offsetMBB and overflowMBB successors of thisMBB
18152     thisMBB->addSuccessor(offsetMBB);
18153     thisMBB->addSuccessor(overflowMBB);
18154
18155     // endMBB is a successor of both offsetMBB and overflowMBB
18156     offsetMBB->addSuccessor(endMBB);
18157     overflowMBB->addSuccessor(endMBB);
18158
18159     // Load the offset value into a register
18160     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18161     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18162       .addOperand(Base)
18163       .addOperand(Scale)
18164       .addOperand(Index)
18165       .addDisp(Disp, UseFPOffset ? 4 : 0)
18166       .addOperand(Segment)
18167       .setMemRefs(MMOBegin, MMOEnd);
18168
18169     // Check if there is enough room left to pull this argument.
18170     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18171       .addReg(OffsetReg)
18172       .addImm(MaxOffset + 8 - ArgSizeA8);
18173
18174     // Branch to "overflowMBB" if offset >= max
18175     // Fall through to "offsetMBB" otherwise
18176     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18177       .addMBB(overflowMBB);
18178   }
18179
18180   // In offsetMBB, emit code to use the reg_save_area.
18181   if (offsetMBB) {
18182     assert(OffsetReg != 0);
18183
18184     // Read the reg_save_area address.
18185     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18186     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18187       .addOperand(Base)
18188       .addOperand(Scale)
18189       .addOperand(Index)
18190       .addDisp(Disp, 16)
18191       .addOperand(Segment)
18192       .setMemRefs(MMOBegin, MMOEnd);
18193
18194     // Zero-extend the offset
18195     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18196       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18197         .addImm(0)
18198         .addReg(OffsetReg)
18199         .addImm(X86::sub_32bit);
18200
18201     // Add the offset to the reg_save_area to get the final address.
18202     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18203       .addReg(OffsetReg64)
18204       .addReg(RegSaveReg);
18205
18206     // Compute the offset for the next argument
18207     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18208     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18209       .addReg(OffsetReg)
18210       .addImm(UseFPOffset ? 16 : 8);
18211
18212     // Store it back into the va_list.
18213     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18214       .addOperand(Base)
18215       .addOperand(Scale)
18216       .addOperand(Index)
18217       .addDisp(Disp, UseFPOffset ? 4 : 0)
18218       .addOperand(Segment)
18219       .addReg(NextOffsetReg)
18220       .setMemRefs(MMOBegin, MMOEnd);
18221
18222     // Jump to endMBB
18223     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
18224       .addMBB(endMBB);
18225   }
18226
18227   //
18228   // Emit code to use overflow area
18229   //
18230
18231   // Load the overflow_area address into a register.
18232   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18233   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18234     .addOperand(Base)
18235     .addOperand(Scale)
18236     .addOperand(Index)
18237     .addDisp(Disp, 8)
18238     .addOperand(Segment)
18239     .setMemRefs(MMOBegin, MMOEnd);
18240
18241   // If we need to align it, do so. Otherwise, just copy the address
18242   // to OverflowDestReg.
18243   if (NeedsAlign) {
18244     // Align the overflow address
18245     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18246     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18247
18248     // aligned_addr = (addr + (align-1)) & ~(align-1)
18249     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18250       .addReg(OverflowAddrReg)
18251       .addImm(Align-1);
18252
18253     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18254       .addReg(TmpReg)
18255       .addImm(~(uint64_t)(Align-1));
18256   } else {
18257     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18258       .addReg(OverflowAddrReg);
18259   }
18260
18261   // Compute the next overflow address after this argument.
18262   // (the overflow address should be kept 8-byte aligned)
18263   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18264   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18265     .addReg(OverflowDestReg)
18266     .addImm(ArgSizeA8);
18267
18268   // Store the new overflow address.
18269   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18270     .addOperand(Base)
18271     .addOperand(Scale)
18272     .addOperand(Index)
18273     .addDisp(Disp, 8)
18274     .addOperand(Segment)
18275     .addReg(NextAddrReg)
18276     .setMemRefs(MMOBegin, MMOEnd);
18277
18278   // If we branched, emit the PHI to the front of endMBB.
18279   if (offsetMBB) {
18280     BuildMI(*endMBB, endMBB->begin(), DL,
18281             TII->get(X86::PHI), DestReg)
18282       .addReg(OffsetDestReg).addMBB(offsetMBB)
18283       .addReg(OverflowDestReg).addMBB(overflowMBB);
18284   }
18285
18286   // Erase the pseudo instruction
18287   MI->eraseFromParent();
18288
18289   return endMBB;
18290 }
18291
18292 MachineBasicBlock *
18293 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18294                                                  MachineInstr *MI,
18295                                                  MachineBasicBlock *MBB) const {
18296   // Emit code to save XMM registers to the stack. The ABI says that the
18297   // number of registers to save is given in %al, so it's theoretically
18298   // possible to do an indirect jump trick to avoid saving all of them,
18299   // however this code takes a simpler approach and just executes all
18300   // of the stores if %al is non-zero. It's less code, and it's probably
18301   // easier on the hardware branch predictor, and stores aren't all that
18302   // expensive anyway.
18303
18304   // Create the new basic blocks. One block contains all the XMM stores,
18305   // and one block is the final destination regardless of whether any
18306   // stores were performed.
18307   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18308   MachineFunction *F = MBB->getParent();
18309   MachineFunction::iterator MBBIter = MBB;
18310   ++MBBIter;
18311   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18312   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18313   F->insert(MBBIter, XMMSaveMBB);
18314   F->insert(MBBIter, EndMBB);
18315
18316   // Transfer the remainder of MBB and its successor edges to EndMBB.
18317   EndMBB->splice(EndMBB->begin(), MBB,
18318                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18319   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18320
18321   // The original block will now fall through to the XMM save block.
18322   MBB->addSuccessor(XMMSaveMBB);
18323   // The XMMSaveMBB will fall through to the end block.
18324   XMMSaveMBB->addSuccessor(EndMBB);
18325
18326   // Now add the instructions.
18327   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18328   DebugLoc DL = MI->getDebugLoc();
18329
18330   unsigned CountReg = MI->getOperand(0).getReg();
18331   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18332   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18333
18334   if (!Subtarget->isTargetWin64()) {
18335     // If %al is 0, branch around the XMM save block.
18336     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18337     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
18338     MBB->addSuccessor(EndMBB);
18339   }
18340
18341   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18342   // that was just emitted, but clearly shouldn't be "saved".
18343   assert((MI->getNumOperands() <= 3 ||
18344           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18345           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18346          && "Expected last argument to be EFLAGS");
18347   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18348   // In the XMM save block, save all the XMM argument registers.
18349   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18350     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18351     MachineMemOperand *MMO =
18352       F->getMachineMemOperand(
18353           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18354         MachineMemOperand::MOStore,
18355         /*Size=*/16, /*Align=*/16);
18356     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18357       .addFrameIndex(RegSaveFrameIndex)
18358       .addImm(/*Scale=*/1)
18359       .addReg(/*IndexReg=*/0)
18360       .addImm(/*Disp=*/Offset)
18361       .addReg(/*Segment=*/0)
18362       .addReg(MI->getOperand(i).getReg())
18363       .addMemOperand(MMO);
18364   }
18365
18366   MI->eraseFromParent();   // The pseudo instruction is gone now.
18367
18368   return EndMBB;
18369 }
18370
18371 // The EFLAGS operand of SelectItr might be missing a kill marker
18372 // because there were multiple uses of EFLAGS, and ISel didn't know
18373 // which to mark. Figure out whether SelectItr should have had a
18374 // kill marker, and set it if it should. Returns the correct kill
18375 // marker value.
18376 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18377                                      MachineBasicBlock* BB,
18378                                      const TargetRegisterInfo* TRI) {
18379   // Scan forward through BB for a use/def of EFLAGS.
18380   MachineBasicBlock::iterator miI(std::next(SelectItr));
18381   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18382     const MachineInstr& mi = *miI;
18383     if (mi.readsRegister(X86::EFLAGS))
18384       return false;
18385     if (mi.definesRegister(X86::EFLAGS))
18386       break; // Should have kill-flag - update below.
18387   }
18388
18389   // If we hit the end of the block, check whether EFLAGS is live into a
18390   // successor.
18391   if (miI == BB->end()) {
18392     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18393                                           sEnd = BB->succ_end();
18394          sItr != sEnd; ++sItr) {
18395       MachineBasicBlock* succ = *sItr;
18396       if (succ->isLiveIn(X86::EFLAGS))
18397         return false;
18398     }
18399   }
18400
18401   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18402   // out. SelectMI should have a kill flag on EFLAGS.
18403   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18404   return true;
18405 }
18406
18407 MachineBasicBlock *
18408 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18409                                      MachineBasicBlock *BB) const {
18410   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18411   DebugLoc DL = MI->getDebugLoc();
18412
18413   // To "insert" a SELECT_CC instruction, we actually have to insert the
18414   // diamond control-flow pattern.  The incoming instruction knows the
18415   // destination vreg to set, the condition code register to branch on, the
18416   // true/false values to select between, and a branch opcode to use.
18417   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18418   MachineFunction::iterator It = BB;
18419   ++It;
18420
18421   //  thisMBB:
18422   //  ...
18423   //   TrueVal = ...
18424   //   cmpTY ccX, r1, r2
18425   //   bCC copy1MBB
18426   //   fallthrough --> copy0MBB
18427   MachineBasicBlock *thisMBB = BB;
18428   MachineFunction *F = BB->getParent();
18429   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18430   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18431   F->insert(It, copy0MBB);
18432   F->insert(It, sinkMBB);
18433
18434   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18435   // live into the sink and copy blocks.
18436   const TargetRegisterInfo *TRI =
18437       BB->getParent()->getSubtarget().getRegisterInfo();
18438   if (!MI->killsRegister(X86::EFLAGS) &&
18439       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18440     copy0MBB->addLiveIn(X86::EFLAGS);
18441     sinkMBB->addLiveIn(X86::EFLAGS);
18442   }
18443
18444   // Transfer the remainder of BB and its successor edges to sinkMBB.
18445   sinkMBB->splice(sinkMBB->begin(), BB,
18446                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18447   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18448
18449   // Add the true and fallthrough blocks as its successors.
18450   BB->addSuccessor(copy0MBB);
18451   BB->addSuccessor(sinkMBB);
18452
18453   // Create the conditional branch instruction.
18454   unsigned Opc =
18455     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18456   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18457
18458   //  copy0MBB:
18459   //   %FalseValue = ...
18460   //   # fallthrough to sinkMBB
18461   copy0MBB->addSuccessor(sinkMBB);
18462
18463   //  sinkMBB:
18464   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18465   //  ...
18466   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18467           TII->get(X86::PHI), MI->getOperand(0).getReg())
18468     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18469     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18470
18471   MI->eraseFromParent();   // The pseudo instruction is gone now.
18472   return sinkMBB;
18473 }
18474
18475 MachineBasicBlock *
18476 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18477                                         bool Is64Bit) const {
18478   MachineFunction *MF = BB->getParent();
18479   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18480   DebugLoc DL = MI->getDebugLoc();
18481   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18482
18483   assert(MF->shouldSplitStack());
18484
18485   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18486   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18487
18488   // BB:
18489   //  ... [Till the alloca]
18490   // If stacklet is not large enough, jump to mallocMBB
18491   //
18492   // bumpMBB:
18493   //  Allocate by subtracting from RSP
18494   //  Jump to continueMBB
18495   //
18496   // mallocMBB:
18497   //  Allocate by call to runtime
18498   //
18499   // continueMBB:
18500   //  ...
18501   //  [rest of original BB]
18502   //
18503
18504   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18505   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18506   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18507
18508   MachineRegisterInfo &MRI = MF->getRegInfo();
18509   const TargetRegisterClass *AddrRegClass =
18510     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18511
18512   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18513     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18514     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18515     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18516     sizeVReg = MI->getOperand(1).getReg(),
18517     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18518
18519   MachineFunction::iterator MBBIter = BB;
18520   ++MBBIter;
18521
18522   MF->insert(MBBIter, bumpMBB);
18523   MF->insert(MBBIter, mallocMBB);
18524   MF->insert(MBBIter, continueMBB);
18525
18526   continueMBB->splice(continueMBB->begin(), BB,
18527                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18528   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18529
18530   // Add code to the main basic block to check if the stack limit has been hit,
18531   // and if so, jump to mallocMBB otherwise to bumpMBB.
18532   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18533   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18534     .addReg(tmpSPVReg).addReg(sizeVReg);
18535   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18536     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18537     .addReg(SPLimitVReg);
18538   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18539
18540   // bumpMBB simply decreases the stack pointer, since we know the current
18541   // stacklet has enough space.
18542   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18543     .addReg(SPLimitVReg);
18544   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18545     .addReg(SPLimitVReg);
18546   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18547
18548   // Calls into a routine in libgcc to allocate more space from the heap.
18549   const uint32_t *RegMask = MF->getTarget()
18550                                 .getSubtargetImpl()
18551                                 ->getRegisterInfo()
18552                                 ->getCallPreservedMask(CallingConv::C);
18553   if (Is64Bit) {
18554     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18555       .addReg(sizeVReg);
18556     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18557       .addExternalSymbol("__morestack_allocate_stack_space")
18558       .addRegMask(RegMask)
18559       .addReg(X86::RDI, RegState::Implicit)
18560       .addReg(X86::RAX, RegState::ImplicitDefine);
18561   } else {
18562     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18563       .addImm(12);
18564     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18565     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18566       .addExternalSymbol("__morestack_allocate_stack_space")
18567       .addRegMask(RegMask)
18568       .addReg(X86::EAX, RegState::ImplicitDefine);
18569   }
18570
18571   if (!Is64Bit)
18572     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18573       .addImm(16);
18574
18575   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18576     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18577   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18578
18579   // Set up the CFG correctly.
18580   BB->addSuccessor(bumpMBB);
18581   BB->addSuccessor(mallocMBB);
18582   mallocMBB->addSuccessor(continueMBB);
18583   bumpMBB->addSuccessor(continueMBB);
18584
18585   // Take care of the PHI nodes.
18586   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18587           MI->getOperand(0).getReg())
18588     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18589     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18590
18591   // Delete the original pseudo instruction.
18592   MI->eraseFromParent();
18593
18594   // And we're done.
18595   return continueMBB;
18596 }
18597
18598 MachineBasicBlock *
18599 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18600                                         MachineBasicBlock *BB) const {
18601   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18602   DebugLoc DL = MI->getDebugLoc();
18603
18604   assert(!Subtarget->isTargetMacho());
18605
18606   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18607   // non-trivial part is impdef of ESP.
18608
18609   if (Subtarget->isTargetWin64()) {
18610     if (Subtarget->isTargetCygMing()) {
18611       // ___chkstk(Mingw64):
18612       // Clobbers R10, R11, RAX and EFLAGS.
18613       // Updates RSP.
18614       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18615         .addExternalSymbol("___chkstk")
18616         .addReg(X86::RAX, RegState::Implicit)
18617         .addReg(X86::RSP, RegState::Implicit)
18618         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18619         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18620         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18621     } else {
18622       // __chkstk(MSVCRT): does not update stack pointer.
18623       // Clobbers R10, R11 and EFLAGS.
18624       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18625         .addExternalSymbol("__chkstk")
18626         .addReg(X86::RAX, RegState::Implicit)
18627         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18628       // RAX has the offset to be subtracted from RSP.
18629       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18630         .addReg(X86::RSP)
18631         .addReg(X86::RAX);
18632     }
18633   } else {
18634     const char *StackProbeSymbol =
18635       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18636
18637     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18638       .addExternalSymbol(StackProbeSymbol)
18639       .addReg(X86::EAX, RegState::Implicit)
18640       .addReg(X86::ESP, RegState::Implicit)
18641       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18642       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18643       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18644   }
18645
18646   MI->eraseFromParent();   // The pseudo instruction is gone now.
18647   return BB;
18648 }
18649
18650 MachineBasicBlock *
18651 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18652                                       MachineBasicBlock *BB) const {
18653   // This is pretty easy.  We're taking the value that we received from
18654   // our load from the relocation, sticking it in either RDI (x86-64)
18655   // or EAX and doing an indirect call.  The return value will then
18656   // be in the normal return register.
18657   MachineFunction *F = BB->getParent();
18658   const X86InstrInfo *TII =
18659       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18660   DebugLoc DL = MI->getDebugLoc();
18661
18662   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18663   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18664
18665   // Get a register mask for the lowered call.
18666   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18667   // proper register mask.
18668   const uint32_t *RegMask = F->getTarget()
18669                                 .getSubtargetImpl()
18670                                 ->getRegisterInfo()
18671                                 ->getCallPreservedMask(CallingConv::C);
18672   if (Subtarget->is64Bit()) {
18673     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18674                                       TII->get(X86::MOV64rm), X86::RDI)
18675     .addReg(X86::RIP)
18676     .addImm(0).addReg(0)
18677     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18678                       MI->getOperand(3).getTargetFlags())
18679     .addReg(0);
18680     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18681     addDirectMem(MIB, X86::RDI);
18682     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18683   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18684     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18685                                       TII->get(X86::MOV32rm), X86::EAX)
18686     .addReg(0)
18687     .addImm(0).addReg(0)
18688     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18689                       MI->getOperand(3).getTargetFlags())
18690     .addReg(0);
18691     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18692     addDirectMem(MIB, X86::EAX);
18693     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18694   } else {
18695     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18696                                       TII->get(X86::MOV32rm), X86::EAX)
18697     .addReg(TII->getGlobalBaseReg(F))
18698     .addImm(0).addReg(0)
18699     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18700                       MI->getOperand(3).getTargetFlags())
18701     .addReg(0);
18702     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18703     addDirectMem(MIB, X86::EAX);
18704     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18705   }
18706
18707   MI->eraseFromParent(); // The pseudo instruction is gone now.
18708   return BB;
18709 }
18710
18711 MachineBasicBlock *
18712 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18713                                     MachineBasicBlock *MBB) const {
18714   DebugLoc DL = MI->getDebugLoc();
18715   MachineFunction *MF = MBB->getParent();
18716   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18717   MachineRegisterInfo &MRI = MF->getRegInfo();
18718
18719   const BasicBlock *BB = MBB->getBasicBlock();
18720   MachineFunction::iterator I = MBB;
18721   ++I;
18722
18723   // Memory Reference
18724   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18725   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18726
18727   unsigned DstReg;
18728   unsigned MemOpndSlot = 0;
18729
18730   unsigned CurOp = 0;
18731
18732   DstReg = MI->getOperand(CurOp++).getReg();
18733   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18734   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18735   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18736   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18737
18738   MemOpndSlot = CurOp;
18739
18740   MVT PVT = getPointerTy();
18741   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18742          "Invalid Pointer Size!");
18743
18744   // For v = setjmp(buf), we generate
18745   //
18746   // thisMBB:
18747   //  buf[LabelOffset] = restoreMBB
18748   //  SjLjSetup restoreMBB
18749   //
18750   // mainMBB:
18751   //  v_main = 0
18752   //
18753   // sinkMBB:
18754   //  v = phi(main, restore)
18755   //
18756   // restoreMBB:
18757   //  v_restore = 1
18758
18759   MachineBasicBlock *thisMBB = MBB;
18760   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18761   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18762   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18763   MF->insert(I, mainMBB);
18764   MF->insert(I, sinkMBB);
18765   MF->push_back(restoreMBB);
18766
18767   MachineInstrBuilder MIB;
18768
18769   // Transfer the remainder of BB and its successor edges to sinkMBB.
18770   sinkMBB->splice(sinkMBB->begin(), MBB,
18771                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18772   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18773
18774   // thisMBB:
18775   unsigned PtrStoreOpc = 0;
18776   unsigned LabelReg = 0;
18777   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18778   Reloc::Model RM = MF->getTarget().getRelocationModel();
18779   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18780                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18781
18782   // Prepare IP either in reg or imm.
18783   if (!UseImmLabel) {
18784     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18785     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18786     LabelReg = MRI.createVirtualRegister(PtrRC);
18787     if (Subtarget->is64Bit()) {
18788       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18789               .addReg(X86::RIP)
18790               .addImm(0)
18791               .addReg(0)
18792               .addMBB(restoreMBB)
18793               .addReg(0);
18794     } else {
18795       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18796       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18797               .addReg(XII->getGlobalBaseReg(MF))
18798               .addImm(0)
18799               .addReg(0)
18800               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18801               .addReg(0);
18802     }
18803   } else
18804     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18805   // Store IP
18806   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18807   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18808     if (i == X86::AddrDisp)
18809       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18810     else
18811       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18812   }
18813   if (!UseImmLabel)
18814     MIB.addReg(LabelReg);
18815   else
18816     MIB.addMBB(restoreMBB);
18817   MIB.setMemRefs(MMOBegin, MMOEnd);
18818   // Setup
18819   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18820           .addMBB(restoreMBB);
18821
18822   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18823       MF->getSubtarget().getRegisterInfo());
18824   MIB.addRegMask(RegInfo->getNoPreservedMask());
18825   thisMBB->addSuccessor(mainMBB);
18826   thisMBB->addSuccessor(restoreMBB);
18827
18828   // mainMBB:
18829   //  EAX = 0
18830   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18831   mainMBB->addSuccessor(sinkMBB);
18832
18833   // sinkMBB:
18834   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18835           TII->get(X86::PHI), DstReg)
18836     .addReg(mainDstReg).addMBB(mainMBB)
18837     .addReg(restoreDstReg).addMBB(restoreMBB);
18838
18839   // restoreMBB:
18840   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18841   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18842   restoreMBB->addSuccessor(sinkMBB);
18843
18844   MI->eraseFromParent();
18845   return sinkMBB;
18846 }
18847
18848 MachineBasicBlock *
18849 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18850                                      MachineBasicBlock *MBB) const {
18851   DebugLoc DL = MI->getDebugLoc();
18852   MachineFunction *MF = MBB->getParent();
18853   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18854   MachineRegisterInfo &MRI = MF->getRegInfo();
18855
18856   // Memory Reference
18857   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18858   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18859
18860   MVT PVT = getPointerTy();
18861   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18862          "Invalid Pointer Size!");
18863
18864   const TargetRegisterClass *RC =
18865     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18866   unsigned Tmp = MRI.createVirtualRegister(RC);
18867   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18868   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18869       MF->getSubtarget().getRegisterInfo());
18870   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18871   unsigned SP = RegInfo->getStackRegister();
18872
18873   MachineInstrBuilder MIB;
18874
18875   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18876   const int64_t SPOffset = 2 * PVT.getStoreSize();
18877
18878   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18879   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18880
18881   // Reload FP
18882   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18883   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18884     MIB.addOperand(MI->getOperand(i));
18885   MIB.setMemRefs(MMOBegin, MMOEnd);
18886   // Reload IP
18887   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18888   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18889     if (i == X86::AddrDisp)
18890       MIB.addDisp(MI->getOperand(i), LabelOffset);
18891     else
18892       MIB.addOperand(MI->getOperand(i));
18893   }
18894   MIB.setMemRefs(MMOBegin, MMOEnd);
18895   // Reload SP
18896   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18897   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18898     if (i == X86::AddrDisp)
18899       MIB.addDisp(MI->getOperand(i), SPOffset);
18900     else
18901       MIB.addOperand(MI->getOperand(i));
18902   }
18903   MIB.setMemRefs(MMOBegin, MMOEnd);
18904   // Jump
18905   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18906
18907   MI->eraseFromParent();
18908   return MBB;
18909 }
18910
18911 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18912 // accumulator loops. Writing back to the accumulator allows the coalescer
18913 // to remove extra copies in the loop.   
18914 MachineBasicBlock *
18915 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18916                                  MachineBasicBlock *MBB) const {
18917   MachineOperand &AddendOp = MI->getOperand(3);
18918
18919   // Bail out early if the addend isn't a register - we can't switch these.
18920   if (!AddendOp.isReg())
18921     return MBB;
18922
18923   MachineFunction &MF = *MBB->getParent();
18924   MachineRegisterInfo &MRI = MF.getRegInfo();
18925
18926   // Check whether the addend is defined by a PHI:
18927   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18928   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18929   if (!AddendDef.isPHI())
18930     return MBB;
18931
18932   // Look for the following pattern:
18933   // loop:
18934   //   %addend = phi [%entry, 0], [%loop, %result]
18935   //   ...
18936   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18937
18938   // Replace with:
18939   //   loop:
18940   //   %addend = phi [%entry, 0], [%loop, %result]
18941   //   ...
18942   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18943
18944   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18945     assert(AddendDef.getOperand(i).isReg());
18946     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18947     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18948     if (&PHISrcInst == MI) {
18949       // Found a matching instruction.
18950       unsigned NewFMAOpc = 0;
18951       switch (MI->getOpcode()) {
18952         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18953         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18954         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18955         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18956         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18957         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18958         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18959         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18960         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18961         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18962         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18963         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18964         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18965         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18966         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18967         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18968         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18969         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18970         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18971         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18972         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18973         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18974         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18975         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18976         default: llvm_unreachable("Unrecognized FMA variant.");
18977       }
18978
18979       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18980       MachineInstrBuilder MIB =
18981         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18982         .addOperand(MI->getOperand(0))
18983         .addOperand(MI->getOperand(3))
18984         .addOperand(MI->getOperand(2))
18985         .addOperand(MI->getOperand(1));
18986       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18987       MI->eraseFromParent();
18988     }
18989   }
18990
18991   return MBB;
18992 }
18993
18994 MachineBasicBlock *
18995 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18996                                                MachineBasicBlock *BB) const {
18997   switch (MI->getOpcode()) {
18998   default: llvm_unreachable("Unexpected instr type to insert");
18999   case X86::TAILJMPd64:
19000   case X86::TAILJMPr64:
19001   case X86::TAILJMPm64:
19002     llvm_unreachable("TAILJMP64 would not be touched here.");
19003   case X86::TCRETURNdi64:
19004   case X86::TCRETURNri64:
19005   case X86::TCRETURNmi64:
19006     return BB;
19007   case X86::WIN_ALLOCA:
19008     return EmitLoweredWinAlloca(MI, BB);
19009   case X86::SEG_ALLOCA_32:
19010     return EmitLoweredSegAlloca(MI, BB, false);
19011   case X86::SEG_ALLOCA_64:
19012     return EmitLoweredSegAlloca(MI, BB, true);
19013   case X86::TLSCall_32:
19014   case X86::TLSCall_64:
19015     return EmitLoweredTLSCall(MI, BB);
19016   case X86::CMOV_GR8:
19017   case X86::CMOV_FR32:
19018   case X86::CMOV_FR64:
19019   case X86::CMOV_V4F32:
19020   case X86::CMOV_V2F64:
19021   case X86::CMOV_V2I64:
19022   case X86::CMOV_V8F32:
19023   case X86::CMOV_V4F64:
19024   case X86::CMOV_V4I64:
19025   case X86::CMOV_V16F32:
19026   case X86::CMOV_V8F64:
19027   case X86::CMOV_V8I64:
19028   case X86::CMOV_GR16:
19029   case X86::CMOV_GR32:
19030   case X86::CMOV_RFP32:
19031   case X86::CMOV_RFP64:
19032   case X86::CMOV_RFP80:
19033     return EmitLoweredSelect(MI, BB);
19034
19035   case X86::FP32_TO_INT16_IN_MEM:
19036   case X86::FP32_TO_INT32_IN_MEM:
19037   case X86::FP32_TO_INT64_IN_MEM:
19038   case X86::FP64_TO_INT16_IN_MEM:
19039   case X86::FP64_TO_INT32_IN_MEM:
19040   case X86::FP64_TO_INT64_IN_MEM:
19041   case X86::FP80_TO_INT16_IN_MEM:
19042   case X86::FP80_TO_INT32_IN_MEM:
19043   case X86::FP80_TO_INT64_IN_MEM: {
19044     MachineFunction *F = BB->getParent();
19045     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
19046     DebugLoc DL = MI->getDebugLoc();
19047
19048     // Change the floating point control register to use "round towards zero"
19049     // mode when truncating to an integer value.
19050     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19051     addFrameReference(BuildMI(*BB, MI, DL,
19052                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19053
19054     // Load the old value of the high byte of the control word...
19055     unsigned OldCW =
19056       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19057     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19058                       CWFrameIdx);
19059
19060     // Set the high part to be round to zero...
19061     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19062       .addImm(0xC7F);
19063
19064     // Reload the modified control word now...
19065     addFrameReference(BuildMI(*BB, MI, DL,
19066                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19067
19068     // Restore the memory image of control word to original value
19069     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19070       .addReg(OldCW);
19071
19072     // Get the X86 opcode to use.
19073     unsigned Opc;
19074     switch (MI->getOpcode()) {
19075     default: llvm_unreachable("illegal opcode!");
19076     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19077     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19078     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19079     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19080     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19081     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19082     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19083     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19084     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19085     }
19086
19087     X86AddressMode AM;
19088     MachineOperand &Op = MI->getOperand(0);
19089     if (Op.isReg()) {
19090       AM.BaseType = X86AddressMode::RegBase;
19091       AM.Base.Reg = Op.getReg();
19092     } else {
19093       AM.BaseType = X86AddressMode::FrameIndexBase;
19094       AM.Base.FrameIndex = Op.getIndex();
19095     }
19096     Op = MI->getOperand(1);
19097     if (Op.isImm())
19098       AM.Scale = Op.getImm();
19099     Op = MI->getOperand(2);
19100     if (Op.isImm())
19101       AM.IndexReg = Op.getImm();
19102     Op = MI->getOperand(3);
19103     if (Op.isGlobal()) {
19104       AM.GV = Op.getGlobal();
19105     } else {
19106       AM.Disp = Op.getImm();
19107     }
19108     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19109                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19110
19111     // Reload the original control word now.
19112     addFrameReference(BuildMI(*BB, MI, DL,
19113                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19114
19115     MI->eraseFromParent();   // The pseudo instruction is gone now.
19116     return BB;
19117   }
19118     // String/text processing lowering.
19119   case X86::PCMPISTRM128REG:
19120   case X86::VPCMPISTRM128REG:
19121   case X86::PCMPISTRM128MEM:
19122   case X86::VPCMPISTRM128MEM:
19123   case X86::PCMPESTRM128REG:
19124   case X86::VPCMPESTRM128REG:
19125   case X86::PCMPESTRM128MEM:
19126   case X86::VPCMPESTRM128MEM:
19127     assert(Subtarget->hasSSE42() &&
19128            "Target must have SSE4.2 or AVX features enabled");
19129     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19130
19131   // String/text processing lowering.
19132   case X86::PCMPISTRIREG:
19133   case X86::VPCMPISTRIREG:
19134   case X86::PCMPISTRIMEM:
19135   case X86::VPCMPISTRIMEM:
19136   case X86::PCMPESTRIREG:
19137   case X86::VPCMPESTRIREG:
19138   case X86::PCMPESTRIMEM:
19139   case X86::VPCMPESTRIMEM:
19140     assert(Subtarget->hasSSE42() &&
19141            "Target must have SSE4.2 or AVX features enabled");
19142     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19143
19144   // Thread synchronization.
19145   case X86::MONITOR:
19146     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
19147                        Subtarget);
19148
19149   // xbegin
19150   case X86::XBEGIN:
19151     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19152
19153   case X86::VASTART_SAVE_XMM_REGS:
19154     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19155
19156   case X86::VAARG_64:
19157     return EmitVAARG64WithCustomInserter(MI, BB);
19158
19159   case X86::EH_SjLj_SetJmp32:
19160   case X86::EH_SjLj_SetJmp64:
19161     return emitEHSjLjSetJmp(MI, BB);
19162
19163   case X86::EH_SjLj_LongJmp32:
19164   case X86::EH_SjLj_LongJmp64:
19165     return emitEHSjLjLongJmp(MI, BB);
19166
19167   case TargetOpcode::STACKMAP:
19168   case TargetOpcode::PATCHPOINT:
19169     return emitPatchPoint(MI, BB);
19170
19171   case X86::VFMADDPDr213r:
19172   case X86::VFMADDPSr213r:
19173   case X86::VFMADDSDr213r:
19174   case X86::VFMADDSSr213r:
19175   case X86::VFMSUBPDr213r:
19176   case X86::VFMSUBPSr213r:
19177   case X86::VFMSUBSDr213r:
19178   case X86::VFMSUBSSr213r:
19179   case X86::VFNMADDPDr213r:
19180   case X86::VFNMADDPSr213r:
19181   case X86::VFNMADDSDr213r:
19182   case X86::VFNMADDSSr213r:
19183   case X86::VFNMSUBPDr213r:
19184   case X86::VFNMSUBPSr213r:
19185   case X86::VFNMSUBSDr213r:
19186   case X86::VFNMSUBSSr213r:
19187   case X86::VFMADDPDr213rY:
19188   case X86::VFMADDPSr213rY:
19189   case X86::VFMSUBPDr213rY:
19190   case X86::VFMSUBPSr213rY:
19191   case X86::VFNMADDPDr213rY:
19192   case X86::VFNMADDPSr213rY:
19193   case X86::VFNMSUBPDr213rY:
19194   case X86::VFNMSUBPSr213rY:
19195     return emitFMA3Instr(MI, BB);
19196   }
19197 }
19198
19199 //===----------------------------------------------------------------------===//
19200 //                           X86 Optimization Hooks
19201 //===----------------------------------------------------------------------===//
19202
19203 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19204                                                       APInt &KnownZero,
19205                                                       APInt &KnownOne,
19206                                                       const SelectionDAG &DAG,
19207                                                       unsigned Depth) const {
19208   unsigned BitWidth = KnownZero.getBitWidth();
19209   unsigned Opc = Op.getOpcode();
19210   assert((Opc >= ISD::BUILTIN_OP_END ||
19211           Opc == ISD::INTRINSIC_WO_CHAIN ||
19212           Opc == ISD::INTRINSIC_W_CHAIN ||
19213           Opc == ISD::INTRINSIC_VOID) &&
19214          "Should use MaskedValueIsZero if you don't know whether Op"
19215          " is a target node!");
19216
19217   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19218   switch (Opc) {
19219   default: break;
19220   case X86ISD::ADD:
19221   case X86ISD::SUB:
19222   case X86ISD::ADC:
19223   case X86ISD::SBB:
19224   case X86ISD::SMUL:
19225   case X86ISD::UMUL:
19226   case X86ISD::INC:
19227   case X86ISD::DEC:
19228   case X86ISD::OR:
19229   case X86ISD::XOR:
19230   case X86ISD::AND:
19231     // These nodes' second result is a boolean.
19232     if (Op.getResNo() == 0)
19233       break;
19234     // Fallthrough
19235   case X86ISD::SETCC:
19236     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19237     break;
19238   case ISD::INTRINSIC_WO_CHAIN: {
19239     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19240     unsigned NumLoBits = 0;
19241     switch (IntId) {
19242     default: break;
19243     case Intrinsic::x86_sse_movmsk_ps:
19244     case Intrinsic::x86_avx_movmsk_ps_256:
19245     case Intrinsic::x86_sse2_movmsk_pd:
19246     case Intrinsic::x86_avx_movmsk_pd_256:
19247     case Intrinsic::x86_mmx_pmovmskb:
19248     case Intrinsic::x86_sse2_pmovmskb_128:
19249     case Intrinsic::x86_avx2_pmovmskb: {
19250       // High bits of movmskp{s|d}, pmovmskb are known zero.
19251       switch (IntId) {
19252         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19253         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19254         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19255         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19256         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19257         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19258         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19259         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19260       }
19261       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19262       break;
19263     }
19264     }
19265     break;
19266   }
19267   }
19268 }
19269
19270 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19271   SDValue Op,
19272   const SelectionDAG &,
19273   unsigned Depth) const {
19274   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19275   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19276     return Op.getValueType().getScalarType().getSizeInBits();
19277
19278   // Fallback case.
19279   return 1;
19280 }
19281
19282 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19283 /// node is a GlobalAddress + offset.
19284 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19285                                        const GlobalValue* &GA,
19286                                        int64_t &Offset) const {
19287   if (N->getOpcode() == X86ISD::Wrapper) {
19288     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19289       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19290       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19291       return true;
19292     }
19293   }
19294   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19295 }
19296
19297 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19298 /// same as extracting the high 128-bit part of 256-bit vector and then
19299 /// inserting the result into the low part of a new 256-bit vector
19300 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19301   EVT VT = SVOp->getValueType(0);
19302   unsigned NumElems = VT.getVectorNumElements();
19303
19304   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19305   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19306     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19307         SVOp->getMaskElt(j) >= 0)
19308       return false;
19309
19310   return true;
19311 }
19312
19313 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19314 /// same as extracting the low 128-bit part of 256-bit vector and then
19315 /// inserting the result into the high part of a new 256-bit vector
19316 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19317   EVT VT = SVOp->getValueType(0);
19318   unsigned NumElems = VT.getVectorNumElements();
19319
19320   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19321   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19322     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19323         SVOp->getMaskElt(j) >= 0)
19324       return false;
19325
19326   return true;
19327 }
19328
19329 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19330 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19331                                         TargetLowering::DAGCombinerInfo &DCI,
19332                                         const X86Subtarget* Subtarget) {
19333   SDLoc dl(N);
19334   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19335   SDValue V1 = SVOp->getOperand(0);
19336   SDValue V2 = SVOp->getOperand(1);
19337   EVT VT = SVOp->getValueType(0);
19338   unsigned NumElems = VT.getVectorNumElements();
19339
19340   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19341       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19342     //
19343     //                   0,0,0,...
19344     //                      |
19345     //    V      UNDEF    BUILD_VECTOR    UNDEF
19346     //     \      /           \           /
19347     //  CONCAT_VECTOR         CONCAT_VECTOR
19348     //         \                  /
19349     //          \                /
19350     //          RESULT: V + zero extended
19351     //
19352     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19353         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19354         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19355       return SDValue();
19356
19357     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19358       return SDValue();
19359
19360     // To match the shuffle mask, the first half of the mask should
19361     // be exactly the first vector, and all the rest a splat with the
19362     // first element of the second one.
19363     for (unsigned i = 0; i != NumElems/2; ++i)
19364       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19365           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19366         return SDValue();
19367
19368     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19369     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19370       if (Ld->hasNUsesOfValue(1, 0)) {
19371         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19372         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19373         SDValue ResNode =
19374           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19375                                   Ld->getMemoryVT(),
19376                                   Ld->getPointerInfo(),
19377                                   Ld->getAlignment(),
19378                                   false/*isVolatile*/, true/*ReadMem*/,
19379                                   false/*WriteMem*/);
19380
19381         // Make sure the newly-created LOAD is in the same position as Ld in
19382         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19383         // and update uses of Ld's output chain to use the TokenFactor.
19384         if (Ld->hasAnyUseOfValue(1)) {
19385           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19386                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19387           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19388           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19389                                  SDValue(ResNode.getNode(), 1));
19390         }
19391
19392         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19393       }
19394     }
19395
19396     // Emit a zeroed vector and insert the desired subvector on its
19397     // first half.
19398     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19399     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19400     return DCI.CombineTo(N, InsV);
19401   }
19402
19403   //===--------------------------------------------------------------------===//
19404   // Combine some shuffles into subvector extracts and inserts:
19405   //
19406
19407   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19408   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19409     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19410     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19411     return DCI.CombineTo(N, InsV);
19412   }
19413
19414   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19415   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19416     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19417     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19418     return DCI.CombineTo(N, InsV);
19419   }
19420
19421   return SDValue();
19422 }
19423
19424 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19425 /// possible.
19426 ///
19427 /// This is the leaf of the recursive combinine below. When we have found some
19428 /// chain of single-use x86 shuffle instructions and accumulated the combined
19429 /// shuffle mask represented by them, this will try to pattern match that mask
19430 /// into either a single instruction if there is a special purpose instruction
19431 /// for this operation, or into a PSHUFB instruction which is a fully general
19432 /// instruction but should only be used to replace chains over a certain depth.
19433 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19434                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19435                                    TargetLowering::DAGCombinerInfo &DCI,
19436                                    const X86Subtarget *Subtarget) {
19437   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19438
19439   // Find the operand that enters the chain. Note that multiple uses are OK
19440   // here, we're not going to remove the operand we find.
19441   SDValue Input = Op.getOperand(0);
19442   while (Input.getOpcode() == ISD::BITCAST)
19443     Input = Input.getOperand(0);
19444
19445   MVT VT = Input.getSimpleValueType();
19446   MVT RootVT = Root.getSimpleValueType();
19447   SDLoc DL(Root);
19448
19449   // Just remove no-op shuffle masks.
19450   if (Mask.size() == 1) {
19451     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19452                   /*AddTo*/ true);
19453     return true;
19454   }
19455
19456   // Use the float domain if the operand type is a floating point type.
19457   bool FloatDomain = VT.isFloatingPoint();
19458
19459   // If we don't have access to VEX encodings, the generic PSHUF instructions
19460   // are preferable to some of the specialized forms despite requiring one more
19461   // byte to encode because they can implicitly copy.
19462   //
19463   // IF we *do* have VEX encodings, than we can use shorter, more specific
19464   // shuffle instructions freely as they can copy due to the extra register
19465   // operand.
19466   if (Subtarget->hasAVX()) {
19467     // We have both floating point and integer variants of shuffles that dup
19468     // either the low or high half of the vector.
19469     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19470       bool Lo = Mask.equals(0, 0);
19471       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19472                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19473       if (Depth == 1 && Root->getOpcode() == Shuffle)
19474         return false; // Nothing to do!
19475       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19476       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19477       DCI.AddToWorklist(Op.getNode());
19478       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19479       DCI.AddToWorklist(Op.getNode());
19480       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19481                     /*AddTo*/ true);
19482       return true;
19483     }
19484
19485     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19486
19487     // For the integer domain we have specialized instructions for duplicating
19488     // any element size from the low or high half.
19489     if (!FloatDomain &&
19490         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19491          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19492          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19493          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19494          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19495                      15))) {
19496       bool Lo = Mask[0] == 0;
19497       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19498       if (Depth == 1 && Root->getOpcode() == Shuffle)
19499         return false; // Nothing to do!
19500       MVT ShuffleVT;
19501       switch (Mask.size()) {
19502       case 4: ShuffleVT = MVT::v4i32; break;
19503       case 8: ShuffleVT = MVT::v8i16; break;
19504       case 16: ShuffleVT = MVT::v16i8; break;
19505       };
19506       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19507       DCI.AddToWorklist(Op.getNode());
19508       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19509       DCI.AddToWorklist(Op.getNode());
19510       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19511                     /*AddTo*/ true);
19512       return true;
19513     }
19514   }
19515
19516   // Don't try to re-form single instruction chains under any circumstances now
19517   // that we've done encoding canonicalization for them.
19518   if (Depth < 2)
19519     return false;
19520
19521   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19522   // can replace them with a single PSHUFB instruction profitably. Intel's
19523   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19524   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19525   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19526     SmallVector<SDValue, 16> PSHUFBMask;
19527     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19528     int Ratio = 16 / Mask.size();
19529     for (unsigned i = 0; i < 16; ++i) {
19530       int M = Mask[i / Ratio] != SM_SentinelZero
19531                   ? Ratio * Mask[i / Ratio] + i % Ratio
19532                   : 255;
19533       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19534     }
19535     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19536     DCI.AddToWorklist(Op.getNode());
19537     SDValue PSHUFBMaskOp =
19538         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19539     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19540     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19541     DCI.AddToWorklist(Op.getNode());
19542     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19543                   /*AddTo*/ true);
19544     return true;
19545   }
19546
19547   // Failed to find any combines.
19548   return false;
19549 }
19550
19551 /// \brief Fully generic combining of x86 shuffle instructions.
19552 ///
19553 /// This should be the last combine run over the x86 shuffle instructions. Once
19554 /// they have been fully optimized, this will recursively consider all chains
19555 /// of single-use shuffle instructions, build a generic model of the cumulative
19556 /// shuffle operation, and check for simpler instructions which implement this
19557 /// operation. We use this primarily for two purposes:
19558 ///
19559 /// 1) Collapse generic shuffles to specialized single instructions when
19560 ///    equivalent. In most cases, this is just an encoding size win, but
19561 ///    sometimes we will collapse multiple generic shuffles into a single
19562 ///    special-purpose shuffle.
19563 /// 2) Look for sequences of shuffle instructions with 3 or more total
19564 ///    instructions, and replace them with the slightly more expensive SSSE3
19565 ///    PSHUFB instruction if available. We do this as the last combining step
19566 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19567 ///    a suitable short sequence of other instructions. The PHUFB will either
19568 ///    use a register or have to read from memory and so is slightly (but only
19569 ///    slightly) more expensive than the other shuffle instructions.
19570 ///
19571 /// Because this is inherently a quadratic operation (for each shuffle in
19572 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19573 /// This should never be an issue in practice as the shuffle lowering doesn't
19574 /// produce sequences of more than 8 instructions.
19575 ///
19576 /// FIXME: We will currently miss some cases where the redundant shuffling
19577 /// would simplify under the threshold for PSHUFB formation because of
19578 /// combine-ordering. To fix this, we should do the redundant instruction
19579 /// combining in this recursive walk.
19580 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19581                                           ArrayRef<int> RootMask,
19582                                           int Depth, bool HasPSHUFB,
19583                                           SelectionDAG &DAG,
19584                                           TargetLowering::DAGCombinerInfo &DCI,
19585                                           const X86Subtarget *Subtarget) {
19586   // Bound the depth of our recursive combine because this is ultimately
19587   // quadratic in nature.
19588   if (Depth > 8)
19589     return false;
19590
19591   // Directly rip through bitcasts to find the underlying operand.
19592   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19593     Op = Op.getOperand(0);
19594
19595   MVT VT = Op.getSimpleValueType();
19596   if (!VT.isVector())
19597     return false; // Bail if we hit a non-vector.
19598   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19599   // version should be added.
19600   if (VT.getSizeInBits() != 128)
19601     return false;
19602
19603   assert(Root.getSimpleValueType().isVector() &&
19604          "Shuffles operate on vector types!");
19605   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19606          "Can only combine shuffles of the same vector register size.");
19607
19608   if (!isTargetShuffle(Op.getOpcode()))
19609     return false;
19610   SmallVector<int, 16> OpMask;
19611   bool IsUnary;
19612   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19613   // We only can combine unary shuffles which we can decode the mask for.
19614   if (!HaveMask || !IsUnary)
19615     return false;
19616
19617   assert(VT.getVectorNumElements() == OpMask.size() &&
19618          "Different mask size from vector size!");
19619   assert(((RootMask.size() > OpMask.size() &&
19620            RootMask.size() % OpMask.size() == 0) ||
19621           (OpMask.size() > RootMask.size() &&
19622            OpMask.size() % RootMask.size() == 0) ||
19623           OpMask.size() == RootMask.size()) &&
19624          "The smaller number of elements must divide the larger.");
19625   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19626   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19627   assert(((RootRatio == 1 && OpRatio == 1) ||
19628           (RootRatio == 1) != (OpRatio == 1)) &&
19629          "Must not have a ratio for both incoming and op masks!");
19630
19631   SmallVector<int, 16> Mask;
19632   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19633
19634   // Merge this shuffle operation's mask into our accumulated mask. Note that
19635   // this shuffle's mask will be the first applied to the input, followed by the
19636   // root mask to get us all the way to the root value arrangement. The reason
19637   // for this order is that we are recursing up the operation chain.
19638   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19639     int RootIdx = i / RootRatio;
19640     if (RootMask[RootIdx] == SM_SentinelZero) {
19641       // This is a zero-ed lane, we're done.
19642       Mask.push_back(SM_SentinelZero);
19643       continue;
19644     }
19645
19646     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19647     int OpIdx = RootMaskedIdx / OpRatio;
19648     if (OpMask[OpIdx] == SM_SentinelZero) {
19649       // The incoming lanes are zero, it doesn't matter which ones we are using.
19650       Mask.push_back(SM_SentinelZero);
19651       continue;
19652     }
19653
19654     // Ok, we have non-zero lanes, map them through.
19655     Mask.push_back(OpMask[OpIdx] * OpRatio +
19656                    RootMaskedIdx % OpRatio);
19657   }
19658
19659   // See if we can recurse into the operand to combine more things.
19660   switch (Op.getOpcode()) {
19661     case X86ISD::PSHUFB:
19662       HasPSHUFB = true;
19663     case X86ISD::PSHUFD:
19664     case X86ISD::PSHUFHW:
19665     case X86ISD::PSHUFLW:
19666       if (Op.getOperand(0).hasOneUse() &&
19667           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19668                                         HasPSHUFB, DAG, DCI, Subtarget))
19669         return true;
19670       break;
19671
19672     case X86ISD::UNPCKL:
19673     case X86ISD::UNPCKH:
19674       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19675       // We can't check for single use, we have to check that this shuffle is the only user.
19676       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19677           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19678                                         HasPSHUFB, DAG, DCI, Subtarget))
19679           return true;
19680       break;
19681   }
19682
19683   // Minor canonicalization of the accumulated shuffle mask to make it easier
19684   // to match below. All this does is detect masks with squential pairs of
19685   // elements, and shrink them to the half-width mask. It does this in a loop
19686   // so it will reduce the size of the mask to the minimal width mask which
19687   // performs an equivalent shuffle.
19688   while (Mask.size() > 1 && canWidenShuffleElements(Mask)) {
19689     for (int i = 0, e = Mask.size() / 2; i < e; ++i)
19690       Mask[i] = Mask[2 * i] / 2;
19691     Mask.resize(Mask.size() / 2);
19692   }
19693
19694   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19695                                 Subtarget);
19696 }
19697
19698 /// \brief Get the PSHUF-style mask from PSHUF node.
19699 ///
19700 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19701 /// PSHUF-style masks that can be reused with such instructions.
19702 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19703   SmallVector<int, 4> Mask;
19704   bool IsUnary;
19705   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19706   (void)HaveMask;
19707   assert(HaveMask);
19708
19709   switch (N.getOpcode()) {
19710   case X86ISD::PSHUFD:
19711     return Mask;
19712   case X86ISD::PSHUFLW:
19713     Mask.resize(4);
19714     return Mask;
19715   case X86ISD::PSHUFHW:
19716     Mask.erase(Mask.begin(), Mask.begin() + 4);
19717     for (int &M : Mask)
19718       M -= 4;
19719     return Mask;
19720   default:
19721     llvm_unreachable("No valid shuffle instruction found!");
19722   }
19723 }
19724
19725 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19726 ///
19727 /// We walk up the chain and look for a combinable shuffle, skipping over
19728 /// shuffles that we could hoist this shuffle's transformation past without
19729 /// altering anything.
19730 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19731                                          SelectionDAG &DAG,
19732                                          TargetLowering::DAGCombinerInfo &DCI) {
19733   assert(N.getOpcode() == X86ISD::PSHUFD &&
19734          "Called with something other than an x86 128-bit half shuffle!");
19735   SDLoc DL(N);
19736
19737   // Walk up a single-use chain looking for a combinable shuffle.
19738   SDValue V = N.getOperand(0);
19739   for (; V.hasOneUse(); V = V.getOperand(0)) {
19740     switch (V.getOpcode()) {
19741     default:
19742       return false; // Nothing combined!
19743
19744     case ISD::BITCAST:
19745       // Skip bitcasts as we always know the type for the target specific
19746       // instructions.
19747       continue;
19748
19749     case X86ISD::PSHUFD:
19750       // Found another dword shuffle.
19751       break;
19752
19753     case X86ISD::PSHUFLW:
19754       // Check that the low words (being shuffled) are the identity in the
19755       // dword shuffle, and the high words are self-contained.
19756       if (Mask[0] != 0 || Mask[1] != 1 ||
19757           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19758         return false;
19759
19760       continue;
19761
19762     case X86ISD::PSHUFHW:
19763       // Check that the high words (being shuffled) are the identity in the
19764       // dword shuffle, and the low words are self-contained.
19765       if (Mask[2] != 2 || Mask[3] != 3 ||
19766           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19767         return false;
19768
19769       continue;
19770
19771     case X86ISD::UNPCKL:
19772     case X86ISD::UNPCKH:
19773       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19774       // shuffle into a preceding word shuffle.
19775       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19776         return false;
19777
19778       // Search for a half-shuffle which we can combine with.
19779       unsigned CombineOp =
19780           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19781       if (V.getOperand(0) != V.getOperand(1) ||
19782           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19783         return false;
19784       V = V.getOperand(0);
19785       do {
19786         switch (V.getOpcode()) {
19787         default:
19788           return false; // Nothing to combine.
19789
19790         case X86ISD::PSHUFLW:
19791         case X86ISD::PSHUFHW:
19792           if (V.getOpcode() == CombineOp)
19793             break;
19794
19795           // Fallthrough!
19796         case ISD::BITCAST:
19797           V = V.getOperand(0);
19798           continue;
19799         }
19800         break;
19801       } while (V.hasOneUse());
19802       break;
19803     }
19804     // Break out of the loop if we break out of the switch.
19805     break;
19806   }
19807
19808   if (!V.hasOneUse())
19809     // We fell out of the loop without finding a viable combining instruction.
19810     return false;
19811
19812   // Record the old value to use in RAUW-ing.
19813   SDValue Old = V;
19814
19815   // Merge this node's mask and our incoming mask.
19816   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19817   for (int &M : Mask)
19818     M = VMask[M];
19819   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19820                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19821
19822   // It is possible that one of the combinable shuffles was completely absorbed
19823   // by the other, just replace it and revisit all users in that case.
19824   if (Old.getNode() == V.getNode()) {
19825     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19826     return true;
19827   }
19828
19829   // Replace N with its operand as we're going to combine that shuffle away.
19830   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19831
19832   // Replace the combinable shuffle with the combined one, updating all users
19833   // so that we re-evaluate the chain here.
19834   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19835   return true;
19836 }
19837
19838 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19839 ///
19840 /// We walk up the chain, skipping shuffles of the other half and looking
19841 /// through shuffles which switch halves trying to find a shuffle of the same
19842 /// pair of dwords.
19843 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19844                                         SelectionDAG &DAG,
19845                                         TargetLowering::DAGCombinerInfo &DCI) {
19846   assert(
19847       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19848       "Called with something other than an x86 128-bit half shuffle!");
19849   SDLoc DL(N);
19850   unsigned CombineOpcode = N.getOpcode();
19851
19852   // Walk up a single-use chain looking for a combinable shuffle.
19853   SDValue V = N.getOperand(0);
19854   for (; V.hasOneUse(); V = V.getOperand(0)) {
19855     switch (V.getOpcode()) {
19856     default:
19857       return false; // Nothing combined!
19858
19859     case ISD::BITCAST:
19860       // Skip bitcasts as we always know the type for the target specific
19861       // instructions.
19862       continue;
19863
19864     case X86ISD::PSHUFLW:
19865     case X86ISD::PSHUFHW:
19866       if (V.getOpcode() == CombineOpcode)
19867         break;
19868
19869       // Other-half shuffles are no-ops.
19870       continue;
19871     }
19872     // Break out of the loop if we break out of the switch.
19873     break;
19874   }
19875
19876   if (!V.hasOneUse())
19877     // We fell out of the loop without finding a viable combining instruction.
19878     return false;
19879
19880   // Combine away the bottom node as its shuffle will be accumulated into
19881   // a preceding shuffle.
19882   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19883
19884   // Record the old value.
19885   SDValue Old = V;
19886
19887   // Merge this node's mask and our incoming mask (adjusted to account for all
19888   // the pshufd instructions encountered).
19889   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19890   for (int &M : Mask)
19891     M = VMask[M];
19892   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19893                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19894
19895   // Check that the shuffles didn't cancel each other out. If not, we need to
19896   // combine to the new one.
19897   if (Old != V)
19898     // Replace the combinable shuffle with the combined one, updating all users
19899     // so that we re-evaluate the chain here.
19900     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19901
19902   return true;
19903 }
19904
19905 /// \brief Try to combine x86 target specific shuffles.
19906 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19907                                            TargetLowering::DAGCombinerInfo &DCI,
19908                                            const X86Subtarget *Subtarget) {
19909   SDLoc DL(N);
19910   MVT VT = N.getSimpleValueType();
19911   SmallVector<int, 4> Mask;
19912
19913   switch (N.getOpcode()) {
19914   case X86ISD::PSHUFD:
19915   case X86ISD::PSHUFLW:
19916   case X86ISD::PSHUFHW:
19917     Mask = getPSHUFShuffleMask(N);
19918     assert(Mask.size() == 4);
19919     break;
19920   default:
19921     return SDValue();
19922   }
19923
19924   // Nuke no-op shuffles that show up after combining.
19925   if (isNoopShuffleMask(Mask))
19926     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19927
19928   // Look for simplifications involving one or two shuffle instructions.
19929   SDValue V = N.getOperand(0);
19930   switch (N.getOpcode()) {
19931   default:
19932     break;
19933   case X86ISD::PSHUFLW:
19934   case X86ISD::PSHUFHW:
19935     assert(VT == MVT::v8i16);
19936     (void)VT;
19937
19938     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19939       return SDValue(); // We combined away this shuffle, so we're done.
19940
19941     // See if this reduces to a PSHUFD which is no more expensive and can
19942     // combine with more operations.
19943     if (canWidenShuffleElements(Mask)) {
19944       int DMask[] = {-1, -1, -1, -1};
19945       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19946       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19947       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19948       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19949       DCI.AddToWorklist(V.getNode());
19950       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19951                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19952       DCI.AddToWorklist(V.getNode());
19953       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19954     }
19955
19956     // Look for shuffle patterns which can be implemented as a single unpack.
19957     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19958     // only works when we have a PSHUFD followed by two half-shuffles.
19959     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19960         (V.getOpcode() == X86ISD::PSHUFLW ||
19961          V.getOpcode() == X86ISD::PSHUFHW) &&
19962         V.getOpcode() != N.getOpcode() &&
19963         V.hasOneUse()) {
19964       SDValue D = V.getOperand(0);
19965       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19966         D = D.getOperand(0);
19967       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19968         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19969         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19970         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19971         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19972         int WordMask[8];
19973         for (int i = 0; i < 4; ++i) {
19974           WordMask[i + NOffset] = Mask[i] + NOffset;
19975           WordMask[i + VOffset] = VMask[i] + VOffset;
19976         }
19977         // Map the word mask through the DWord mask.
19978         int MappedMask[8];
19979         for (int i = 0; i < 8; ++i)
19980           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19981         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19982         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19983         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19984                        std::begin(UnpackLoMask)) ||
19985             std::equal(std::begin(MappedMask), std::end(MappedMask),
19986                        std::begin(UnpackHiMask))) {
19987           // We can replace all three shuffles with an unpack.
19988           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19989           DCI.AddToWorklist(V.getNode());
19990           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19991                                                 : X86ISD::UNPCKH,
19992                              DL, MVT::v8i16, V, V);
19993         }
19994       }
19995     }
19996
19997     break;
19998
19999   case X86ISD::PSHUFD:
20000     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20001       return SDValue(); // We combined away this shuffle.
20002
20003     break;
20004   }
20005
20006   return SDValue();
20007 }
20008
20009 /// PerformShuffleCombine - Performs several different shuffle combines.
20010 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20011                                      TargetLowering::DAGCombinerInfo &DCI,
20012                                      const X86Subtarget *Subtarget) {
20013   SDLoc dl(N);
20014   SDValue N0 = N->getOperand(0);
20015   SDValue N1 = N->getOperand(1);
20016   EVT VT = N->getValueType(0);
20017
20018   // Don't create instructions with illegal types after legalize types has run.
20019   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20020   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20021     return SDValue();
20022
20023   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20024   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20025       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20026     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20027
20028   // During Type Legalization, when promoting illegal vector types,
20029   // the backend might introduce new shuffle dag nodes and bitcasts.
20030   //
20031   // This code performs the following transformation:
20032   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20033   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20034   //
20035   // We do this only if both the bitcast and the BINOP dag nodes have
20036   // one use. Also, perform this transformation only if the new binary
20037   // operation is legal. This is to avoid introducing dag nodes that
20038   // potentially need to be further expanded (or custom lowered) into a
20039   // less optimal sequence of dag nodes.
20040   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20041       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20042       N0.getOpcode() == ISD::BITCAST) {
20043     SDValue BC0 = N0.getOperand(0);
20044     EVT SVT = BC0.getValueType();
20045     unsigned Opcode = BC0.getOpcode();
20046     unsigned NumElts = VT.getVectorNumElements();
20047     
20048     if (BC0.hasOneUse() && SVT.isVector() &&
20049         SVT.getVectorNumElements() * 2 == NumElts &&
20050         TLI.isOperationLegal(Opcode, VT)) {
20051       bool CanFold = false;
20052       switch (Opcode) {
20053       default : break;
20054       case ISD::ADD :
20055       case ISD::FADD :
20056       case ISD::SUB :
20057       case ISD::FSUB :
20058       case ISD::MUL :
20059       case ISD::FMUL :
20060         CanFold = true;
20061       }
20062
20063       unsigned SVTNumElts = SVT.getVectorNumElements();
20064       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20065       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20066         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20067       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20068         CanFold = SVOp->getMaskElt(i) < 0;
20069
20070       if (CanFold) {
20071         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20072         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20073         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20074         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20075       }
20076     }
20077   }
20078
20079   // Only handle 128 wide vector from here on.
20080   if (!VT.is128BitVector())
20081     return SDValue();
20082
20083   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20084   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20085   // consecutive, non-overlapping, and in the right order.
20086   SmallVector<SDValue, 16> Elts;
20087   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20088     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20089
20090   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20091   if (LD.getNode())
20092     return LD;
20093
20094   if (isTargetShuffle(N->getOpcode())) {
20095     SDValue Shuffle =
20096         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20097     if (Shuffle.getNode())
20098       return Shuffle;
20099
20100     // Try recursively combining arbitrary sequences of x86 shuffle
20101     // instructions into higher-order shuffles. We do this after combining
20102     // specific PSHUF instruction sequences into their minimal form so that we
20103     // can evaluate how many specialized shuffle instructions are involved in
20104     // a particular chain.
20105     SmallVector<int, 1> NonceMask; // Just a placeholder.
20106     NonceMask.push_back(0);
20107     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20108                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20109                                       DCI, Subtarget))
20110       return SDValue(); // This routine will use CombineTo to replace N.
20111   }
20112
20113   return SDValue();
20114 }
20115
20116 /// PerformTruncateCombine - Converts truncate operation to
20117 /// a sequence of vector shuffle operations.
20118 /// It is possible when we truncate 256-bit vector to 128-bit vector
20119 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20120                                       TargetLowering::DAGCombinerInfo &DCI,
20121                                       const X86Subtarget *Subtarget)  {
20122   return SDValue();
20123 }
20124
20125 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20126 /// specific shuffle of a load can be folded into a single element load.
20127 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20128 /// shuffles have been customed lowered so we need to handle those here.
20129 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20130                                          TargetLowering::DAGCombinerInfo &DCI) {
20131   if (DCI.isBeforeLegalizeOps())
20132     return SDValue();
20133
20134   SDValue InVec = N->getOperand(0);
20135   SDValue EltNo = N->getOperand(1);
20136
20137   if (!isa<ConstantSDNode>(EltNo))
20138     return SDValue();
20139
20140   EVT VT = InVec.getValueType();
20141
20142   bool HasShuffleIntoBitcast = false;
20143   if (InVec.getOpcode() == ISD::BITCAST) {
20144     // Don't duplicate a load with other uses.
20145     if (!InVec.hasOneUse())
20146       return SDValue();
20147     EVT BCVT = InVec.getOperand(0).getValueType();
20148     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
20149       return SDValue();
20150     InVec = InVec.getOperand(0);
20151     HasShuffleIntoBitcast = true;
20152   }
20153
20154   if (!isTargetShuffle(InVec.getOpcode()))
20155     return SDValue();
20156
20157   // Don't duplicate a load with other uses.
20158   if (!InVec.hasOneUse())
20159     return SDValue();
20160
20161   SmallVector<int, 16> ShuffleMask;
20162   bool UnaryShuffle;
20163   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
20164                             UnaryShuffle))
20165     return SDValue();
20166
20167   // Select the input vector, guarding against out of range extract vector.
20168   unsigned NumElems = VT.getVectorNumElements();
20169   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20170   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20171   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20172                                          : InVec.getOperand(1);
20173
20174   // If inputs to shuffle are the same for both ops, then allow 2 uses
20175   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20176
20177   if (LdNode.getOpcode() == ISD::BITCAST) {
20178     // Don't duplicate a load with other uses.
20179     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20180       return SDValue();
20181
20182     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20183     LdNode = LdNode.getOperand(0);
20184   }
20185
20186   if (!ISD::isNormalLoad(LdNode.getNode()))
20187     return SDValue();
20188
20189   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20190
20191   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20192     return SDValue();
20193
20194   if (HasShuffleIntoBitcast) {
20195     // If there's a bitcast before the shuffle, check if the load type and
20196     // alignment is valid.
20197     unsigned Align = LN0->getAlignment();
20198     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20199     unsigned NewAlign = TLI.getDataLayout()->
20200       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
20201
20202     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
20203       return SDValue();
20204   }
20205
20206   // All checks match so transform back to vector_shuffle so that DAG combiner
20207   // can finish the job
20208   SDLoc dl(N);
20209
20210   // Create shuffle node taking into account the case that its a unary shuffle
20211   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
20212   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
20213                                  InVec.getOperand(0), Shuffle,
20214                                  &ShuffleMask[0]);
20215   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
20216   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20217                      EltNo);
20218 }
20219
20220 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20221 /// generation and convert it from being a bunch of shuffles and extracts
20222 /// to a simple store and scalar loads to extract the elements.
20223 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20224                                          TargetLowering::DAGCombinerInfo &DCI) {
20225   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20226   if (NewOp.getNode())
20227     return NewOp;
20228
20229   SDValue InputVector = N->getOperand(0);
20230
20231   // Detect whether we are trying to convert from mmx to i32 and the bitcast
20232   // from mmx to v2i32 has a single usage.
20233   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
20234       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
20235       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
20236     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20237                        N->getValueType(0),
20238                        InputVector.getNode()->getOperand(0));
20239
20240   // Only operate on vectors of 4 elements, where the alternative shuffling
20241   // gets to be more expensive.
20242   if (InputVector.getValueType() != MVT::v4i32)
20243     return SDValue();
20244
20245   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20246   // single use which is a sign-extend or zero-extend, and all elements are
20247   // used.
20248   SmallVector<SDNode *, 4> Uses;
20249   unsigned ExtractedElements = 0;
20250   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20251        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20252     if (UI.getUse().getResNo() != InputVector.getResNo())
20253       return SDValue();
20254
20255     SDNode *Extract = *UI;
20256     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20257       return SDValue();
20258
20259     if (Extract->getValueType(0) != MVT::i32)
20260       return SDValue();
20261     if (!Extract->hasOneUse())
20262       return SDValue();
20263     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20264         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20265       return SDValue();
20266     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20267       return SDValue();
20268
20269     // Record which element was extracted.
20270     ExtractedElements |=
20271       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20272
20273     Uses.push_back(Extract);
20274   }
20275
20276   // If not all the elements were used, this may not be worthwhile.
20277   if (ExtractedElements != 15)
20278     return SDValue();
20279
20280   // Ok, we've now decided to do the transformation.
20281   SDLoc dl(InputVector);
20282
20283   // Store the value to a temporary stack slot.
20284   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20285   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20286                             MachinePointerInfo(), false, false, 0);
20287
20288   // Replace each use (extract) with a load of the appropriate element.
20289   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20290        UE = Uses.end(); UI != UE; ++UI) {
20291     SDNode *Extract = *UI;
20292
20293     // cOMpute the element's address.
20294     SDValue Idx = Extract->getOperand(1);
20295     unsigned EltSize =
20296         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
20297     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
20298     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20299     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20300
20301     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20302                                      StackPtr, OffsetVal);
20303
20304     // Load the scalar.
20305     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
20306                                      ScalarAddr, MachinePointerInfo(),
20307                                      false, false, false, 0);
20308
20309     // Replace the exact with the load.
20310     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
20311   }
20312
20313   // The replacement was made in place; don't return anything.
20314   return SDValue();
20315 }
20316
20317 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20318 static std::pair<unsigned, bool>
20319 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20320                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20321   if (!VT.isVector())
20322     return std::make_pair(0, false);
20323
20324   bool NeedSplit = false;
20325   switch (VT.getSimpleVT().SimpleTy) {
20326   default: return std::make_pair(0, false);
20327   case MVT::v32i8:
20328   case MVT::v16i16:
20329   case MVT::v8i32:
20330     if (!Subtarget->hasAVX2())
20331       NeedSplit = true;
20332     if (!Subtarget->hasAVX())
20333       return std::make_pair(0, false);
20334     break;
20335   case MVT::v16i8:
20336   case MVT::v8i16:
20337   case MVT::v4i32:
20338     if (!Subtarget->hasSSE2())
20339       return std::make_pair(0, false);
20340   }
20341
20342   // SSE2 has only a small subset of the operations.
20343   bool hasUnsigned = Subtarget->hasSSE41() ||
20344                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20345   bool hasSigned = Subtarget->hasSSE41() ||
20346                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20347
20348   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20349
20350   unsigned Opc = 0;
20351   // Check for x CC y ? x : y.
20352   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20353       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20354     switch (CC) {
20355     default: break;
20356     case ISD::SETULT:
20357     case ISD::SETULE:
20358       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20359     case ISD::SETUGT:
20360     case ISD::SETUGE:
20361       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20362     case ISD::SETLT:
20363     case ISD::SETLE:
20364       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20365     case ISD::SETGT:
20366     case ISD::SETGE:
20367       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20368     }
20369   // Check for x CC y ? y : x -- a min/max with reversed arms.
20370   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20371              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20372     switch (CC) {
20373     default: break;
20374     case ISD::SETULT:
20375     case ISD::SETULE:
20376       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20377     case ISD::SETUGT:
20378     case ISD::SETUGE:
20379       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20380     case ISD::SETLT:
20381     case ISD::SETLE:
20382       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20383     case ISD::SETGT:
20384     case ISD::SETGE:
20385       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20386     }
20387   }
20388
20389   return std::make_pair(Opc, NeedSplit);
20390 }
20391
20392 static SDValue
20393 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20394                                       const X86Subtarget *Subtarget) {
20395   SDLoc dl(N);
20396   SDValue Cond = N->getOperand(0);
20397   SDValue LHS = N->getOperand(1);
20398   SDValue RHS = N->getOperand(2);
20399
20400   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20401     SDValue CondSrc = Cond->getOperand(0);
20402     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20403       Cond = CondSrc->getOperand(0);
20404   }
20405
20406   MVT VT = N->getSimpleValueType(0);
20407   MVT EltVT = VT.getVectorElementType();
20408   unsigned NumElems = VT.getVectorNumElements();
20409   // There is no blend with immediate in AVX-512.
20410   if (VT.is512BitVector())
20411     return SDValue();
20412
20413   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
20414     return SDValue();
20415   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
20416     return SDValue();
20417
20418   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20419     return SDValue();
20420
20421   unsigned MaskValue = 0;
20422   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20423     return SDValue();
20424
20425   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20426   for (unsigned i = 0; i < NumElems; ++i) {
20427     // Be sure we emit undef where we can.
20428     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20429       ShuffleMask[i] = -1;
20430     else
20431       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20432   }
20433
20434   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20435 }
20436
20437 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20438 /// nodes.
20439 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20440                                     TargetLowering::DAGCombinerInfo &DCI,
20441                                     const X86Subtarget *Subtarget) {
20442   SDLoc DL(N);
20443   SDValue Cond = N->getOperand(0);
20444   // Get the LHS/RHS of the select.
20445   SDValue LHS = N->getOperand(1);
20446   SDValue RHS = N->getOperand(2);
20447   EVT VT = LHS.getValueType();
20448   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20449
20450   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20451   // instructions match the semantics of the common C idiom x<y?x:y but not
20452   // x<=y?x:y, because of how they handle negative zero (which can be
20453   // ignored in unsafe-math mode).
20454   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20455       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20456       (Subtarget->hasSSE2() ||
20457        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20458     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20459
20460     unsigned Opcode = 0;
20461     // Check for x CC y ? x : y.
20462     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20463         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20464       switch (CC) {
20465       default: break;
20466       case ISD::SETULT:
20467         // Converting this to a min would handle NaNs incorrectly, and swapping
20468         // the operands would cause it to handle comparisons between positive
20469         // and negative zero incorrectly.
20470         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20471           if (!DAG.getTarget().Options.UnsafeFPMath &&
20472               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20473             break;
20474           std::swap(LHS, RHS);
20475         }
20476         Opcode = X86ISD::FMIN;
20477         break;
20478       case ISD::SETOLE:
20479         // Converting this to a min would handle comparisons between positive
20480         // and negative zero incorrectly.
20481         if (!DAG.getTarget().Options.UnsafeFPMath &&
20482             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20483           break;
20484         Opcode = X86ISD::FMIN;
20485         break;
20486       case ISD::SETULE:
20487         // Converting this to a min would handle both negative zeros and NaNs
20488         // incorrectly, but we can swap the operands to fix both.
20489         std::swap(LHS, RHS);
20490       case ISD::SETOLT:
20491       case ISD::SETLT:
20492       case ISD::SETLE:
20493         Opcode = X86ISD::FMIN;
20494         break;
20495
20496       case ISD::SETOGE:
20497         // Converting this to a max would handle comparisons between positive
20498         // and negative zero incorrectly.
20499         if (!DAG.getTarget().Options.UnsafeFPMath &&
20500             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20501           break;
20502         Opcode = X86ISD::FMAX;
20503         break;
20504       case ISD::SETUGT:
20505         // Converting this to a max would handle NaNs incorrectly, and swapping
20506         // the operands would cause it to handle comparisons between positive
20507         // and negative zero incorrectly.
20508         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20509           if (!DAG.getTarget().Options.UnsafeFPMath &&
20510               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20511             break;
20512           std::swap(LHS, RHS);
20513         }
20514         Opcode = X86ISD::FMAX;
20515         break;
20516       case ISD::SETUGE:
20517         // Converting this to a max would handle both negative zeros and NaNs
20518         // incorrectly, but we can swap the operands to fix both.
20519         std::swap(LHS, RHS);
20520       case ISD::SETOGT:
20521       case ISD::SETGT:
20522       case ISD::SETGE:
20523         Opcode = X86ISD::FMAX;
20524         break;
20525       }
20526     // Check for x CC y ? y : x -- a min/max with reversed arms.
20527     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20528                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20529       switch (CC) {
20530       default: break;
20531       case ISD::SETOGE:
20532         // Converting this to a min would handle comparisons between positive
20533         // and negative zero incorrectly, and swapping the operands would
20534         // cause it to handle NaNs incorrectly.
20535         if (!DAG.getTarget().Options.UnsafeFPMath &&
20536             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20537           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20538             break;
20539           std::swap(LHS, RHS);
20540         }
20541         Opcode = X86ISD::FMIN;
20542         break;
20543       case ISD::SETUGT:
20544         // Converting this to a min would handle NaNs incorrectly.
20545         if (!DAG.getTarget().Options.UnsafeFPMath &&
20546             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20547           break;
20548         Opcode = X86ISD::FMIN;
20549         break;
20550       case ISD::SETUGE:
20551         // Converting this to a min would handle both negative zeros and NaNs
20552         // incorrectly, but we can swap the operands to fix both.
20553         std::swap(LHS, RHS);
20554       case ISD::SETOGT:
20555       case ISD::SETGT:
20556       case ISD::SETGE:
20557         Opcode = X86ISD::FMIN;
20558         break;
20559
20560       case ISD::SETULT:
20561         // Converting this to a max would handle NaNs incorrectly.
20562         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20563           break;
20564         Opcode = X86ISD::FMAX;
20565         break;
20566       case ISD::SETOLE:
20567         // Converting this to a max would handle comparisons between positive
20568         // and negative zero incorrectly, and swapping the operands would
20569         // cause it to handle NaNs incorrectly.
20570         if (!DAG.getTarget().Options.UnsafeFPMath &&
20571             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20572           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20573             break;
20574           std::swap(LHS, RHS);
20575         }
20576         Opcode = X86ISD::FMAX;
20577         break;
20578       case ISD::SETULE:
20579         // Converting this to a max would handle both negative zeros and NaNs
20580         // incorrectly, but we can swap the operands to fix both.
20581         std::swap(LHS, RHS);
20582       case ISD::SETOLT:
20583       case ISD::SETLT:
20584       case ISD::SETLE:
20585         Opcode = X86ISD::FMAX;
20586         break;
20587       }
20588     }
20589
20590     if (Opcode)
20591       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20592   }
20593
20594   EVT CondVT = Cond.getValueType();
20595   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20596       CondVT.getVectorElementType() == MVT::i1) {
20597     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20598     // lowering on AVX-512. In this case we convert it to
20599     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20600     // The same situation for all 128 and 256-bit vectors of i8 and i16
20601     EVT OpVT = LHS.getValueType();
20602     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20603         (OpVT.getVectorElementType() == MVT::i8 ||
20604          OpVT.getVectorElementType() == MVT::i16)) {
20605       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20606       DCI.AddToWorklist(Cond.getNode());
20607       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20608     }
20609   }
20610   // If this is a select between two integer constants, try to do some
20611   // optimizations.
20612   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20613     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20614       // Don't do this for crazy integer types.
20615       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20616         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20617         // so that TrueC (the true value) is larger than FalseC.
20618         bool NeedsCondInvert = false;
20619
20620         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20621             // Efficiently invertible.
20622             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20623              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20624               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20625           NeedsCondInvert = true;
20626           std::swap(TrueC, FalseC);
20627         }
20628
20629         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20630         if (FalseC->getAPIntValue() == 0 &&
20631             TrueC->getAPIntValue().isPowerOf2()) {
20632           if (NeedsCondInvert) // Invert the condition if needed.
20633             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20634                                DAG.getConstant(1, Cond.getValueType()));
20635
20636           // Zero extend the condition if needed.
20637           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20638
20639           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20640           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20641                              DAG.getConstant(ShAmt, MVT::i8));
20642         }
20643
20644         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20645         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20646           if (NeedsCondInvert) // Invert the condition if needed.
20647             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20648                                DAG.getConstant(1, Cond.getValueType()));
20649
20650           // Zero extend the condition if needed.
20651           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20652                              FalseC->getValueType(0), Cond);
20653           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20654                              SDValue(FalseC, 0));
20655         }
20656
20657         // Optimize cases that will turn into an LEA instruction.  This requires
20658         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20659         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20660           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20661           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20662
20663           bool isFastMultiplier = false;
20664           if (Diff < 10) {
20665             switch ((unsigned char)Diff) {
20666               default: break;
20667               case 1:  // result = add base, cond
20668               case 2:  // result = lea base(    , cond*2)
20669               case 3:  // result = lea base(cond, cond*2)
20670               case 4:  // result = lea base(    , cond*4)
20671               case 5:  // result = lea base(cond, cond*4)
20672               case 8:  // result = lea base(    , cond*8)
20673               case 9:  // result = lea base(cond, cond*8)
20674                 isFastMultiplier = true;
20675                 break;
20676             }
20677           }
20678
20679           if (isFastMultiplier) {
20680             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20681             if (NeedsCondInvert) // Invert the condition if needed.
20682               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20683                                  DAG.getConstant(1, Cond.getValueType()));
20684
20685             // Zero extend the condition if needed.
20686             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20687                                Cond);
20688             // Scale the condition by the difference.
20689             if (Diff != 1)
20690               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20691                                  DAG.getConstant(Diff, Cond.getValueType()));
20692
20693             // Add the base if non-zero.
20694             if (FalseC->getAPIntValue() != 0)
20695               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20696                                  SDValue(FalseC, 0));
20697             return Cond;
20698           }
20699         }
20700       }
20701   }
20702
20703   // Canonicalize max and min:
20704   // (x > y) ? x : y -> (x >= y) ? x : y
20705   // (x < y) ? x : y -> (x <= y) ? x : y
20706   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20707   // the need for an extra compare
20708   // against zero. e.g.
20709   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20710   // subl   %esi, %edi
20711   // testl  %edi, %edi
20712   // movl   $0, %eax
20713   // cmovgl %edi, %eax
20714   // =>
20715   // xorl   %eax, %eax
20716   // subl   %esi, $edi
20717   // cmovsl %eax, %edi
20718   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20719       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20720       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20721     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20722     switch (CC) {
20723     default: break;
20724     case ISD::SETLT:
20725     case ISD::SETGT: {
20726       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20727       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20728                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20729       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20730     }
20731     }
20732   }
20733
20734   // Early exit check
20735   if (!TLI.isTypeLegal(VT))
20736     return SDValue();
20737
20738   // Match VSELECTs into subs with unsigned saturation.
20739   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20740       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20741       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20742        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20743     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20744
20745     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20746     // left side invert the predicate to simplify logic below.
20747     SDValue Other;
20748     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20749       Other = RHS;
20750       CC = ISD::getSetCCInverse(CC, true);
20751     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20752       Other = LHS;
20753     }
20754
20755     if (Other.getNode() && Other->getNumOperands() == 2 &&
20756         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20757       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20758       SDValue CondRHS = Cond->getOperand(1);
20759
20760       // Look for a general sub with unsigned saturation first.
20761       // x >= y ? x-y : 0 --> subus x, y
20762       // x >  y ? x-y : 0 --> subus x, y
20763       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20764           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20765         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20766
20767       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20768         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20769           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20770             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20771               // If the RHS is a constant we have to reverse the const
20772               // canonicalization.
20773               // x > C-1 ? x+-C : 0 --> subus x, C
20774               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20775                   CondRHSConst->getAPIntValue() ==
20776                       (-OpRHSConst->getAPIntValue() - 1))
20777                 return DAG.getNode(
20778                     X86ISD::SUBUS, DL, VT, OpLHS,
20779                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20780
20781           // Another special case: If C was a sign bit, the sub has been
20782           // canonicalized into a xor.
20783           // FIXME: Would it be better to use computeKnownBits to determine
20784           //        whether it's safe to decanonicalize the xor?
20785           // x s< 0 ? x^C : 0 --> subus x, C
20786           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20787               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20788               OpRHSConst->getAPIntValue().isSignBit())
20789             // Note that we have to rebuild the RHS constant here to ensure we
20790             // don't rely on particular values of undef lanes.
20791             return DAG.getNode(
20792                 X86ISD::SUBUS, DL, VT, OpLHS,
20793                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20794         }
20795     }
20796   }
20797
20798   // Try to match a min/max vector operation.
20799   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20800     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20801     unsigned Opc = ret.first;
20802     bool NeedSplit = ret.second;
20803
20804     if (Opc && NeedSplit) {
20805       unsigned NumElems = VT.getVectorNumElements();
20806       // Extract the LHS vectors
20807       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20808       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20809
20810       // Extract the RHS vectors
20811       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20812       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20813
20814       // Create min/max for each subvector
20815       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20816       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20817
20818       // Merge the result
20819       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20820     } else if (Opc)
20821       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20822   }
20823
20824   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20825   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20826       // Check if SETCC has already been promoted
20827       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20828       // Check that condition value type matches vselect operand type
20829       CondVT == VT) { 
20830
20831     assert(Cond.getValueType().isVector() &&
20832            "vector select expects a vector selector!");
20833
20834     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20835     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20836
20837     if (!TValIsAllOnes && !FValIsAllZeros) {
20838       // Try invert the condition if true value is not all 1s and false value
20839       // is not all 0s.
20840       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20841       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20842
20843       if (TValIsAllZeros || FValIsAllOnes) {
20844         SDValue CC = Cond.getOperand(2);
20845         ISD::CondCode NewCC =
20846           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20847                                Cond.getOperand(0).getValueType().isInteger());
20848         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20849         std::swap(LHS, RHS);
20850         TValIsAllOnes = FValIsAllOnes;
20851         FValIsAllZeros = TValIsAllZeros;
20852       }
20853     }
20854
20855     if (TValIsAllOnes || FValIsAllZeros) {
20856       SDValue Ret;
20857
20858       if (TValIsAllOnes && FValIsAllZeros)
20859         Ret = Cond;
20860       else if (TValIsAllOnes)
20861         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20862                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20863       else if (FValIsAllZeros)
20864         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20865                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20866
20867       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20868     }
20869   }
20870
20871   // Try to fold this VSELECT into a MOVSS/MOVSD
20872   if (N->getOpcode() == ISD::VSELECT &&
20873       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20874     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20875         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20876       bool CanFold = false;
20877       unsigned NumElems = Cond.getNumOperands();
20878       SDValue A = LHS;
20879       SDValue B = RHS;
20880       
20881       if (isZero(Cond.getOperand(0))) {
20882         CanFold = true;
20883
20884         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20885         // fold (vselect <0,-1> -> (movsd A, B)
20886         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20887           CanFold = isAllOnes(Cond.getOperand(i));
20888       } else if (isAllOnes(Cond.getOperand(0))) {
20889         CanFold = true;
20890         std::swap(A, B);
20891
20892         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20893         // fold (vselect <-1,0> -> (movsd B, A)
20894         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20895           CanFold = isZero(Cond.getOperand(i));
20896       }
20897
20898       if (CanFold) {
20899         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20900           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20901         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20902       }
20903
20904       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20905         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20906         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20907         //                             (v2i64 (bitcast B)))))
20908         //
20909         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20910         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20911         //                             (v2f64 (bitcast B)))))
20912         //
20913         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20914         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20915         //                             (v2i64 (bitcast A)))))
20916         //
20917         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20918         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20919         //                             (v2f64 (bitcast A)))))
20920
20921         CanFold = (isZero(Cond.getOperand(0)) &&
20922                    isZero(Cond.getOperand(1)) &&
20923                    isAllOnes(Cond.getOperand(2)) &&
20924                    isAllOnes(Cond.getOperand(3)));
20925
20926         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20927             isAllOnes(Cond.getOperand(1)) &&
20928             isZero(Cond.getOperand(2)) &&
20929             isZero(Cond.getOperand(3))) {
20930           CanFold = true;
20931           std::swap(LHS, RHS);
20932         }
20933
20934         if (CanFold) {
20935           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20936           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20937           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20938           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20939                                                 NewB, DAG);
20940           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20941         }
20942       }
20943     }
20944   }
20945
20946   // If we know that this node is legal then we know that it is going to be
20947   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20948   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20949   // to simplify previous instructions.
20950   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20951       !DCI.isBeforeLegalize() &&
20952       // We explicitly check against v8i16 and v16i16 because, although
20953       // they're marked as Custom, they might only be legal when Cond is a
20954       // build_vector of constants. This will be taken care in a later
20955       // condition.
20956       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20957        VT != MVT::v8i16)) {
20958     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20959
20960     // Don't optimize vector selects that map to mask-registers.
20961     if (BitWidth == 1)
20962       return SDValue();
20963
20964     // Check all uses of that condition operand to check whether it will be
20965     // consumed by non-BLEND instructions, which may depend on all bits are set
20966     // properly.
20967     for (SDNode::use_iterator I = Cond->use_begin(),
20968                               E = Cond->use_end(); I != E; ++I)
20969       if (I->getOpcode() != ISD::VSELECT)
20970         // TODO: Add other opcodes eventually lowered into BLEND.
20971         return SDValue();
20972
20973     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20974     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20975
20976     APInt KnownZero, KnownOne;
20977     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20978                                           DCI.isBeforeLegalizeOps());
20979     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20980         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20981       DCI.CommitTargetLoweringOpt(TLO);
20982   }
20983
20984   // We should generate an X86ISD::BLENDI from a vselect if its argument
20985   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20986   // constants. This specific pattern gets generated when we split a
20987   // selector for a 512 bit vector in a machine without AVX512 (but with
20988   // 256-bit vectors), during legalization:
20989   //
20990   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20991   //
20992   // Iff we find this pattern and the build_vectors are built from
20993   // constants, we translate the vselect into a shuffle_vector that we
20994   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20995   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20996     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20997     if (Shuffle.getNode())
20998       return Shuffle;
20999   }
21000
21001   return SDValue();
21002 }
21003
21004 // Check whether a boolean test is testing a boolean value generated by
21005 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21006 // code.
21007 //
21008 // Simplify the following patterns:
21009 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21010 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21011 // to (Op EFLAGS Cond)
21012 //
21013 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21014 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21015 // to (Op EFLAGS !Cond)
21016 //
21017 // where Op could be BRCOND or CMOV.
21018 //
21019 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21020   // Quit if not CMP and SUB with its value result used.
21021   if (Cmp.getOpcode() != X86ISD::CMP &&
21022       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21023       return SDValue();
21024
21025   // Quit if not used as a boolean value.
21026   if (CC != X86::COND_E && CC != X86::COND_NE)
21027     return SDValue();
21028
21029   // Check CMP operands. One of them should be 0 or 1 and the other should be
21030   // an SetCC or extended from it.
21031   SDValue Op1 = Cmp.getOperand(0);
21032   SDValue Op2 = Cmp.getOperand(1);
21033
21034   SDValue SetCC;
21035   const ConstantSDNode* C = nullptr;
21036   bool needOppositeCond = (CC == X86::COND_E);
21037   bool checkAgainstTrue = false; // Is it a comparison against 1?
21038
21039   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21040     SetCC = Op2;
21041   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21042     SetCC = Op1;
21043   else // Quit if all operands are not constants.
21044     return SDValue();
21045
21046   if (C->getZExtValue() == 1) {
21047     needOppositeCond = !needOppositeCond;
21048     checkAgainstTrue = true;
21049   } else if (C->getZExtValue() != 0)
21050     // Quit if the constant is neither 0 or 1.
21051     return SDValue();
21052
21053   bool truncatedToBoolWithAnd = false;
21054   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21055   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21056          SetCC.getOpcode() == ISD::TRUNCATE ||
21057          SetCC.getOpcode() == ISD::AND) {
21058     if (SetCC.getOpcode() == ISD::AND) {
21059       int OpIdx = -1;
21060       ConstantSDNode *CS;
21061       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21062           CS->getZExtValue() == 1)
21063         OpIdx = 1;
21064       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21065           CS->getZExtValue() == 1)
21066         OpIdx = 0;
21067       if (OpIdx == -1)
21068         break;
21069       SetCC = SetCC.getOperand(OpIdx);
21070       truncatedToBoolWithAnd = true;
21071     } else
21072       SetCC = SetCC.getOperand(0);
21073   }
21074
21075   switch (SetCC.getOpcode()) {
21076   case X86ISD::SETCC_CARRY:
21077     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21078     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21079     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21080     // truncated to i1 using 'and'.
21081     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21082       break;
21083     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21084            "Invalid use of SETCC_CARRY!");
21085     // FALL THROUGH
21086   case X86ISD::SETCC:
21087     // Set the condition code or opposite one if necessary.
21088     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21089     if (needOppositeCond)
21090       CC = X86::GetOppositeBranchCondition(CC);
21091     return SetCC.getOperand(1);
21092   case X86ISD::CMOV: {
21093     // Check whether false/true value has canonical one, i.e. 0 or 1.
21094     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21095     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21096     // Quit if true value is not a constant.
21097     if (!TVal)
21098       return SDValue();
21099     // Quit if false value is not a constant.
21100     if (!FVal) {
21101       SDValue Op = SetCC.getOperand(0);
21102       // Skip 'zext' or 'trunc' node.
21103       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21104           Op.getOpcode() == ISD::TRUNCATE)
21105         Op = Op.getOperand(0);
21106       // A special case for rdrand/rdseed, where 0 is set if false cond is
21107       // found.
21108       if ((Op.getOpcode() != X86ISD::RDRAND &&
21109            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21110         return SDValue();
21111     }
21112     // Quit if false value is not the constant 0 or 1.
21113     bool FValIsFalse = true;
21114     if (FVal && FVal->getZExtValue() != 0) {
21115       if (FVal->getZExtValue() != 1)
21116         return SDValue();
21117       // If FVal is 1, opposite cond is needed.
21118       needOppositeCond = !needOppositeCond;
21119       FValIsFalse = false;
21120     }
21121     // Quit if TVal is not the constant opposite of FVal.
21122     if (FValIsFalse && TVal->getZExtValue() != 1)
21123       return SDValue();
21124     if (!FValIsFalse && TVal->getZExtValue() != 0)
21125       return SDValue();
21126     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21127     if (needOppositeCond)
21128       CC = X86::GetOppositeBranchCondition(CC);
21129     return SetCC.getOperand(3);
21130   }
21131   }
21132
21133   return SDValue();
21134 }
21135
21136 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21137 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21138                                   TargetLowering::DAGCombinerInfo &DCI,
21139                                   const X86Subtarget *Subtarget) {
21140   SDLoc DL(N);
21141
21142   // If the flag operand isn't dead, don't touch this CMOV.
21143   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21144     return SDValue();
21145
21146   SDValue FalseOp = N->getOperand(0);
21147   SDValue TrueOp = N->getOperand(1);
21148   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21149   SDValue Cond = N->getOperand(3);
21150
21151   if (CC == X86::COND_E || CC == X86::COND_NE) {
21152     switch (Cond.getOpcode()) {
21153     default: break;
21154     case X86ISD::BSR:
21155     case X86ISD::BSF:
21156       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21157       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21158         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21159     }
21160   }
21161
21162   SDValue Flags;
21163
21164   Flags = checkBoolTestSetCCCombine(Cond, CC);
21165   if (Flags.getNode() &&
21166       // Extra check as FCMOV only supports a subset of X86 cond.
21167       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21168     SDValue Ops[] = { FalseOp, TrueOp,
21169                       DAG.getConstant(CC, MVT::i8), Flags };
21170     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21171   }
21172
21173   // If this is a select between two integer constants, try to do some
21174   // optimizations.  Note that the operands are ordered the opposite of SELECT
21175   // operands.
21176   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21177     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21178       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21179       // larger than FalseC (the false value).
21180       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21181         CC = X86::GetOppositeBranchCondition(CC);
21182         std::swap(TrueC, FalseC);
21183         std::swap(TrueOp, FalseOp);
21184       }
21185
21186       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21187       // This is efficient for any integer data type (including i8/i16) and
21188       // shift amount.
21189       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21190         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21191                            DAG.getConstant(CC, MVT::i8), Cond);
21192
21193         // Zero extend the condition if needed.
21194         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21195
21196         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21197         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21198                            DAG.getConstant(ShAmt, MVT::i8));
21199         if (N->getNumValues() == 2)  // Dead flag value?
21200           return DCI.CombineTo(N, Cond, SDValue());
21201         return Cond;
21202       }
21203
21204       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21205       // for any integer data type, including i8/i16.
21206       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21207         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21208                            DAG.getConstant(CC, MVT::i8), Cond);
21209
21210         // Zero extend the condition if needed.
21211         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21212                            FalseC->getValueType(0), Cond);
21213         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21214                            SDValue(FalseC, 0));
21215
21216         if (N->getNumValues() == 2)  // Dead flag value?
21217           return DCI.CombineTo(N, Cond, SDValue());
21218         return Cond;
21219       }
21220
21221       // Optimize cases that will turn into an LEA instruction.  This requires
21222       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21223       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21224         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21225         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21226
21227         bool isFastMultiplier = false;
21228         if (Diff < 10) {
21229           switch ((unsigned char)Diff) {
21230           default: break;
21231           case 1:  // result = add base, cond
21232           case 2:  // result = lea base(    , cond*2)
21233           case 3:  // result = lea base(cond, cond*2)
21234           case 4:  // result = lea base(    , cond*4)
21235           case 5:  // result = lea base(cond, cond*4)
21236           case 8:  // result = lea base(    , cond*8)
21237           case 9:  // result = lea base(cond, cond*8)
21238             isFastMultiplier = true;
21239             break;
21240           }
21241         }
21242
21243         if (isFastMultiplier) {
21244           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21245           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21246                              DAG.getConstant(CC, MVT::i8), Cond);
21247           // Zero extend the condition if needed.
21248           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21249                              Cond);
21250           // Scale the condition by the difference.
21251           if (Diff != 1)
21252             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21253                                DAG.getConstant(Diff, Cond.getValueType()));
21254
21255           // Add the base if non-zero.
21256           if (FalseC->getAPIntValue() != 0)
21257             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21258                                SDValue(FalseC, 0));
21259           if (N->getNumValues() == 2)  // Dead flag value?
21260             return DCI.CombineTo(N, Cond, SDValue());
21261           return Cond;
21262         }
21263       }
21264     }
21265   }
21266
21267   // Handle these cases:
21268   //   (select (x != c), e, c) -> select (x != c), e, x),
21269   //   (select (x == c), c, e) -> select (x == c), x, e)
21270   // where the c is an integer constant, and the "select" is the combination
21271   // of CMOV and CMP.
21272   //
21273   // The rationale for this change is that the conditional-move from a constant
21274   // needs two instructions, however, conditional-move from a register needs
21275   // only one instruction.
21276   //
21277   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21278   //  some instruction-combining opportunities. This opt needs to be
21279   //  postponed as late as possible.
21280   //
21281   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21282     // the DCI.xxxx conditions are provided to postpone the optimization as
21283     // late as possible.
21284
21285     ConstantSDNode *CmpAgainst = nullptr;
21286     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21287         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21288         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21289
21290       if (CC == X86::COND_NE &&
21291           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21292         CC = X86::GetOppositeBranchCondition(CC);
21293         std::swap(TrueOp, FalseOp);
21294       }
21295
21296       if (CC == X86::COND_E &&
21297           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21298         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21299                           DAG.getConstant(CC, MVT::i8), Cond };
21300         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21301       }
21302     }
21303   }
21304
21305   return SDValue();
21306 }
21307
21308 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21309                                                 const X86Subtarget *Subtarget) {
21310   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21311   switch (IntNo) {
21312   default: return SDValue();
21313   // SSE/AVX/AVX2 blend intrinsics.
21314   case Intrinsic::x86_avx2_pblendvb:
21315   case Intrinsic::x86_avx2_pblendw:
21316   case Intrinsic::x86_avx2_pblendd_128:
21317   case Intrinsic::x86_avx2_pblendd_256:
21318     // Don't try to simplify this intrinsic if we don't have AVX2.
21319     if (!Subtarget->hasAVX2())
21320       return SDValue();
21321     // FALL-THROUGH
21322   case Intrinsic::x86_avx_blend_pd_256:
21323   case Intrinsic::x86_avx_blend_ps_256:
21324   case Intrinsic::x86_avx_blendv_pd_256:
21325   case Intrinsic::x86_avx_blendv_ps_256:
21326     // Don't try to simplify this intrinsic if we don't have AVX.
21327     if (!Subtarget->hasAVX())
21328       return SDValue();
21329     // FALL-THROUGH
21330   case Intrinsic::x86_sse41_pblendw:
21331   case Intrinsic::x86_sse41_blendpd:
21332   case Intrinsic::x86_sse41_blendps:
21333   case Intrinsic::x86_sse41_blendvps:
21334   case Intrinsic::x86_sse41_blendvpd:
21335   case Intrinsic::x86_sse41_pblendvb: {
21336     SDValue Op0 = N->getOperand(1);
21337     SDValue Op1 = N->getOperand(2);
21338     SDValue Mask = N->getOperand(3);
21339
21340     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21341     if (!Subtarget->hasSSE41())
21342       return SDValue();
21343
21344     // fold (blend A, A, Mask) -> A
21345     if (Op0 == Op1)
21346       return Op0;
21347     // fold (blend A, B, allZeros) -> A
21348     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21349       return Op0;
21350     // fold (blend A, B, allOnes) -> B
21351     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21352       return Op1;
21353     
21354     // Simplify the case where the mask is a constant i32 value.
21355     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21356       if (C->isNullValue())
21357         return Op0;
21358       if (C->isAllOnesValue())
21359         return Op1;
21360     }
21361
21362     return SDValue();
21363   }
21364
21365   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21366   case Intrinsic::x86_sse2_psrai_w:
21367   case Intrinsic::x86_sse2_psrai_d:
21368   case Intrinsic::x86_avx2_psrai_w:
21369   case Intrinsic::x86_avx2_psrai_d:
21370   case Intrinsic::x86_sse2_psra_w:
21371   case Intrinsic::x86_sse2_psra_d:
21372   case Intrinsic::x86_avx2_psra_w:
21373   case Intrinsic::x86_avx2_psra_d: {
21374     SDValue Op0 = N->getOperand(1);
21375     SDValue Op1 = N->getOperand(2);
21376     EVT VT = Op0.getValueType();
21377     assert(VT.isVector() && "Expected a vector type!");
21378
21379     if (isa<BuildVectorSDNode>(Op1))
21380       Op1 = Op1.getOperand(0);
21381
21382     if (!isa<ConstantSDNode>(Op1))
21383       return SDValue();
21384
21385     EVT SVT = VT.getVectorElementType();
21386     unsigned SVTBits = SVT.getSizeInBits();
21387
21388     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21389     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21390     uint64_t ShAmt = C.getZExtValue();
21391
21392     // Don't try to convert this shift into a ISD::SRA if the shift
21393     // count is bigger than or equal to the element size.
21394     if (ShAmt >= SVTBits)
21395       return SDValue();
21396
21397     // Trivial case: if the shift count is zero, then fold this
21398     // into the first operand.
21399     if (ShAmt == 0)
21400       return Op0;
21401
21402     // Replace this packed shift intrinsic with a target independent
21403     // shift dag node.
21404     SDValue Splat = DAG.getConstant(C, VT);
21405     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21406   }
21407   }
21408 }
21409
21410 /// PerformMulCombine - Optimize a single multiply with constant into two
21411 /// in order to implement it with two cheaper instructions, e.g.
21412 /// LEA + SHL, LEA + LEA.
21413 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21414                                  TargetLowering::DAGCombinerInfo &DCI) {
21415   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21416     return SDValue();
21417
21418   EVT VT = N->getValueType(0);
21419   if (VT != MVT::i64)
21420     return SDValue();
21421
21422   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21423   if (!C)
21424     return SDValue();
21425   uint64_t MulAmt = C->getZExtValue();
21426   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21427     return SDValue();
21428
21429   uint64_t MulAmt1 = 0;
21430   uint64_t MulAmt2 = 0;
21431   if ((MulAmt % 9) == 0) {
21432     MulAmt1 = 9;
21433     MulAmt2 = MulAmt / 9;
21434   } else if ((MulAmt % 5) == 0) {
21435     MulAmt1 = 5;
21436     MulAmt2 = MulAmt / 5;
21437   } else if ((MulAmt % 3) == 0) {
21438     MulAmt1 = 3;
21439     MulAmt2 = MulAmt / 3;
21440   }
21441   if (MulAmt2 &&
21442       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21443     SDLoc DL(N);
21444
21445     if (isPowerOf2_64(MulAmt2) &&
21446         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21447       // If second multiplifer is pow2, issue it first. We want the multiply by
21448       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21449       // is an add.
21450       std::swap(MulAmt1, MulAmt2);
21451
21452     SDValue NewMul;
21453     if (isPowerOf2_64(MulAmt1))
21454       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21455                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21456     else
21457       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21458                            DAG.getConstant(MulAmt1, VT));
21459
21460     if (isPowerOf2_64(MulAmt2))
21461       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21462                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21463     else
21464       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21465                            DAG.getConstant(MulAmt2, VT));
21466
21467     // Do not add new nodes to DAG combiner worklist.
21468     DCI.CombineTo(N, NewMul, false);
21469   }
21470   return SDValue();
21471 }
21472
21473 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21474   SDValue N0 = N->getOperand(0);
21475   SDValue N1 = N->getOperand(1);
21476   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21477   EVT VT = N0.getValueType();
21478
21479   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21480   // since the result of setcc_c is all zero's or all ones.
21481   if (VT.isInteger() && !VT.isVector() &&
21482       N1C && N0.getOpcode() == ISD::AND &&
21483       N0.getOperand(1).getOpcode() == ISD::Constant) {
21484     SDValue N00 = N0.getOperand(0);
21485     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21486         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21487           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21488          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21489       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21490       APInt ShAmt = N1C->getAPIntValue();
21491       Mask = Mask.shl(ShAmt);
21492       if (Mask != 0)
21493         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21494                            N00, DAG.getConstant(Mask, VT));
21495     }
21496   }
21497
21498   // Hardware support for vector shifts is sparse which makes us scalarize the
21499   // vector operations in many cases. Also, on sandybridge ADD is faster than
21500   // shl.
21501   // (shl V, 1) -> add V,V
21502   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21503     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21504       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21505       // We shift all of the values by one. In many cases we do not have
21506       // hardware support for this operation. This is better expressed as an ADD
21507       // of two values.
21508       if (N1SplatC->getZExtValue() == 1)
21509         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21510     }
21511
21512   return SDValue();
21513 }
21514
21515 /// \brief Returns a vector of 0s if the node in input is a vector logical
21516 /// shift by a constant amount which is known to be bigger than or equal
21517 /// to the vector element size in bits.
21518 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21519                                       const X86Subtarget *Subtarget) {
21520   EVT VT = N->getValueType(0);
21521
21522   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21523       (!Subtarget->hasInt256() ||
21524        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21525     return SDValue();
21526
21527   SDValue Amt = N->getOperand(1);
21528   SDLoc DL(N);
21529   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21530     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21531       APInt ShiftAmt = AmtSplat->getAPIntValue();
21532       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21533
21534       // SSE2/AVX2 logical shifts always return a vector of 0s
21535       // if the shift amount is bigger than or equal to
21536       // the element size. The constant shift amount will be
21537       // encoded as a 8-bit immediate.
21538       if (ShiftAmt.trunc(8).uge(MaxAmount))
21539         return getZeroVector(VT, Subtarget, DAG, DL);
21540     }
21541
21542   return SDValue();
21543 }
21544
21545 /// PerformShiftCombine - Combine shifts.
21546 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21547                                    TargetLowering::DAGCombinerInfo &DCI,
21548                                    const X86Subtarget *Subtarget) {
21549   if (N->getOpcode() == ISD::SHL) {
21550     SDValue V = PerformSHLCombine(N, DAG);
21551     if (V.getNode()) return V;
21552   }
21553
21554   if (N->getOpcode() != ISD::SRA) {
21555     // Try to fold this logical shift into a zero vector.
21556     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21557     if (V.getNode()) return V;
21558   }
21559
21560   return SDValue();
21561 }
21562
21563 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21564 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21565 // and friends.  Likewise for OR -> CMPNEQSS.
21566 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21567                             TargetLowering::DAGCombinerInfo &DCI,
21568                             const X86Subtarget *Subtarget) {
21569   unsigned opcode;
21570
21571   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21572   // we're requiring SSE2 for both.
21573   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21574     SDValue N0 = N->getOperand(0);
21575     SDValue N1 = N->getOperand(1);
21576     SDValue CMP0 = N0->getOperand(1);
21577     SDValue CMP1 = N1->getOperand(1);
21578     SDLoc DL(N);
21579
21580     // The SETCCs should both refer to the same CMP.
21581     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21582       return SDValue();
21583
21584     SDValue CMP00 = CMP0->getOperand(0);
21585     SDValue CMP01 = CMP0->getOperand(1);
21586     EVT     VT    = CMP00.getValueType();
21587
21588     if (VT == MVT::f32 || VT == MVT::f64) {
21589       bool ExpectingFlags = false;
21590       // Check for any users that want flags:
21591       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21592            !ExpectingFlags && UI != UE; ++UI)
21593         switch (UI->getOpcode()) {
21594         default:
21595         case ISD::BR_CC:
21596         case ISD::BRCOND:
21597         case ISD::SELECT:
21598           ExpectingFlags = true;
21599           break;
21600         case ISD::CopyToReg:
21601         case ISD::SIGN_EXTEND:
21602         case ISD::ZERO_EXTEND:
21603         case ISD::ANY_EXTEND:
21604           break;
21605         }
21606
21607       if (!ExpectingFlags) {
21608         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21609         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21610
21611         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21612           X86::CondCode tmp = cc0;
21613           cc0 = cc1;
21614           cc1 = tmp;
21615         }
21616
21617         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21618             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21619           // FIXME: need symbolic constants for these magic numbers.
21620           // See X86ATTInstPrinter.cpp:printSSECC().
21621           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21622           if (Subtarget->hasAVX512()) {
21623             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21624                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21625             if (N->getValueType(0) != MVT::i1)
21626               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21627                                  FSetCC);
21628             return FSetCC;
21629           }
21630           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21631                                               CMP00.getValueType(), CMP00, CMP01,
21632                                               DAG.getConstant(x86cc, MVT::i8));
21633
21634           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21635           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21636
21637           if (is64BitFP && !Subtarget->is64Bit()) {
21638             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21639             // 64-bit integer, since that's not a legal type. Since
21640             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21641             // bits, but can do this little dance to extract the lowest 32 bits
21642             // and work with those going forward.
21643             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21644                                            OnesOrZeroesF);
21645             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21646                                            Vector64);
21647             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21648                                         Vector32, DAG.getIntPtrConstant(0));
21649             IntVT = MVT::i32;
21650           }
21651
21652           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21653           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21654                                       DAG.getConstant(1, IntVT));
21655           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21656           return OneBitOfTruth;
21657         }
21658       }
21659     }
21660   }
21661   return SDValue();
21662 }
21663
21664 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21665 /// so it can be folded inside ANDNP.
21666 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21667   EVT VT = N->getValueType(0);
21668
21669   // Match direct AllOnes for 128 and 256-bit vectors
21670   if (ISD::isBuildVectorAllOnes(N))
21671     return true;
21672
21673   // Look through a bit convert.
21674   if (N->getOpcode() == ISD::BITCAST)
21675     N = N->getOperand(0).getNode();
21676
21677   // Sometimes the operand may come from a insert_subvector building a 256-bit
21678   // allones vector
21679   if (VT.is256BitVector() &&
21680       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21681     SDValue V1 = N->getOperand(0);
21682     SDValue V2 = N->getOperand(1);
21683
21684     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21685         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21686         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21687         ISD::isBuildVectorAllOnes(V2.getNode()))
21688       return true;
21689   }
21690
21691   return false;
21692 }
21693
21694 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21695 // register. In most cases we actually compare or select YMM-sized registers
21696 // and mixing the two types creates horrible code. This method optimizes
21697 // some of the transition sequences.
21698 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21699                                  TargetLowering::DAGCombinerInfo &DCI,
21700                                  const X86Subtarget *Subtarget) {
21701   EVT VT = N->getValueType(0);
21702   if (!VT.is256BitVector())
21703     return SDValue();
21704
21705   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21706           N->getOpcode() == ISD::ZERO_EXTEND ||
21707           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21708
21709   SDValue Narrow = N->getOperand(0);
21710   EVT NarrowVT = Narrow->getValueType(0);
21711   if (!NarrowVT.is128BitVector())
21712     return SDValue();
21713
21714   if (Narrow->getOpcode() != ISD::XOR &&
21715       Narrow->getOpcode() != ISD::AND &&
21716       Narrow->getOpcode() != ISD::OR)
21717     return SDValue();
21718
21719   SDValue N0  = Narrow->getOperand(0);
21720   SDValue N1  = Narrow->getOperand(1);
21721   SDLoc DL(Narrow);
21722
21723   // The Left side has to be a trunc.
21724   if (N0.getOpcode() != ISD::TRUNCATE)
21725     return SDValue();
21726
21727   // The type of the truncated inputs.
21728   EVT WideVT = N0->getOperand(0)->getValueType(0);
21729   if (WideVT != VT)
21730     return SDValue();
21731
21732   // The right side has to be a 'trunc' or a constant vector.
21733   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21734   ConstantSDNode *RHSConstSplat = nullptr;
21735   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21736     RHSConstSplat = RHSBV->getConstantSplatNode();
21737   if (!RHSTrunc && !RHSConstSplat)
21738     return SDValue();
21739
21740   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21741
21742   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21743     return SDValue();
21744
21745   // Set N0 and N1 to hold the inputs to the new wide operation.
21746   N0 = N0->getOperand(0);
21747   if (RHSConstSplat) {
21748     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21749                      SDValue(RHSConstSplat, 0));
21750     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21751     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21752   } else if (RHSTrunc) {
21753     N1 = N1->getOperand(0);
21754   }
21755
21756   // Generate the wide operation.
21757   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21758   unsigned Opcode = N->getOpcode();
21759   switch (Opcode) {
21760   case ISD::ANY_EXTEND:
21761     return Op;
21762   case ISD::ZERO_EXTEND: {
21763     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21764     APInt Mask = APInt::getAllOnesValue(InBits);
21765     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21766     return DAG.getNode(ISD::AND, DL, VT,
21767                        Op, DAG.getConstant(Mask, VT));
21768   }
21769   case ISD::SIGN_EXTEND:
21770     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21771                        Op, DAG.getValueType(NarrowVT));
21772   default:
21773     llvm_unreachable("Unexpected opcode");
21774   }
21775 }
21776
21777 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21778                                  TargetLowering::DAGCombinerInfo &DCI,
21779                                  const X86Subtarget *Subtarget) {
21780   EVT VT = N->getValueType(0);
21781   if (DCI.isBeforeLegalizeOps())
21782     return SDValue();
21783
21784   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21785   if (R.getNode())
21786     return R;
21787
21788   // Create BEXTR instructions
21789   // BEXTR is ((X >> imm) & (2**size-1))
21790   if (VT == MVT::i32 || VT == MVT::i64) {
21791     SDValue N0 = N->getOperand(0);
21792     SDValue N1 = N->getOperand(1);
21793     SDLoc DL(N);
21794
21795     // Check for BEXTR.
21796     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21797         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21798       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21799       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21800       if (MaskNode && ShiftNode) {
21801         uint64_t Mask = MaskNode->getZExtValue();
21802         uint64_t Shift = ShiftNode->getZExtValue();
21803         if (isMask_64(Mask)) {
21804           uint64_t MaskSize = CountPopulation_64(Mask);
21805           if (Shift + MaskSize <= VT.getSizeInBits())
21806             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21807                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21808         }
21809       }
21810     } // BEXTR
21811
21812     return SDValue();
21813   }
21814
21815   // Want to form ANDNP nodes:
21816   // 1) In the hopes of then easily combining them with OR and AND nodes
21817   //    to form PBLEND/PSIGN.
21818   // 2) To match ANDN packed intrinsics
21819   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21820     return SDValue();
21821
21822   SDValue N0 = N->getOperand(0);
21823   SDValue N1 = N->getOperand(1);
21824   SDLoc DL(N);
21825
21826   // Check LHS for vnot
21827   if (N0.getOpcode() == ISD::XOR &&
21828       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21829       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21830     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21831
21832   // Check RHS for vnot
21833   if (N1.getOpcode() == ISD::XOR &&
21834       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21835       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21836     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21837
21838   return SDValue();
21839 }
21840
21841 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21842                                 TargetLowering::DAGCombinerInfo &DCI,
21843                                 const X86Subtarget *Subtarget) {
21844   if (DCI.isBeforeLegalizeOps())
21845     return SDValue();
21846
21847   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21848   if (R.getNode())
21849     return R;
21850
21851   SDValue N0 = N->getOperand(0);
21852   SDValue N1 = N->getOperand(1);
21853   EVT VT = N->getValueType(0);
21854
21855   // look for psign/blend
21856   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21857     if (!Subtarget->hasSSSE3() ||
21858         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21859       return SDValue();
21860
21861     // Canonicalize pandn to RHS
21862     if (N0.getOpcode() == X86ISD::ANDNP)
21863       std::swap(N0, N1);
21864     // or (and (m, y), (pandn m, x))
21865     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21866       SDValue Mask = N1.getOperand(0);
21867       SDValue X    = N1.getOperand(1);
21868       SDValue Y;
21869       if (N0.getOperand(0) == Mask)
21870         Y = N0.getOperand(1);
21871       if (N0.getOperand(1) == Mask)
21872         Y = N0.getOperand(0);
21873
21874       // Check to see if the mask appeared in both the AND and ANDNP and
21875       if (!Y.getNode())
21876         return SDValue();
21877
21878       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21879       // Look through mask bitcast.
21880       if (Mask.getOpcode() == ISD::BITCAST)
21881         Mask = Mask.getOperand(0);
21882       if (X.getOpcode() == ISD::BITCAST)
21883         X = X.getOperand(0);
21884       if (Y.getOpcode() == ISD::BITCAST)
21885         Y = Y.getOperand(0);
21886
21887       EVT MaskVT = Mask.getValueType();
21888
21889       // Validate that the Mask operand is a vector sra node.
21890       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21891       // there is no psrai.b
21892       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21893       unsigned SraAmt = ~0;
21894       if (Mask.getOpcode() == ISD::SRA) {
21895         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21896           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21897             SraAmt = AmtConst->getZExtValue();
21898       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21899         SDValue SraC = Mask.getOperand(1);
21900         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21901       }
21902       if ((SraAmt + 1) != EltBits)
21903         return SDValue();
21904
21905       SDLoc DL(N);
21906
21907       // Now we know we at least have a plendvb with the mask val.  See if
21908       // we can form a psignb/w/d.
21909       // psign = x.type == y.type == mask.type && y = sub(0, x);
21910       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21911           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21912           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21913         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21914                "Unsupported VT for PSIGN");
21915         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21916         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21917       }
21918       // PBLENDVB only available on SSE 4.1
21919       if (!Subtarget->hasSSE41())
21920         return SDValue();
21921
21922       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21923
21924       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21925       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21926       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21927       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21928       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21929     }
21930   }
21931
21932   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21933     return SDValue();
21934
21935   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21936   MachineFunction &MF = DAG.getMachineFunction();
21937   bool OptForSize = MF.getFunction()->getAttributes().
21938     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21939
21940   // SHLD/SHRD instructions have lower register pressure, but on some
21941   // platforms they have higher latency than the equivalent
21942   // series of shifts/or that would otherwise be generated.
21943   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21944   // have higher latencies and we are not optimizing for size.
21945   if (!OptForSize && Subtarget->isSHLDSlow())
21946     return SDValue();
21947
21948   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21949     std::swap(N0, N1);
21950   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21951     return SDValue();
21952   if (!N0.hasOneUse() || !N1.hasOneUse())
21953     return SDValue();
21954
21955   SDValue ShAmt0 = N0.getOperand(1);
21956   if (ShAmt0.getValueType() != MVT::i8)
21957     return SDValue();
21958   SDValue ShAmt1 = N1.getOperand(1);
21959   if (ShAmt1.getValueType() != MVT::i8)
21960     return SDValue();
21961   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21962     ShAmt0 = ShAmt0.getOperand(0);
21963   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21964     ShAmt1 = ShAmt1.getOperand(0);
21965
21966   SDLoc DL(N);
21967   unsigned Opc = X86ISD::SHLD;
21968   SDValue Op0 = N0.getOperand(0);
21969   SDValue Op1 = N1.getOperand(0);
21970   if (ShAmt0.getOpcode() == ISD::SUB) {
21971     Opc = X86ISD::SHRD;
21972     std::swap(Op0, Op1);
21973     std::swap(ShAmt0, ShAmt1);
21974   }
21975
21976   unsigned Bits = VT.getSizeInBits();
21977   if (ShAmt1.getOpcode() == ISD::SUB) {
21978     SDValue Sum = ShAmt1.getOperand(0);
21979     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21980       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21981       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21982         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21983       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21984         return DAG.getNode(Opc, DL, VT,
21985                            Op0, Op1,
21986                            DAG.getNode(ISD::TRUNCATE, DL,
21987                                        MVT::i8, ShAmt0));
21988     }
21989   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21990     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21991     if (ShAmt0C &&
21992         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21993       return DAG.getNode(Opc, DL, VT,
21994                          N0.getOperand(0), N1.getOperand(0),
21995                          DAG.getNode(ISD::TRUNCATE, DL,
21996                                        MVT::i8, ShAmt0));
21997   }
21998
21999   return SDValue();
22000 }
22001
22002 // Generate NEG and CMOV for integer abs.
22003 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22004   EVT VT = N->getValueType(0);
22005
22006   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22007   // 8-bit integer abs to NEG and CMOV.
22008   if (VT.isInteger() && VT.getSizeInBits() == 8)
22009     return SDValue();
22010
22011   SDValue N0 = N->getOperand(0);
22012   SDValue N1 = N->getOperand(1);
22013   SDLoc DL(N);
22014
22015   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22016   // and change it to SUB and CMOV.
22017   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22018       N0.getOpcode() == ISD::ADD &&
22019       N0.getOperand(1) == N1 &&
22020       N1.getOpcode() == ISD::SRA &&
22021       N1.getOperand(0) == N0.getOperand(0))
22022     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22023       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22024         // Generate SUB & CMOV.
22025         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22026                                   DAG.getConstant(0, VT), N0.getOperand(0));
22027
22028         SDValue Ops[] = { N0.getOperand(0), Neg,
22029                           DAG.getConstant(X86::COND_GE, MVT::i8),
22030                           SDValue(Neg.getNode(), 1) };
22031         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22032       }
22033   return SDValue();
22034 }
22035
22036 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22037 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22038                                  TargetLowering::DAGCombinerInfo &DCI,
22039                                  const X86Subtarget *Subtarget) {
22040   if (DCI.isBeforeLegalizeOps())
22041     return SDValue();
22042
22043   if (Subtarget->hasCMov()) {
22044     SDValue RV = performIntegerAbsCombine(N, DAG);
22045     if (RV.getNode())
22046       return RV;
22047   }
22048
22049   return SDValue();
22050 }
22051
22052 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22053 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22054                                   TargetLowering::DAGCombinerInfo &DCI,
22055                                   const X86Subtarget *Subtarget) {
22056   LoadSDNode *Ld = cast<LoadSDNode>(N);
22057   EVT RegVT = Ld->getValueType(0);
22058   EVT MemVT = Ld->getMemoryVT();
22059   SDLoc dl(Ld);
22060   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22061
22062   // On Sandybridge unaligned 256bit loads are inefficient.
22063   ISD::LoadExtType Ext = Ld->getExtensionType();
22064   unsigned Alignment = Ld->getAlignment();
22065   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22066   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
22067       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22068     unsigned NumElems = RegVT.getVectorNumElements();
22069     if (NumElems < 2)
22070       return SDValue();
22071
22072     SDValue Ptr = Ld->getBasePtr();
22073     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22074
22075     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22076                                   NumElems/2);
22077     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22078                                 Ld->getPointerInfo(), Ld->isVolatile(),
22079                                 Ld->isNonTemporal(), Ld->isInvariant(),
22080                                 Alignment);
22081     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22082     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22083                                 Ld->getPointerInfo(), Ld->isVolatile(),
22084                                 Ld->isNonTemporal(), Ld->isInvariant(),
22085                                 std::min(16U, Alignment));
22086     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22087                              Load1.getValue(1),
22088                              Load2.getValue(1));
22089
22090     SDValue NewVec = DAG.getUNDEF(RegVT);
22091     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22092     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22093     return DCI.CombineTo(N, NewVec, TF, true);
22094   }
22095
22096   return SDValue();
22097 }
22098
22099 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22100 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22101                                    const X86Subtarget *Subtarget) {
22102   StoreSDNode *St = cast<StoreSDNode>(N);
22103   EVT VT = St->getValue().getValueType();
22104   EVT StVT = St->getMemoryVT();
22105   SDLoc dl(St);
22106   SDValue StoredVal = St->getOperand(1);
22107   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22108
22109   // If we are saving a concatenation of two XMM registers, perform two stores.
22110   // On Sandy Bridge, 256-bit memory operations are executed by two
22111   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
22112   // memory  operation.
22113   unsigned Alignment = St->getAlignment();
22114   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22115   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
22116       StVT == VT && !IsAligned) {
22117     unsigned NumElems = VT.getVectorNumElements();
22118     if (NumElems < 2)
22119       return SDValue();
22120
22121     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22122     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22123
22124     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22125     SDValue Ptr0 = St->getBasePtr();
22126     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22127
22128     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22129                                 St->getPointerInfo(), St->isVolatile(),
22130                                 St->isNonTemporal(), Alignment);
22131     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22132                                 St->getPointerInfo(), St->isVolatile(),
22133                                 St->isNonTemporal(),
22134                                 std::min(16U, Alignment));
22135     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22136   }
22137
22138   // Optimize trunc store (of multiple scalars) to shuffle and store.
22139   // First, pack all of the elements in one place. Next, store to memory
22140   // in fewer chunks.
22141   if (St->isTruncatingStore() && VT.isVector()) {
22142     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22143     unsigned NumElems = VT.getVectorNumElements();
22144     assert(StVT != VT && "Cannot truncate to the same type");
22145     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22146     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22147
22148     // From, To sizes and ElemCount must be pow of two
22149     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22150     // We are going to use the original vector elt for storing.
22151     // Accumulated smaller vector elements must be a multiple of the store size.
22152     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22153
22154     unsigned SizeRatio  = FromSz / ToSz;
22155
22156     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22157
22158     // Create a type on which we perform the shuffle
22159     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22160             StVT.getScalarType(), NumElems*SizeRatio);
22161
22162     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22163
22164     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22165     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22166     for (unsigned i = 0; i != NumElems; ++i)
22167       ShuffleVec[i] = i * SizeRatio;
22168
22169     // Can't shuffle using an illegal type.
22170     if (!TLI.isTypeLegal(WideVecVT))
22171       return SDValue();
22172
22173     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22174                                          DAG.getUNDEF(WideVecVT),
22175                                          &ShuffleVec[0]);
22176     // At this point all of the data is stored at the bottom of the
22177     // register. We now need to save it to mem.
22178
22179     // Find the largest store unit
22180     MVT StoreType = MVT::i8;
22181     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
22182          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
22183       MVT Tp = (MVT::SimpleValueType)tp;
22184       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22185         StoreType = Tp;
22186     }
22187
22188     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22189     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22190         (64 <= NumElems * ToSz))
22191       StoreType = MVT::f64;
22192
22193     // Bitcast the original vector into a vector of store-size units
22194     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22195             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22196     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22197     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22198     SmallVector<SDValue, 8> Chains;
22199     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22200                                         TLI.getPointerTy());
22201     SDValue Ptr = St->getBasePtr();
22202
22203     // Perform one or more big stores into memory.
22204     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22205       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22206                                    StoreType, ShuffWide,
22207                                    DAG.getIntPtrConstant(i));
22208       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22209                                 St->getPointerInfo(), St->isVolatile(),
22210                                 St->isNonTemporal(), St->getAlignment());
22211       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22212       Chains.push_back(Ch);
22213     }
22214
22215     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22216   }
22217
22218   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
22219   // the FP state in cases where an emms may be missing.
22220   // A preferable solution to the general problem is to figure out the right
22221   // places to insert EMMS.  This qualifies as a quick hack.
22222
22223   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22224   if (VT.getSizeInBits() != 64)
22225     return SDValue();
22226
22227   const Function *F = DAG.getMachineFunction().getFunction();
22228   bool NoImplicitFloatOps = F->getAttributes().
22229     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
22230   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22231                      && Subtarget->hasSSE2();
22232   if ((VT.isVector() ||
22233        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22234       isa<LoadSDNode>(St->getValue()) &&
22235       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22236       St->getChain().hasOneUse() && !St->isVolatile()) {
22237     SDNode* LdVal = St->getValue().getNode();
22238     LoadSDNode *Ld = nullptr;
22239     int TokenFactorIndex = -1;
22240     SmallVector<SDValue, 8> Ops;
22241     SDNode* ChainVal = St->getChain().getNode();
22242     // Must be a store of a load.  We currently handle two cases:  the load
22243     // is a direct child, and it's under an intervening TokenFactor.  It is
22244     // possible to dig deeper under nested TokenFactors.
22245     if (ChainVal == LdVal)
22246       Ld = cast<LoadSDNode>(St->getChain());
22247     else if (St->getValue().hasOneUse() &&
22248              ChainVal->getOpcode() == ISD::TokenFactor) {
22249       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22250         if (ChainVal->getOperand(i).getNode() == LdVal) {
22251           TokenFactorIndex = i;
22252           Ld = cast<LoadSDNode>(St->getValue());
22253         } else
22254           Ops.push_back(ChainVal->getOperand(i));
22255       }
22256     }
22257
22258     if (!Ld || !ISD::isNormalLoad(Ld))
22259       return SDValue();
22260
22261     // If this is not the MMX case, i.e. we are just turning i64 load/store
22262     // into f64 load/store, avoid the transformation if there are multiple
22263     // uses of the loaded value.
22264     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22265       return SDValue();
22266
22267     SDLoc LdDL(Ld);
22268     SDLoc StDL(N);
22269     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22270     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22271     // pair instead.
22272     if (Subtarget->is64Bit() || F64IsLegal) {
22273       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22274       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22275                                   Ld->getPointerInfo(), Ld->isVolatile(),
22276                                   Ld->isNonTemporal(), Ld->isInvariant(),
22277                                   Ld->getAlignment());
22278       SDValue NewChain = NewLd.getValue(1);
22279       if (TokenFactorIndex != -1) {
22280         Ops.push_back(NewChain);
22281         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22282       }
22283       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22284                           St->getPointerInfo(),
22285                           St->isVolatile(), St->isNonTemporal(),
22286                           St->getAlignment());
22287     }
22288
22289     // Otherwise, lower to two pairs of 32-bit loads / stores.
22290     SDValue LoAddr = Ld->getBasePtr();
22291     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22292                                  DAG.getConstant(4, MVT::i32));
22293
22294     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22295                                Ld->getPointerInfo(),
22296                                Ld->isVolatile(), Ld->isNonTemporal(),
22297                                Ld->isInvariant(), Ld->getAlignment());
22298     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22299                                Ld->getPointerInfo().getWithOffset(4),
22300                                Ld->isVolatile(), Ld->isNonTemporal(),
22301                                Ld->isInvariant(),
22302                                MinAlign(Ld->getAlignment(), 4));
22303
22304     SDValue NewChain = LoLd.getValue(1);
22305     if (TokenFactorIndex != -1) {
22306       Ops.push_back(LoLd);
22307       Ops.push_back(HiLd);
22308       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22309     }
22310
22311     LoAddr = St->getBasePtr();
22312     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22313                          DAG.getConstant(4, MVT::i32));
22314
22315     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22316                                 St->getPointerInfo(),
22317                                 St->isVolatile(), St->isNonTemporal(),
22318                                 St->getAlignment());
22319     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22320                                 St->getPointerInfo().getWithOffset(4),
22321                                 St->isVolatile(),
22322                                 St->isNonTemporal(),
22323                                 MinAlign(St->getAlignment(), 4));
22324     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22325   }
22326   return SDValue();
22327 }
22328
22329 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
22330 /// and return the operands for the horizontal operation in LHS and RHS.  A
22331 /// horizontal operation performs the binary operation on successive elements
22332 /// of its first operand, then on successive elements of its second operand,
22333 /// returning the resulting values in a vector.  For example, if
22334 ///   A = < float a0, float a1, float a2, float a3 >
22335 /// and
22336 ///   B = < float b0, float b1, float b2, float b3 >
22337 /// then the result of doing a horizontal operation on A and B is
22338 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22339 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22340 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22341 /// set to A, RHS to B, and the routine returns 'true'.
22342 /// Note that the binary operation should have the property that if one of the
22343 /// operands is UNDEF then the result is UNDEF.
22344 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22345   // Look for the following pattern: if
22346   //   A = < float a0, float a1, float a2, float a3 >
22347   //   B = < float b0, float b1, float b2, float b3 >
22348   // and
22349   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22350   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22351   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22352   // which is A horizontal-op B.
22353
22354   // At least one of the operands should be a vector shuffle.
22355   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22356       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22357     return false;
22358
22359   MVT VT = LHS.getSimpleValueType();
22360
22361   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22362          "Unsupported vector type for horizontal add/sub");
22363
22364   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22365   // operate independently on 128-bit lanes.
22366   unsigned NumElts = VT.getVectorNumElements();
22367   unsigned NumLanes = VT.getSizeInBits()/128;
22368   unsigned NumLaneElts = NumElts / NumLanes;
22369   assert((NumLaneElts % 2 == 0) &&
22370          "Vector type should have an even number of elements in each lane");
22371   unsigned HalfLaneElts = NumLaneElts/2;
22372
22373   // View LHS in the form
22374   //   LHS = VECTOR_SHUFFLE A, B, LMask
22375   // If LHS is not a shuffle then pretend it is the shuffle
22376   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22377   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22378   // type VT.
22379   SDValue A, B;
22380   SmallVector<int, 16> LMask(NumElts);
22381   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22382     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22383       A = LHS.getOperand(0);
22384     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22385       B = LHS.getOperand(1);
22386     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22387     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22388   } else {
22389     if (LHS.getOpcode() != ISD::UNDEF)
22390       A = LHS;
22391     for (unsigned i = 0; i != NumElts; ++i)
22392       LMask[i] = i;
22393   }
22394
22395   // Likewise, view RHS in the form
22396   //   RHS = VECTOR_SHUFFLE C, D, RMask
22397   SDValue C, D;
22398   SmallVector<int, 16> RMask(NumElts);
22399   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22400     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22401       C = RHS.getOperand(0);
22402     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22403       D = RHS.getOperand(1);
22404     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22405     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22406   } else {
22407     if (RHS.getOpcode() != ISD::UNDEF)
22408       C = RHS;
22409     for (unsigned i = 0; i != NumElts; ++i)
22410       RMask[i] = i;
22411   }
22412
22413   // Check that the shuffles are both shuffling the same vectors.
22414   if (!(A == C && B == D) && !(A == D && B == C))
22415     return false;
22416
22417   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22418   if (!A.getNode() && !B.getNode())
22419     return false;
22420
22421   // If A and B occur in reverse order in RHS, then "swap" them (which means
22422   // rewriting the mask).
22423   if (A != C)
22424     CommuteVectorShuffleMask(RMask, NumElts);
22425
22426   // At this point LHS and RHS are equivalent to
22427   //   LHS = VECTOR_SHUFFLE A, B, LMask
22428   //   RHS = VECTOR_SHUFFLE A, B, RMask
22429   // Check that the masks correspond to performing a horizontal operation.
22430   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22431     for (unsigned i = 0; i != NumLaneElts; ++i) {
22432       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22433
22434       // Ignore any UNDEF components.
22435       if (LIdx < 0 || RIdx < 0 ||
22436           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22437           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22438         continue;
22439
22440       // Check that successive elements are being operated on.  If not, this is
22441       // not a horizontal operation.
22442       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22443       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22444       if (!(LIdx == Index && RIdx == Index + 1) &&
22445           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22446         return false;
22447     }
22448   }
22449
22450   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22451   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22452   return true;
22453 }
22454
22455 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22456 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22457                                   const X86Subtarget *Subtarget) {
22458   EVT VT = N->getValueType(0);
22459   SDValue LHS = N->getOperand(0);
22460   SDValue RHS = N->getOperand(1);
22461
22462   // Try to synthesize horizontal adds from adds of shuffles.
22463   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22464        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22465       isHorizontalBinOp(LHS, RHS, true))
22466     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22467   return SDValue();
22468 }
22469
22470 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22471 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22472                                   const X86Subtarget *Subtarget) {
22473   EVT VT = N->getValueType(0);
22474   SDValue LHS = N->getOperand(0);
22475   SDValue RHS = N->getOperand(1);
22476
22477   // Try to synthesize horizontal subs from subs of shuffles.
22478   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22479        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22480       isHorizontalBinOp(LHS, RHS, false))
22481     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22482   return SDValue();
22483 }
22484
22485 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22486 /// X86ISD::FXOR nodes.
22487 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22488   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22489   // F[X]OR(0.0, x) -> x
22490   // F[X]OR(x, 0.0) -> x
22491   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22492     if (C->getValueAPF().isPosZero())
22493       return N->getOperand(1);
22494   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22495     if (C->getValueAPF().isPosZero())
22496       return N->getOperand(0);
22497   return SDValue();
22498 }
22499
22500 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22501 /// X86ISD::FMAX nodes.
22502 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22503   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22504
22505   // Only perform optimizations if UnsafeMath is used.
22506   if (!DAG.getTarget().Options.UnsafeFPMath)
22507     return SDValue();
22508
22509   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22510   // into FMINC and FMAXC, which are Commutative operations.
22511   unsigned NewOp = 0;
22512   switch (N->getOpcode()) {
22513     default: llvm_unreachable("unknown opcode");
22514     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22515     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22516   }
22517
22518   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22519                      N->getOperand(0), N->getOperand(1));
22520 }
22521
22522 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22523 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22524   // FAND(0.0, x) -> 0.0
22525   // FAND(x, 0.0) -> 0.0
22526   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22527     if (C->getValueAPF().isPosZero())
22528       return N->getOperand(0);
22529   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22530     if (C->getValueAPF().isPosZero())
22531       return N->getOperand(1);
22532   return SDValue();
22533 }
22534
22535 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22536 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22537   // FANDN(x, 0.0) -> 0.0
22538   // FANDN(0.0, x) -> x
22539   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22540     if (C->getValueAPF().isPosZero())
22541       return N->getOperand(1);
22542   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22543     if (C->getValueAPF().isPosZero())
22544       return N->getOperand(1);
22545   return SDValue();
22546 }
22547
22548 static SDValue PerformBTCombine(SDNode *N,
22549                                 SelectionDAG &DAG,
22550                                 TargetLowering::DAGCombinerInfo &DCI) {
22551   // BT ignores high bits in the bit index operand.
22552   SDValue Op1 = N->getOperand(1);
22553   if (Op1.hasOneUse()) {
22554     unsigned BitWidth = Op1.getValueSizeInBits();
22555     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22556     APInt KnownZero, KnownOne;
22557     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22558                                           !DCI.isBeforeLegalizeOps());
22559     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22560     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22561         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22562       DCI.CommitTargetLoweringOpt(TLO);
22563   }
22564   return SDValue();
22565 }
22566
22567 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22568   SDValue Op = N->getOperand(0);
22569   if (Op.getOpcode() == ISD::BITCAST)
22570     Op = Op.getOperand(0);
22571   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22572   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22573       VT.getVectorElementType().getSizeInBits() ==
22574       OpVT.getVectorElementType().getSizeInBits()) {
22575     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22576   }
22577   return SDValue();
22578 }
22579
22580 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22581                                                const X86Subtarget *Subtarget) {
22582   EVT VT = N->getValueType(0);
22583   if (!VT.isVector())
22584     return SDValue();
22585
22586   SDValue N0 = N->getOperand(0);
22587   SDValue N1 = N->getOperand(1);
22588   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22589   SDLoc dl(N);
22590
22591   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22592   // both SSE and AVX2 since there is no sign-extended shift right
22593   // operation on a vector with 64-bit elements.
22594   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22595   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22596   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22597       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22598     SDValue N00 = N0.getOperand(0);
22599
22600     // EXTLOAD has a better solution on AVX2,
22601     // it may be replaced with X86ISD::VSEXT node.
22602     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22603       if (!ISD::isNormalLoad(N00.getNode()))
22604         return SDValue();
22605
22606     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22607         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22608                                   N00, N1);
22609       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22610     }
22611   }
22612   return SDValue();
22613 }
22614
22615 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22616                                   TargetLowering::DAGCombinerInfo &DCI,
22617                                   const X86Subtarget *Subtarget) {
22618   if (!DCI.isBeforeLegalizeOps())
22619     return SDValue();
22620
22621   if (!Subtarget->hasFp256())
22622     return SDValue();
22623
22624   EVT VT = N->getValueType(0);
22625   if (VT.isVector() && VT.getSizeInBits() == 256) {
22626     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22627     if (R.getNode())
22628       return R;
22629   }
22630
22631   return SDValue();
22632 }
22633
22634 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22635                                  const X86Subtarget* Subtarget) {
22636   SDLoc dl(N);
22637   EVT VT = N->getValueType(0);
22638
22639   // Let legalize expand this if it isn't a legal type yet.
22640   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22641     return SDValue();
22642
22643   EVT ScalarVT = VT.getScalarType();
22644   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22645       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22646     return SDValue();
22647
22648   SDValue A = N->getOperand(0);
22649   SDValue B = N->getOperand(1);
22650   SDValue C = N->getOperand(2);
22651
22652   bool NegA = (A.getOpcode() == ISD::FNEG);
22653   bool NegB = (B.getOpcode() == ISD::FNEG);
22654   bool NegC = (C.getOpcode() == ISD::FNEG);
22655
22656   // Negative multiplication when NegA xor NegB
22657   bool NegMul = (NegA != NegB);
22658   if (NegA)
22659     A = A.getOperand(0);
22660   if (NegB)
22661     B = B.getOperand(0);
22662   if (NegC)
22663     C = C.getOperand(0);
22664
22665   unsigned Opcode;
22666   if (!NegMul)
22667     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22668   else
22669     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22670
22671   return DAG.getNode(Opcode, dl, VT, A, B, C);
22672 }
22673
22674 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22675                                   TargetLowering::DAGCombinerInfo &DCI,
22676                                   const X86Subtarget *Subtarget) {
22677   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22678   //           (and (i32 x86isd::setcc_carry), 1)
22679   // This eliminates the zext. This transformation is necessary because
22680   // ISD::SETCC is always legalized to i8.
22681   SDLoc dl(N);
22682   SDValue N0 = N->getOperand(0);
22683   EVT VT = N->getValueType(0);
22684
22685   if (N0.getOpcode() == ISD::AND &&
22686       N0.hasOneUse() &&
22687       N0.getOperand(0).hasOneUse()) {
22688     SDValue N00 = N0.getOperand(0);
22689     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22690       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22691       if (!C || C->getZExtValue() != 1)
22692         return SDValue();
22693       return DAG.getNode(ISD::AND, dl, VT,
22694                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22695                                      N00.getOperand(0), N00.getOperand(1)),
22696                          DAG.getConstant(1, VT));
22697     }
22698   }
22699
22700   if (N0.getOpcode() == ISD::TRUNCATE &&
22701       N0.hasOneUse() &&
22702       N0.getOperand(0).hasOneUse()) {
22703     SDValue N00 = N0.getOperand(0);
22704     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22705       return DAG.getNode(ISD::AND, dl, VT,
22706                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22707                                      N00.getOperand(0), N00.getOperand(1)),
22708                          DAG.getConstant(1, VT));
22709     }
22710   }
22711   if (VT.is256BitVector()) {
22712     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22713     if (R.getNode())
22714       return R;
22715   }
22716
22717   return SDValue();
22718 }
22719
22720 // Optimize x == -y --> x+y == 0
22721 //          x != -y --> x+y != 0
22722 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22723                                       const X86Subtarget* Subtarget) {
22724   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22725   SDValue LHS = N->getOperand(0);
22726   SDValue RHS = N->getOperand(1);
22727   EVT VT = N->getValueType(0);
22728   SDLoc DL(N);
22729
22730   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22731     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22732       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22733         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22734                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22735         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22736                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22737       }
22738   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22739     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22740       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22741         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22742                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22743         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22744                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22745       }
22746
22747   if (VT.getScalarType() == MVT::i1) {
22748     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22749       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22750     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22751     if (!IsSEXT0 && !IsVZero0)
22752       return SDValue();
22753     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22754       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22755     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22756
22757     if (!IsSEXT1 && !IsVZero1)
22758       return SDValue();
22759
22760     if (IsSEXT0 && IsVZero1) {
22761       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22762       if (CC == ISD::SETEQ)
22763         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22764       return LHS.getOperand(0);
22765     }
22766     if (IsSEXT1 && IsVZero0) {
22767       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22768       if (CC == ISD::SETEQ)
22769         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22770       return RHS.getOperand(0);
22771     }
22772   }
22773
22774   return SDValue();
22775 }
22776
22777 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22778                                       const X86Subtarget *Subtarget) {
22779   SDLoc dl(N);
22780   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22781   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22782          "X86insertps is only defined for v4x32");
22783
22784   SDValue Ld = N->getOperand(1);
22785   if (MayFoldLoad(Ld)) {
22786     // Extract the countS bits from the immediate so we can get the proper
22787     // address when narrowing the vector load to a specific element.
22788     // When the second source op is a memory address, interps doesn't use
22789     // countS and just gets an f32 from that address.
22790     unsigned DestIndex =
22791         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22792     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22793   } else
22794     return SDValue();
22795
22796   // Create this as a scalar to vector to match the instruction pattern.
22797   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22798   // countS bits are ignored when loading from memory on insertps, which
22799   // means we don't need to explicitly set them to 0.
22800   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22801                      LoadScalarToVector, N->getOperand(2));
22802 }
22803
22804 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22805 // as "sbb reg,reg", since it can be extended without zext and produces
22806 // an all-ones bit which is more useful than 0/1 in some cases.
22807 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22808                                MVT VT) {
22809   if (VT == MVT::i8)
22810     return DAG.getNode(ISD::AND, DL, VT,
22811                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22812                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22813                        DAG.getConstant(1, VT));
22814   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22815   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22816                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22817                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22818 }
22819
22820 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22821 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22822                                    TargetLowering::DAGCombinerInfo &DCI,
22823                                    const X86Subtarget *Subtarget) {
22824   SDLoc DL(N);
22825   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22826   SDValue EFLAGS = N->getOperand(1);
22827
22828   if (CC == X86::COND_A) {
22829     // Try to convert COND_A into COND_B in an attempt to facilitate
22830     // materializing "setb reg".
22831     //
22832     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22833     // cannot take an immediate as its first operand.
22834     //
22835     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22836         EFLAGS.getValueType().isInteger() &&
22837         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22838       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22839                                    EFLAGS.getNode()->getVTList(),
22840                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22841       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22842       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22843     }
22844   }
22845
22846   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22847   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22848   // cases.
22849   if (CC == X86::COND_B)
22850     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22851
22852   SDValue Flags;
22853
22854   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22855   if (Flags.getNode()) {
22856     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22857     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22858   }
22859
22860   return SDValue();
22861 }
22862
22863 // Optimize branch condition evaluation.
22864 //
22865 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22866                                     TargetLowering::DAGCombinerInfo &DCI,
22867                                     const X86Subtarget *Subtarget) {
22868   SDLoc DL(N);
22869   SDValue Chain = N->getOperand(0);
22870   SDValue Dest = N->getOperand(1);
22871   SDValue EFLAGS = N->getOperand(3);
22872   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22873
22874   SDValue Flags;
22875
22876   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22877   if (Flags.getNode()) {
22878     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22879     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22880                        Flags);
22881   }
22882
22883   return SDValue();
22884 }
22885
22886 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22887                                                          SelectionDAG &DAG) {
22888   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22889   // optimize away operation when it's from a constant.
22890   //
22891   // The general transformation is:
22892   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22893   //       AND(VECTOR_CMP(x,y), constant2)
22894   //    constant2 = UNARYOP(constant)
22895
22896   // Early exit if this isn't a vector operation, the operand of the
22897   // unary operation isn't a bitwise AND, or if the sizes of the operations
22898   // aren't the same.
22899   EVT VT = N->getValueType(0);
22900   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22901       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22902       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22903     return SDValue();
22904
22905   // Now check that the other operand of the AND is a constant. We could
22906   // make the transformation for non-constant splats as well, but it's unclear
22907   // that would be a benefit as it would not eliminate any operations, just
22908   // perform one more step in scalar code before moving to the vector unit.
22909   if (BuildVectorSDNode *BV =
22910           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22911     // Bail out if the vector isn't a constant.
22912     if (!BV->isConstant())
22913       return SDValue();
22914
22915     // Everything checks out. Build up the new and improved node.
22916     SDLoc DL(N);
22917     EVT IntVT = BV->getValueType(0);
22918     // Create a new constant of the appropriate type for the transformed
22919     // DAG.
22920     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22921     // The AND node needs bitcasts to/from an integer vector type around it.
22922     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22923     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22924                                  N->getOperand(0)->getOperand(0), MaskConst);
22925     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22926     return Res;
22927   }
22928
22929   return SDValue();
22930 }
22931
22932 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22933                                         const X86TargetLowering *XTLI) {
22934   // First try to optimize away the conversion entirely when it's
22935   // conditionally from a constant. Vectors only.
22936   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22937   if (Res != SDValue())
22938     return Res;
22939
22940   // Now move on to more general possibilities.
22941   SDValue Op0 = N->getOperand(0);
22942   EVT InVT = Op0->getValueType(0);
22943
22944   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22945   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22946     SDLoc dl(N);
22947     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22948     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22949     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22950   }
22951
22952   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22953   // a 32-bit target where SSE doesn't support i64->FP operations.
22954   if (Op0.getOpcode() == ISD::LOAD) {
22955     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22956     EVT VT = Ld->getValueType(0);
22957     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22958         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22959         !XTLI->getSubtarget()->is64Bit() &&
22960         VT == MVT::i64) {
22961       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22962                                           Ld->getChain(), Op0, DAG);
22963       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22964       return FILDChain;
22965     }
22966   }
22967   return SDValue();
22968 }
22969
22970 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22971 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22972                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22973   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22974   // the result is either zero or one (depending on the input carry bit).
22975   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22976   if (X86::isZeroNode(N->getOperand(0)) &&
22977       X86::isZeroNode(N->getOperand(1)) &&
22978       // We don't have a good way to replace an EFLAGS use, so only do this when
22979       // dead right now.
22980       SDValue(N, 1).use_empty()) {
22981     SDLoc DL(N);
22982     EVT VT = N->getValueType(0);
22983     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22984     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22985                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22986                                            DAG.getConstant(X86::COND_B,MVT::i8),
22987                                            N->getOperand(2)),
22988                                DAG.getConstant(1, VT));
22989     return DCI.CombineTo(N, Res1, CarryOut);
22990   }
22991
22992   return SDValue();
22993 }
22994
22995 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22996 //      (add Y, (setne X, 0)) -> sbb -1, Y
22997 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22998 //      (sub (setne X, 0), Y) -> adc -1, Y
22999 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23000   SDLoc DL(N);
23001
23002   // Look through ZExts.
23003   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23004   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23005     return SDValue();
23006
23007   SDValue SetCC = Ext.getOperand(0);
23008   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23009     return SDValue();
23010
23011   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23012   if (CC != X86::COND_E && CC != X86::COND_NE)
23013     return SDValue();
23014
23015   SDValue Cmp = SetCC.getOperand(1);
23016   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23017       !X86::isZeroNode(Cmp.getOperand(1)) ||
23018       !Cmp.getOperand(0).getValueType().isInteger())
23019     return SDValue();
23020
23021   SDValue CmpOp0 = Cmp.getOperand(0);
23022   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23023                                DAG.getConstant(1, CmpOp0.getValueType()));
23024
23025   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23026   if (CC == X86::COND_NE)
23027     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23028                        DL, OtherVal.getValueType(), OtherVal,
23029                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23030   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23031                      DL, OtherVal.getValueType(), OtherVal,
23032                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23033 }
23034
23035 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23036 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23037                                  const X86Subtarget *Subtarget) {
23038   EVT VT = N->getValueType(0);
23039   SDValue Op0 = N->getOperand(0);
23040   SDValue Op1 = N->getOperand(1);
23041
23042   // Try to synthesize horizontal adds from adds of shuffles.
23043   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23044        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23045       isHorizontalBinOp(Op0, Op1, true))
23046     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23047
23048   return OptimizeConditionalInDecrement(N, DAG);
23049 }
23050
23051 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23052                                  const X86Subtarget *Subtarget) {
23053   SDValue Op0 = N->getOperand(0);
23054   SDValue Op1 = N->getOperand(1);
23055
23056   // X86 can't encode an immediate LHS of a sub. See if we can push the
23057   // negation into a preceding instruction.
23058   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23059     // If the RHS of the sub is a XOR with one use and a constant, invert the
23060     // immediate. Then add one to the LHS of the sub so we can turn
23061     // X-Y -> X+~Y+1, saving one register.
23062     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23063         isa<ConstantSDNode>(Op1.getOperand(1))) {
23064       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23065       EVT VT = Op0.getValueType();
23066       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23067                                    Op1.getOperand(0),
23068                                    DAG.getConstant(~XorC, VT));
23069       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23070                          DAG.getConstant(C->getAPIntValue()+1, VT));
23071     }
23072   }
23073
23074   // Try to synthesize horizontal adds from adds of shuffles.
23075   EVT VT = N->getValueType(0);
23076   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23077        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23078       isHorizontalBinOp(Op0, Op1, true))
23079     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23080
23081   return OptimizeConditionalInDecrement(N, DAG);
23082 }
23083
23084 /// performVZEXTCombine - Performs build vector combines
23085 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23086                                         TargetLowering::DAGCombinerInfo &DCI,
23087                                         const X86Subtarget *Subtarget) {
23088   // (vzext (bitcast (vzext (x)) -> (vzext x)
23089   SDValue In = N->getOperand(0);
23090   while (In.getOpcode() == ISD::BITCAST)
23091     In = In.getOperand(0);
23092
23093   if (In.getOpcode() != X86ISD::VZEXT)
23094     return SDValue();
23095
23096   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
23097                      In.getOperand(0));
23098 }
23099
23100 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23101                                              DAGCombinerInfo &DCI) const {
23102   SelectionDAG &DAG = DCI.DAG;
23103   switch (N->getOpcode()) {
23104   default: break;
23105   case ISD::EXTRACT_VECTOR_ELT:
23106     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23107   case ISD::VSELECT:
23108   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23109   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23110   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
23111   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
23112   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
23113   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
23114   case ISD::SHL:
23115   case ISD::SRA:
23116   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
23117   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
23118   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
23119   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
23120   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
23121   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
23122   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
23123   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
23124   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
23125   case X86ISD::FXOR:
23126   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
23127   case X86ISD::FMIN:
23128   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
23129   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
23130   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
23131   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
23132   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
23133   case ISD::ANY_EXTEND:
23134   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
23135   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
23136   case ISD::SIGN_EXTEND_INREG:
23137     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23138   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23139   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
23140   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23141   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23142   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
23143   case X86ISD::SHUFP:       // Handle all target specific shuffles
23144   case X86ISD::PALIGNR:
23145   case X86ISD::UNPCKH:
23146   case X86ISD::UNPCKL:
23147   case X86ISD::MOVHLPS:
23148   case X86ISD::MOVLHPS:
23149   case X86ISD::PSHUFB:
23150   case X86ISD::PSHUFD:
23151   case X86ISD::PSHUFHW:
23152   case X86ISD::PSHUFLW:
23153   case X86ISD::MOVSS:
23154   case X86ISD::MOVSD:
23155   case X86ISD::VPERMILP:
23156   case X86ISD::VPERM2X128:
23157   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23158   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
23159   case ISD::INTRINSIC_WO_CHAIN:
23160     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23161   case X86ISD::INSERTPS:
23162     return PerformINSERTPSCombine(N, DAG, Subtarget);
23163   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23164   }
23165
23166   return SDValue();
23167 }
23168
23169 /// isTypeDesirableForOp - Return true if the target has native support for
23170 /// the specified value type and it is 'desirable' to use the type for the
23171 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23172 /// instruction encodings are longer and some i16 instructions are slow.
23173 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23174   if (!isTypeLegal(VT))
23175     return false;
23176   if (VT != MVT::i16)
23177     return true;
23178
23179   switch (Opc) {
23180   default:
23181     return true;
23182   case ISD::LOAD:
23183   case ISD::SIGN_EXTEND:
23184   case ISD::ZERO_EXTEND:
23185   case ISD::ANY_EXTEND:
23186   case ISD::SHL:
23187   case ISD::SRL:
23188   case ISD::SUB:
23189   case ISD::ADD:
23190   case ISD::MUL:
23191   case ISD::AND:
23192   case ISD::OR:
23193   case ISD::XOR:
23194     return false;
23195   }
23196 }
23197
23198 /// IsDesirableToPromoteOp - This method query the target whether it is
23199 /// beneficial for dag combiner to promote the specified node. If true, it
23200 /// should return the desired promotion type by reference.
23201 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23202   EVT VT = Op.getValueType();
23203   if (VT != MVT::i16)
23204     return false;
23205
23206   bool Promote = false;
23207   bool Commute = false;
23208   switch (Op.getOpcode()) {
23209   default: break;
23210   case ISD::LOAD: {
23211     LoadSDNode *LD = cast<LoadSDNode>(Op);
23212     // If the non-extending load has a single use and it's not live out, then it
23213     // might be folded.
23214     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23215                                                      Op.hasOneUse()*/) {
23216       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23217              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23218         // The only case where we'd want to promote LOAD (rather then it being
23219         // promoted as an operand is when it's only use is liveout.
23220         if (UI->getOpcode() != ISD::CopyToReg)
23221           return false;
23222       }
23223     }
23224     Promote = true;
23225     break;
23226   }
23227   case ISD::SIGN_EXTEND:
23228   case ISD::ZERO_EXTEND:
23229   case ISD::ANY_EXTEND:
23230     Promote = true;
23231     break;
23232   case ISD::SHL:
23233   case ISD::SRL: {
23234     SDValue N0 = Op.getOperand(0);
23235     // Look out for (store (shl (load), x)).
23236     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23237       return false;
23238     Promote = true;
23239     break;
23240   }
23241   case ISD::ADD:
23242   case ISD::MUL:
23243   case ISD::AND:
23244   case ISD::OR:
23245   case ISD::XOR:
23246     Commute = true;
23247     // fallthrough
23248   case ISD::SUB: {
23249     SDValue N0 = Op.getOperand(0);
23250     SDValue N1 = Op.getOperand(1);
23251     if (!Commute && MayFoldLoad(N1))
23252       return false;
23253     // Avoid disabling potential load folding opportunities.
23254     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23255       return false;
23256     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23257       return false;
23258     Promote = true;
23259   }
23260   }
23261
23262   PVT = MVT::i32;
23263   return Promote;
23264 }
23265
23266 //===----------------------------------------------------------------------===//
23267 //                           X86 Inline Assembly Support
23268 //===----------------------------------------------------------------------===//
23269
23270 namespace {
23271   // Helper to match a string separated by whitespace.
23272   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
23273     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
23274
23275     for (unsigned i = 0, e = args.size(); i != e; ++i) {
23276       StringRef piece(*args[i]);
23277       if (!s.startswith(piece)) // Check if the piece matches.
23278         return false;
23279
23280       s = s.substr(piece.size());
23281       StringRef::size_type pos = s.find_first_not_of(" \t");
23282       if (pos == 0) // We matched a prefix.
23283         return false;
23284
23285       s = s.substr(pos);
23286     }
23287
23288     return s.empty();
23289   }
23290   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
23291 }
23292
23293 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23294
23295   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23296     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23297         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23298         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23299
23300       if (AsmPieces.size() == 3)
23301         return true;
23302       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23303         return true;
23304     }
23305   }
23306   return false;
23307 }
23308
23309 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23310   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23311
23312   std::string AsmStr = IA->getAsmString();
23313
23314   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23315   if (!Ty || Ty->getBitWidth() % 16 != 0)
23316     return false;
23317
23318   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23319   SmallVector<StringRef, 4> AsmPieces;
23320   SplitString(AsmStr, AsmPieces, ";\n");
23321
23322   switch (AsmPieces.size()) {
23323   default: return false;
23324   case 1:
23325     // FIXME: this should verify that we are targeting a 486 or better.  If not,
23326     // we will turn this bswap into something that will be lowered to logical
23327     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
23328     // lower so don't worry about this.
23329     // bswap $0
23330     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
23331         matchAsm(AsmPieces[0], "bswapl", "$0") ||
23332         matchAsm(AsmPieces[0], "bswapq", "$0") ||
23333         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
23334         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
23335         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
23336       // No need to check constraints, nothing other than the equivalent of
23337       // "=r,0" would be valid here.
23338       return IntrinsicLowering::LowerToByteSwap(CI);
23339     }
23340
23341     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
23342     if (CI->getType()->isIntegerTy(16) &&
23343         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23344         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
23345          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23346       AsmPieces.clear();
23347       const std::string &ConstraintsStr = IA->getConstraintString();
23348       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23349       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23350       if (clobbersFlagRegisters(AsmPieces))
23351         return IntrinsicLowering::LowerToByteSwap(CI);
23352     }
23353     break;
23354   case 3:
23355     if (CI->getType()->isIntegerTy(32) &&
23356         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23357         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23358         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23359         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23360       AsmPieces.clear();
23361       const std::string &ConstraintsStr = IA->getConstraintString();
23362       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23363       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23364       if (clobbersFlagRegisters(AsmPieces))
23365         return IntrinsicLowering::LowerToByteSwap(CI);
23366     }
23367
23368     if (CI->getType()->isIntegerTy(64)) {
23369       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23370       if (Constraints.size() >= 2 &&
23371           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23372           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23373         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
23374         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23375             matchAsm(AsmPieces[1], "bswap", "%edx") &&
23376             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23377           return IntrinsicLowering::LowerToByteSwap(CI);
23378       }
23379     }
23380     break;
23381   }
23382   return false;
23383 }
23384
23385 /// getConstraintType - Given a constraint letter, return the type of
23386 /// constraint it is for this target.
23387 X86TargetLowering::ConstraintType
23388 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23389   if (Constraint.size() == 1) {
23390     switch (Constraint[0]) {
23391     case 'R':
23392     case 'q':
23393     case 'Q':
23394     case 'f':
23395     case 't':
23396     case 'u':
23397     case 'y':
23398     case 'x':
23399     case 'Y':
23400     case 'l':
23401       return C_RegisterClass;
23402     case 'a':
23403     case 'b':
23404     case 'c':
23405     case 'd':
23406     case 'S':
23407     case 'D':
23408     case 'A':
23409       return C_Register;
23410     case 'I':
23411     case 'J':
23412     case 'K':
23413     case 'L':
23414     case 'M':
23415     case 'N':
23416     case 'G':
23417     case 'C':
23418     case 'e':
23419     case 'Z':
23420       return C_Other;
23421     default:
23422       break;
23423     }
23424   }
23425   return TargetLowering::getConstraintType(Constraint);
23426 }
23427
23428 /// Examine constraint type and operand type and determine a weight value.
23429 /// This object must already have been set up with the operand type
23430 /// and the current alternative constraint selected.
23431 TargetLowering::ConstraintWeight
23432   X86TargetLowering::getSingleConstraintMatchWeight(
23433     AsmOperandInfo &info, const char *constraint) const {
23434   ConstraintWeight weight = CW_Invalid;
23435   Value *CallOperandVal = info.CallOperandVal;
23436     // If we don't have a value, we can't do a match,
23437     // but allow it at the lowest weight.
23438   if (!CallOperandVal)
23439     return CW_Default;
23440   Type *type = CallOperandVal->getType();
23441   // Look at the constraint type.
23442   switch (*constraint) {
23443   default:
23444     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23445   case 'R':
23446   case 'q':
23447   case 'Q':
23448   case 'a':
23449   case 'b':
23450   case 'c':
23451   case 'd':
23452   case 'S':
23453   case 'D':
23454   case 'A':
23455     if (CallOperandVal->getType()->isIntegerTy())
23456       weight = CW_SpecificReg;
23457     break;
23458   case 'f':
23459   case 't':
23460   case 'u':
23461     if (type->isFloatingPointTy())
23462       weight = CW_SpecificReg;
23463     break;
23464   case 'y':
23465     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23466       weight = CW_SpecificReg;
23467     break;
23468   case 'x':
23469   case 'Y':
23470     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23471         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23472       weight = CW_Register;
23473     break;
23474   case 'I':
23475     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23476       if (C->getZExtValue() <= 31)
23477         weight = CW_Constant;
23478     }
23479     break;
23480   case 'J':
23481     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23482       if (C->getZExtValue() <= 63)
23483         weight = CW_Constant;
23484     }
23485     break;
23486   case 'K':
23487     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23488       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23489         weight = CW_Constant;
23490     }
23491     break;
23492   case 'L':
23493     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23494       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23495         weight = CW_Constant;
23496     }
23497     break;
23498   case 'M':
23499     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23500       if (C->getZExtValue() <= 3)
23501         weight = CW_Constant;
23502     }
23503     break;
23504   case 'N':
23505     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23506       if (C->getZExtValue() <= 0xff)
23507         weight = CW_Constant;
23508     }
23509     break;
23510   case 'G':
23511   case 'C':
23512     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23513       weight = CW_Constant;
23514     }
23515     break;
23516   case 'e':
23517     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23518       if ((C->getSExtValue() >= -0x80000000LL) &&
23519           (C->getSExtValue() <= 0x7fffffffLL))
23520         weight = CW_Constant;
23521     }
23522     break;
23523   case 'Z':
23524     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23525       if (C->getZExtValue() <= 0xffffffff)
23526         weight = CW_Constant;
23527     }
23528     break;
23529   }
23530   return weight;
23531 }
23532
23533 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23534 /// with another that has more specific requirements based on the type of the
23535 /// corresponding operand.
23536 const char *X86TargetLowering::
23537 LowerXConstraint(EVT ConstraintVT) const {
23538   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23539   // 'f' like normal targets.
23540   if (ConstraintVT.isFloatingPoint()) {
23541     if (Subtarget->hasSSE2())
23542       return "Y";
23543     if (Subtarget->hasSSE1())
23544       return "x";
23545   }
23546
23547   return TargetLowering::LowerXConstraint(ConstraintVT);
23548 }
23549
23550 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23551 /// vector.  If it is invalid, don't add anything to Ops.
23552 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23553                                                      std::string &Constraint,
23554                                                      std::vector<SDValue>&Ops,
23555                                                      SelectionDAG &DAG) const {
23556   SDValue Result;
23557
23558   // Only support length 1 constraints for now.
23559   if (Constraint.length() > 1) return;
23560
23561   char ConstraintLetter = Constraint[0];
23562   switch (ConstraintLetter) {
23563   default: break;
23564   case 'I':
23565     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23566       if (C->getZExtValue() <= 31) {
23567         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23568         break;
23569       }
23570     }
23571     return;
23572   case 'J':
23573     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23574       if (C->getZExtValue() <= 63) {
23575         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23576         break;
23577       }
23578     }
23579     return;
23580   case 'K':
23581     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23582       if (isInt<8>(C->getSExtValue())) {
23583         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23584         break;
23585       }
23586     }
23587     return;
23588   case 'N':
23589     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23590       if (C->getZExtValue() <= 255) {
23591         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23592         break;
23593       }
23594     }
23595     return;
23596   case 'e': {
23597     // 32-bit signed value
23598     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23599       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23600                                            C->getSExtValue())) {
23601         // Widen to 64 bits here to get it sign extended.
23602         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23603         break;
23604       }
23605     // FIXME gcc accepts some relocatable values here too, but only in certain
23606     // memory models; it's complicated.
23607     }
23608     return;
23609   }
23610   case 'Z': {
23611     // 32-bit unsigned value
23612     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23613       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23614                                            C->getZExtValue())) {
23615         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23616         break;
23617       }
23618     }
23619     // FIXME gcc accepts some relocatable values here too, but only in certain
23620     // memory models; it's complicated.
23621     return;
23622   }
23623   case 'i': {
23624     // Literal immediates are always ok.
23625     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23626       // Widen to 64 bits here to get it sign extended.
23627       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23628       break;
23629     }
23630
23631     // In any sort of PIC mode addresses need to be computed at runtime by
23632     // adding in a register or some sort of table lookup.  These can't
23633     // be used as immediates.
23634     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23635       return;
23636
23637     // If we are in non-pic codegen mode, we allow the address of a global (with
23638     // an optional displacement) to be used with 'i'.
23639     GlobalAddressSDNode *GA = nullptr;
23640     int64_t Offset = 0;
23641
23642     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23643     while (1) {
23644       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23645         Offset += GA->getOffset();
23646         break;
23647       } else if (Op.getOpcode() == ISD::ADD) {
23648         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23649           Offset += C->getZExtValue();
23650           Op = Op.getOperand(0);
23651           continue;
23652         }
23653       } else if (Op.getOpcode() == ISD::SUB) {
23654         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23655           Offset += -C->getZExtValue();
23656           Op = Op.getOperand(0);
23657           continue;
23658         }
23659       }
23660
23661       // Otherwise, this isn't something we can handle, reject it.
23662       return;
23663     }
23664
23665     const GlobalValue *GV = GA->getGlobal();
23666     // If we require an extra load to get this address, as in PIC mode, we
23667     // can't accept it.
23668     if (isGlobalStubReference(
23669             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23670       return;
23671
23672     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23673                                         GA->getValueType(0), Offset);
23674     break;
23675   }
23676   }
23677
23678   if (Result.getNode()) {
23679     Ops.push_back(Result);
23680     return;
23681   }
23682   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23683 }
23684
23685 std::pair<unsigned, const TargetRegisterClass*>
23686 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23687                                                 MVT VT) const {
23688   // First, see if this is a constraint that directly corresponds to an LLVM
23689   // register class.
23690   if (Constraint.size() == 1) {
23691     // GCC Constraint Letters
23692     switch (Constraint[0]) {
23693     default: break;
23694       // TODO: Slight differences here in allocation order and leaving
23695       // RIP in the class. Do they matter any more here than they do
23696       // in the normal allocation?
23697     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23698       if (Subtarget->is64Bit()) {
23699         if (VT == MVT::i32 || VT == MVT::f32)
23700           return std::make_pair(0U, &X86::GR32RegClass);
23701         if (VT == MVT::i16)
23702           return std::make_pair(0U, &X86::GR16RegClass);
23703         if (VT == MVT::i8 || VT == MVT::i1)
23704           return std::make_pair(0U, &X86::GR8RegClass);
23705         if (VT == MVT::i64 || VT == MVT::f64)
23706           return std::make_pair(0U, &X86::GR64RegClass);
23707         break;
23708       }
23709       // 32-bit fallthrough
23710     case 'Q':   // Q_REGS
23711       if (VT == MVT::i32 || VT == MVT::f32)
23712         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23713       if (VT == MVT::i16)
23714         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23715       if (VT == MVT::i8 || VT == MVT::i1)
23716         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23717       if (VT == MVT::i64)
23718         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23719       break;
23720     case 'r':   // GENERAL_REGS
23721     case 'l':   // INDEX_REGS
23722       if (VT == MVT::i8 || VT == MVT::i1)
23723         return std::make_pair(0U, &X86::GR8RegClass);
23724       if (VT == MVT::i16)
23725         return std::make_pair(0U, &X86::GR16RegClass);
23726       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23727         return std::make_pair(0U, &X86::GR32RegClass);
23728       return std::make_pair(0U, &X86::GR64RegClass);
23729     case 'R':   // LEGACY_REGS
23730       if (VT == MVT::i8 || VT == MVT::i1)
23731         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23732       if (VT == MVT::i16)
23733         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23734       if (VT == MVT::i32 || !Subtarget->is64Bit())
23735         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23736       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23737     case 'f':  // FP Stack registers.
23738       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23739       // value to the correct fpstack register class.
23740       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23741         return std::make_pair(0U, &X86::RFP32RegClass);
23742       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23743         return std::make_pair(0U, &X86::RFP64RegClass);
23744       return std::make_pair(0U, &X86::RFP80RegClass);
23745     case 'y':   // MMX_REGS if MMX allowed.
23746       if (!Subtarget->hasMMX()) break;
23747       return std::make_pair(0U, &X86::VR64RegClass);
23748     case 'Y':   // SSE_REGS if SSE2 allowed
23749       if (!Subtarget->hasSSE2()) break;
23750       // FALL THROUGH.
23751     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23752       if (!Subtarget->hasSSE1()) break;
23753
23754       switch (VT.SimpleTy) {
23755       default: break;
23756       // Scalar SSE types.
23757       case MVT::f32:
23758       case MVT::i32:
23759         return std::make_pair(0U, &X86::FR32RegClass);
23760       case MVT::f64:
23761       case MVT::i64:
23762         return std::make_pair(0U, &X86::FR64RegClass);
23763       // Vector types.
23764       case MVT::v16i8:
23765       case MVT::v8i16:
23766       case MVT::v4i32:
23767       case MVT::v2i64:
23768       case MVT::v4f32:
23769       case MVT::v2f64:
23770         return std::make_pair(0U, &X86::VR128RegClass);
23771       // AVX types.
23772       case MVT::v32i8:
23773       case MVT::v16i16:
23774       case MVT::v8i32:
23775       case MVT::v4i64:
23776       case MVT::v8f32:
23777       case MVT::v4f64:
23778         return std::make_pair(0U, &X86::VR256RegClass);
23779       case MVT::v8f64:
23780       case MVT::v16f32:
23781       case MVT::v16i32:
23782       case MVT::v8i64:
23783         return std::make_pair(0U, &X86::VR512RegClass);
23784       }
23785       break;
23786     }
23787   }
23788
23789   // Use the default implementation in TargetLowering to convert the register
23790   // constraint into a member of a register class.
23791   std::pair<unsigned, const TargetRegisterClass*> Res;
23792   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23793
23794   // Not found as a standard register?
23795   if (!Res.second) {
23796     // Map st(0) -> st(7) -> ST0
23797     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23798         tolower(Constraint[1]) == 's' &&
23799         tolower(Constraint[2]) == 't' &&
23800         Constraint[3] == '(' &&
23801         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23802         Constraint[5] == ')' &&
23803         Constraint[6] == '}') {
23804
23805       Res.first = X86::FP0+Constraint[4]-'0';
23806       Res.second = &X86::RFP80RegClass;
23807       return Res;
23808     }
23809
23810     // GCC allows "st(0)" to be called just plain "st".
23811     if (StringRef("{st}").equals_lower(Constraint)) {
23812       Res.first = X86::FP0;
23813       Res.second = &X86::RFP80RegClass;
23814       return Res;
23815     }
23816
23817     // flags -> EFLAGS
23818     if (StringRef("{flags}").equals_lower(Constraint)) {
23819       Res.first = X86::EFLAGS;
23820       Res.second = &X86::CCRRegClass;
23821       return Res;
23822     }
23823
23824     // 'A' means EAX + EDX.
23825     if (Constraint == "A") {
23826       Res.first = X86::EAX;
23827       Res.second = &X86::GR32_ADRegClass;
23828       return Res;
23829     }
23830     return Res;
23831   }
23832
23833   // Otherwise, check to see if this is a register class of the wrong value
23834   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23835   // turn into {ax},{dx}.
23836   if (Res.second->hasType(VT))
23837     return Res;   // Correct type already, nothing to do.
23838
23839   // All of the single-register GCC register classes map their values onto
23840   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23841   // really want an 8-bit or 32-bit register, map to the appropriate register
23842   // class and return the appropriate register.
23843   if (Res.second == &X86::GR16RegClass) {
23844     if (VT == MVT::i8 || VT == MVT::i1) {
23845       unsigned DestReg = 0;
23846       switch (Res.first) {
23847       default: break;
23848       case X86::AX: DestReg = X86::AL; break;
23849       case X86::DX: DestReg = X86::DL; break;
23850       case X86::CX: DestReg = X86::CL; break;
23851       case X86::BX: DestReg = X86::BL; break;
23852       }
23853       if (DestReg) {
23854         Res.first = DestReg;
23855         Res.second = &X86::GR8RegClass;
23856       }
23857     } else if (VT == MVT::i32 || VT == MVT::f32) {
23858       unsigned DestReg = 0;
23859       switch (Res.first) {
23860       default: break;
23861       case X86::AX: DestReg = X86::EAX; break;
23862       case X86::DX: DestReg = X86::EDX; break;
23863       case X86::CX: DestReg = X86::ECX; break;
23864       case X86::BX: DestReg = X86::EBX; break;
23865       case X86::SI: DestReg = X86::ESI; break;
23866       case X86::DI: DestReg = X86::EDI; break;
23867       case X86::BP: DestReg = X86::EBP; break;
23868       case X86::SP: DestReg = X86::ESP; break;
23869       }
23870       if (DestReg) {
23871         Res.first = DestReg;
23872         Res.second = &X86::GR32RegClass;
23873       }
23874     } else if (VT == MVT::i64 || VT == MVT::f64) {
23875       unsigned DestReg = 0;
23876       switch (Res.first) {
23877       default: break;
23878       case X86::AX: DestReg = X86::RAX; break;
23879       case X86::DX: DestReg = X86::RDX; break;
23880       case X86::CX: DestReg = X86::RCX; break;
23881       case X86::BX: DestReg = X86::RBX; break;
23882       case X86::SI: DestReg = X86::RSI; break;
23883       case X86::DI: DestReg = X86::RDI; break;
23884       case X86::BP: DestReg = X86::RBP; break;
23885       case X86::SP: DestReg = X86::RSP; break;
23886       }
23887       if (DestReg) {
23888         Res.first = DestReg;
23889         Res.second = &X86::GR64RegClass;
23890       }
23891     }
23892   } else if (Res.second == &X86::FR32RegClass ||
23893              Res.second == &X86::FR64RegClass ||
23894              Res.second == &X86::VR128RegClass ||
23895              Res.second == &X86::VR256RegClass ||
23896              Res.second == &X86::FR32XRegClass ||
23897              Res.second == &X86::FR64XRegClass ||
23898              Res.second == &X86::VR128XRegClass ||
23899              Res.second == &X86::VR256XRegClass ||
23900              Res.second == &X86::VR512RegClass) {
23901     // Handle references to XMM physical registers that got mapped into the
23902     // wrong class.  This can happen with constraints like {xmm0} where the
23903     // target independent register mapper will just pick the first match it can
23904     // find, ignoring the required type.
23905
23906     if (VT == MVT::f32 || VT == MVT::i32)
23907       Res.second = &X86::FR32RegClass;
23908     else if (VT == MVT::f64 || VT == MVT::i64)
23909       Res.second = &X86::FR64RegClass;
23910     else if (X86::VR128RegClass.hasType(VT))
23911       Res.second = &X86::VR128RegClass;
23912     else if (X86::VR256RegClass.hasType(VT))
23913       Res.second = &X86::VR256RegClass;
23914     else if (X86::VR512RegClass.hasType(VT))
23915       Res.second = &X86::VR512RegClass;
23916   }
23917
23918   return Res;
23919 }
23920
23921 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23922                                             Type *Ty) const {
23923   // Scaling factors are not free at all.
23924   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23925   // will take 2 allocations in the out of order engine instead of 1
23926   // for plain addressing mode, i.e. inst (reg1).
23927   // E.g.,
23928   // vaddps (%rsi,%drx), %ymm0, %ymm1
23929   // Requires two allocations (one for the load, one for the computation)
23930   // whereas:
23931   // vaddps (%rsi), %ymm0, %ymm1
23932   // Requires just 1 allocation, i.e., freeing allocations for other operations
23933   // and having less micro operations to execute.
23934   //
23935   // For some X86 architectures, this is even worse because for instance for
23936   // stores, the complex addressing mode forces the instruction to use the
23937   // "load" ports instead of the dedicated "store" port.
23938   // E.g., on Haswell:
23939   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23940   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23941   if (isLegalAddressingMode(AM, Ty))
23942     // Scale represents reg2 * scale, thus account for 1
23943     // as soon as we use a second register.
23944     return AM.Scale != 0;
23945   return -1;
23946 }
23947
23948 bool X86TargetLowering::isTargetFTOL() const {
23949   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23950 }