[x86] Add a much more powerful framework for combining x86 shuffle
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
524   }
525
526   // There's never any support for operations beyond MVT::f32.
527   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
531
532   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
536
537   if (Subtarget->hasPOPCNT()) {
538     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
539   } else {
540     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
541     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
543     if (Subtarget->is64Bit())
544       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
545   }
546
547   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
548
549   if (!Subtarget->hasMOVBE())
550     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
551
552   // These should be promoted to a larger select which is supported.
553   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
554   // X86 wants to expand cmov itself.
555   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
556   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
561   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
567   if (Subtarget->is64Bit()) {
568     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
569     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
570   }
571   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
572   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574   // support continuation, user-level threading, and etc.. As a result, no
575   // other SjLj exception interfaces are implemented and please don't build
576   // your own exception handling based on them.
577   // LLVM/Clang supports zero-cost DWARF exception handling.
578   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
580
581   // Darwin ABI issue.
582   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
583   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
584   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
586   if (Subtarget->is64Bit())
587     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
589   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
592     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
593     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
594     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
595     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
596   }
597   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
599   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
601   if (Subtarget->is64Bit()) {
602     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
603     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
605   }
606
607   if (Subtarget->hasSSE1())
608     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
609
610   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
611
612   // Expand certain atomics
613   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
614     MVT VT = IntVTs[i];
615     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
618   }
619
620   if (Subtarget->hasCmpxchg16b()) {
621     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
622   }
623
624   // FIXME - use subtarget debug flags
625   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
628   }
629
630   if (Subtarget->is64Bit()) {
631     setExceptionPointerRegister(X86::RAX);
632     setExceptionSelectorRegister(X86::RDX);
633   } else {
634     setExceptionPointerRegister(X86::EAX);
635     setExceptionSelectorRegister(X86::EDX);
636   }
637   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
639
640   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
642
643   setOperationAction(ISD::TRAP, MVT::Other, Legal);
644   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
645
646   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
648   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
649   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650     // TargetInfo::X86_64ABIBuiltinVaList
651     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
652     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
653   } else {
654     // TargetInfo::CharPtrBuiltinVaList
655     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
656     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
657   }
658
659   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
660   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
661
662   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
663                      MVT::i64 : MVT::i32, Custom);
664
665   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666     // f32 and f64 use SSE.
667     // Set up the FP register classes.
668     addRegisterClass(MVT::f32, &X86::FR32RegClass);
669     addRegisterClass(MVT::f64, &X86::FR64RegClass);
670
671     // Use ANDPD to simulate FABS.
672     setOperationAction(ISD::FABS , MVT::f64, Custom);
673     setOperationAction(ISD::FABS , MVT::f32, Custom);
674
675     // Use XORP to simulate FNEG.
676     setOperationAction(ISD::FNEG , MVT::f64, Custom);
677     setOperationAction(ISD::FNEG , MVT::f32, Custom);
678
679     // Use ANDPD and ORPD to simulate FCOPYSIGN.
680     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
682
683     // Lower this to FGETSIGNx86 plus an AND.
684     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
686
687     // We don't support sin/cos/fmod
688     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
689     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
690     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
692     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
693     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
694
695     // Expand FP immediates into loads from the stack, except for the special
696     // cases we handle.
697     addLegalFPImmediate(APFloat(+0.0)); // xorpd
698     addLegalFPImmediate(APFloat(+0.0f)); // xorps
699   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700     // Use SSE for f32, x87 for f64.
701     // Set up the FP register classes.
702     addRegisterClass(MVT::f32, &X86::FR32RegClass);
703     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
704
705     // Use ANDPS to simulate FABS.
706     setOperationAction(ISD::FABS , MVT::f32, Custom);
707
708     // Use XORP to simulate FNEG.
709     setOperationAction(ISD::FNEG , MVT::f32, Custom);
710
711     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
712
713     // Use ANDPS and ORPS to simulate FCOPYSIGN.
714     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
716
717     // We don't support sin/cos/fmod
718     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
719     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
720     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
721
722     // Special cases we handle for FP constants.
723     addLegalFPImmediate(APFloat(+0.0f)); // xorps
724     addLegalFPImmediate(APFloat(+0.0)); // FLD0
725     addLegalFPImmediate(APFloat(+1.0)); // FLD1
726     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
728
729     if (!TM.Options.UnsafeFPMath) {
730       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
732       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733     }
734   } else if (!TM.Options.UseSoftFloat) {
735     // f32 and f64 in x87.
736     // Set up the FP register classes.
737     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
739
740     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
741     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
744
745     if (!TM.Options.UnsafeFPMath) {
746       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
747       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
749       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
752     }
753     addLegalFPImmediate(APFloat(+0.0)); // FLD0
754     addLegalFPImmediate(APFloat(+1.0)); // FLD1
755     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
761   }
762
763   // We don't support FMA.
764   setOperationAction(ISD::FMA, MVT::f64, Expand);
765   setOperationAction(ISD::FMA, MVT::f32, Expand);
766
767   // Long double always uses X87.
768   if (!TM.Options.UseSoftFloat) {
769     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
771     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
772     {
773       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774       addLegalFPImmediate(TmpFlt);  // FLD0
775       TmpFlt.changeSign();
776       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
777
778       bool ignored;
779       APFloat TmpFlt2(+1.0);
780       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
781                       &ignored);
782       addLegalFPImmediate(TmpFlt2);  // FLD1
783       TmpFlt2.changeSign();
784       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
785     }
786
787     if (!TM.Options.UnsafeFPMath) {
788       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
789       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
790       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
791     }
792
793     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
795     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
797     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798     setOperationAction(ISD::FMA, MVT::f80, Expand);
799   }
800
801   // Always use a library call for pow.
802   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
804   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
805
806   setOperationAction(ISD::FLOG, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP, MVT::f80, Expand);
810   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
811
812   // First set operation action for all vector types to either promote
813   // (for widening) or expand (for scalarization). Then we will selectively
814   // turn on ones that can be effectively codegen'd.
815   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817     MVT VT = (MVT::SimpleValueType)i;
818     setOperationAction(ISD::ADD , VT, Expand);
819     setOperationAction(ISD::SUB , VT, Expand);
820     setOperationAction(ISD::FADD, VT, Expand);
821     setOperationAction(ISD::FNEG, VT, Expand);
822     setOperationAction(ISD::FSUB, VT, Expand);
823     setOperationAction(ISD::MUL , VT, Expand);
824     setOperationAction(ISD::FMUL, VT, Expand);
825     setOperationAction(ISD::SDIV, VT, Expand);
826     setOperationAction(ISD::UDIV, VT, Expand);
827     setOperationAction(ISD::FDIV, VT, Expand);
828     setOperationAction(ISD::SREM, VT, Expand);
829     setOperationAction(ISD::UREM, VT, Expand);
830     setOperationAction(ISD::LOAD, VT, Expand);
831     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836     setOperationAction(ISD::FABS, VT, Expand);
837     setOperationAction(ISD::FSIN, VT, Expand);
838     setOperationAction(ISD::FSINCOS, VT, Expand);
839     setOperationAction(ISD::FCOS, VT, Expand);
840     setOperationAction(ISD::FSINCOS, VT, Expand);
841     setOperationAction(ISD::FREM, VT, Expand);
842     setOperationAction(ISD::FMA,  VT, Expand);
843     setOperationAction(ISD::FPOWI, VT, Expand);
844     setOperationAction(ISD::FSQRT, VT, Expand);
845     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846     setOperationAction(ISD::FFLOOR, VT, Expand);
847     setOperationAction(ISD::FCEIL, VT, Expand);
848     setOperationAction(ISD::FTRUNC, VT, Expand);
849     setOperationAction(ISD::FRINT, VT, Expand);
850     setOperationAction(ISD::FNEARBYINT, VT, Expand);
851     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852     setOperationAction(ISD::MULHS, VT, Expand);
853     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854     setOperationAction(ISD::MULHU, VT, Expand);
855     setOperationAction(ISD::SDIVREM, VT, Expand);
856     setOperationAction(ISD::UDIVREM, VT, Expand);
857     setOperationAction(ISD::FPOW, VT, Expand);
858     setOperationAction(ISD::CTPOP, VT, Expand);
859     setOperationAction(ISD::CTTZ, VT, Expand);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861     setOperationAction(ISD::CTLZ, VT, Expand);
862     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863     setOperationAction(ISD::SHL, VT, Expand);
864     setOperationAction(ISD::SRA, VT, Expand);
865     setOperationAction(ISD::SRL, VT, Expand);
866     setOperationAction(ISD::ROTL, VT, Expand);
867     setOperationAction(ISD::ROTR, VT, Expand);
868     setOperationAction(ISD::BSWAP, VT, Expand);
869     setOperationAction(ISD::SETCC, VT, Expand);
870     setOperationAction(ISD::FLOG, VT, Expand);
871     setOperationAction(ISD::FLOG2, VT, Expand);
872     setOperationAction(ISD::FLOG10, VT, Expand);
873     setOperationAction(ISD::FEXP, VT, Expand);
874     setOperationAction(ISD::FEXP2, VT, Expand);
875     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880     setOperationAction(ISD::TRUNCATE, VT, Expand);
881     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884     setOperationAction(ISD::VSELECT, VT, Expand);
885     setOperationAction(ISD::SELECT_CC, VT, Expand);
886     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888       setTruncStoreAction(VT,
889                           (MVT::SimpleValueType)InnerVT, Expand);
890     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
892
893     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894     // we have to deal with them whether we ask for Expansion or not. Setting
895     // Expand causes its own optimisation problems though, so leave them legal.
896     if (VT.getVectorElementType() == MVT::i1)
897       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
898   }
899
900   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901   // with -msoft-float, disable use of MMX as well.
902   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904     // No operations on x86mmx supported, everything uses intrinsics.
905   }
906
907   // MMX-sized vectors (other than x86mmx) are expected to be expanded
908   // into smaller operations.
909   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
910   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
912   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
913   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
914   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
915   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
916   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
917   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
918   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
919   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
920   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
921   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
922   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
923   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
924   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
928   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
929   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
930   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
931   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
933   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
937   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
938
939   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
941
942     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
946     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
947     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
948     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
949     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
950     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
951     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
952     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
954   }
955
956   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
958
959     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
960     // registers cannot be used even for integer operations.
961     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
965
966     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
967     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
968     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
969     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
970     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
971     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
972     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
974     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
975     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
976     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
977     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
978     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
979     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
980     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
981     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
985     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
986     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
987     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
988
989     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
992     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
993
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
995     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002       MVT VT = (MVT::SimpleValueType)i;
1003       // Do not attempt to custom lower non-power-of-2 vectors
1004       if (!isPowerOf2_32(VT.getVectorNumElements()))
1005         continue;
1006       // Do not attempt to custom lower non-128-bit vectors
1007       if (!VT.is128BitVector())
1008         continue;
1009       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1010       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012     }
1013
1014     // We support custom legalizing of sext and anyext loads for specific
1015     // memory vector types which we can load as a scalar (or sequence of
1016     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1017     // loads these must work with a single scalar load.
1018     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1019     if (Subtarget->is64Bit()) {
1020       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1021       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1022     }
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1028     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1029
1030     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1031     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1032     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1033     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1034     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1035     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1036
1037     if (Subtarget->is64Bit()) {
1038       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1039       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1040     }
1041
1042     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1043     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1044       MVT VT = (MVT::SimpleValueType)i;
1045
1046       // Do not attempt to promote non-128-bit vectors
1047       if (!VT.is128BitVector())
1048         continue;
1049
1050       setOperationAction(ISD::AND,    VT, Promote);
1051       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1052       setOperationAction(ISD::OR,     VT, Promote);
1053       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1054       setOperationAction(ISD::XOR,    VT, Promote);
1055       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1056       setOperationAction(ISD::LOAD,   VT, Promote);
1057       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1058       setOperationAction(ISD::SELECT, VT, Promote);
1059       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1060     }
1061
1062     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1063
1064     // Custom lower v2i64 and v2f64 selects.
1065     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1066     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1067     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1068     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1069
1070     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1071     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1072
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1074     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1075     // As there is no 64-bit GPR available, we need build a special custom
1076     // sequence to convert from v2i32 to v2f32.
1077     if (!Subtarget->is64Bit())
1078       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1079
1080     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1081     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1082
1083     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1084
1085     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1086     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1087     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1088   }
1089
1090   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1091     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1092     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1093     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1094     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1095     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1096     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1097     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1098     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1099     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1100     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1101
1102     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1103     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1104     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1105     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1106     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1107     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1108     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1109     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1110     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1111     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1112
1113     // FIXME: Do we need to handle scalar-to-vector here?
1114     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1115
1116     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1119     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1120     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1121     // There is no BLENDI for byte vectors. We don't need to custom lower
1122     // some vselects for now.
1123     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1124
1125     // SSE41 brings specific instructions for doing vector sign extend even in
1126     // cases where we don't have SRA.
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1128     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1129     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1130
1131     // i8 and i16 vectors are custom , because the source register and source
1132     // source memory operand types are not the same width.  f32 vectors are
1133     // custom since the immediate controlling the insert encodes additional
1134     // information.
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1138     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1139
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1143     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1144
1145     // FIXME: these should be Legal but thats only for the case where
1146     // the index is constant.  For now custom expand to deal with that.
1147     if (Subtarget->is64Bit()) {
1148       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1149       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1150     }
1151   }
1152
1153   if (Subtarget->hasSSE2()) {
1154     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1155     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1156
1157     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1158     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1159
1160     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1161     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1162
1163     // In the customized shift lowering, the legal cases in AVX2 will be
1164     // recognized.
1165     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1166     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1167
1168     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1169     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1170
1171     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1172   }
1173
1174   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1175     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1176     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1177     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1179     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1180     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1181
1182     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1183     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1184     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1185
1186     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1190     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1191     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1192     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1193     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1194     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1195     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1196     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1197     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1198
1199     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1203     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1204     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1205     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1206     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1207     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1208     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1209     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1210     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1211
1212     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1213     // even though v8i16 is a legal type.
1214     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1215     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1216     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1217
1218     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1219     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1220     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1221
1222     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1223     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1224
1225     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1226
1227     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1228     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1229
1230     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1231     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1232
1233     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1234     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1235
1236     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1238     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1239     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1240
1241     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1242     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1243     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1244
1245     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1247     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1248     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1249
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1251     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1252     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1254     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1255     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1257     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1258     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1260     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1261     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1262
1263     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1264       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1266       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1267       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1268       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1269       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1270     }
1271
1272     if (Subtarget->hasInt256()) {
1273       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1275       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1276       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1277
1278       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1280       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1281       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1282
1283       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1284       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1285       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1286       // Don't lower v32i8 because there is no 128-bit byte mul
1287
1288       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1289       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1290       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1291       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1292
1293       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1294       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1295     } else {
1296       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1298       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1299       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1300
1301       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1303       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1304       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1305
1306       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1307       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1308       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1309       // Don't lower v32i8 because there is no 128-bit byte mul
1310     }
1311
1312     // In the customized shift lowering, the legal cases in AVX2 will be
1313     // recognized.
1314     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1315     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1316
1317     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1318     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1319
1320     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1321
1322     // Custom lower several nodes for 256-bit types.
1323     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1324              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1325       MVT VT = (MVT::SimpleValueType)i;
1326
1327       // Extract subvector is special because the value type
1328       // (result) is 128-bit but the source is 256-bit wide.
1329       if (VT.is128BitVector())
1330         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1331
1332       // Do not attempt to custom lower other non-256-bit vectors
1333       if (!VT.is256BitVector())
1334         continue;
1335
1336       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1337       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1338       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1339       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1340       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1341       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1342       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1343     }
1344
1345     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1346     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1347       MVT VT = (MVT::SimpleValueType)i;
1348
1349       // Do not attempt to promote non-256-bit vectors
1350       if (!VT.is256BitVector())
1351         continue;
1352
1353       setOperationAction(ISD::AND,    VT, Promote);
1354       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1355       setOperationAction(ISD::OR,     VT, Promote);
1356       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1357       setOperationAction(ISD::XOR,    VT, Promote);
1358       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1359       setOperationAction(ISD::LOAD,   VT, Promote);
1360       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1361       setOperationAction(ISD::SELECT, VT, Promote);
1362       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1363     }
1364   }
1365
1366   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1367     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1368     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1369     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1370     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1371
1372     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1373     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1374     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1375
1376     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1377     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1378     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1379     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1380     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1381     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1385     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1386     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1387
1388     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1391     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1392     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1393     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1394
1395     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1398     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1399     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1400     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1401     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1402     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1403
1404     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1405     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1406     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1407     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1408     if (Subtarget->is64Bit()) {
1409       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1410       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1411       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1412       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1413     }
1414     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1416     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1417     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1418     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1421     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1422     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1423     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1424
1425     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1438
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1445
1446     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1447     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1448
1449     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1450
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1454     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1456     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1460
1461     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1462     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1463
1464     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1465     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1466
1467     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1468
1469     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1470     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1471
1472     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1473     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1474
1475     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1476     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1477
1478     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1479     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1480     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1481     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1482     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1483     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1484
1485     if (Subtarget->hasCDI()) {
1486       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1487       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1488     }
1489
1490     // Custom lower several nodes.
1491     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1492              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1493       MVT VT = (MVT::SimpleValueType)i;
1494
1495       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1496       // Extract subvector is special because the value type
1497       // (result) is 256/128-bit but the source is 512-bit wide.
1498       if (VT.is128BitVector() || VT.is256BitVector())
1499         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1500
1501       if (VT.getVectorElementType() == MVT::i1)
1502         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1503
1504       // Do not attempt to custom lower other non-512-bit vectors
1505       if (!VT.is512BitVector())
1506         continue;
1507
1508       if ( EltSize >= 32) {
1509         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1510         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1511         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1512         setOperationAction(ISD::VSELECT,             VT, Legal);
1513         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1514         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1515         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1516       }
1517     }
1518     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1519       MVT VT = (MVT::SimpleValueType)i;
1520
1521       // Do not attempt to promote non-256-bit vectors
1522       if (!VT.is512BitVector())
1523         continue;
1524
1525       setOperationAction(ISD::SELECT, VT, Promote);
1526       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1527     }
1528   }// has  AVX-512
1529
1530   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1531     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1532     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1533   }
1534
1535   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1536   // of this type with custom code.
1537   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1538            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1539     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1540                        Custom);
1541   }
1542
1543   // We want to custom lower some of our intrinsics.
1544   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1545   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1546   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1547   if (!Subtarget->is64Bit())
1548     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1549
1550   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1551   // handle type legalization for these operations here.
1552   //
1553   // FIXME: We really should do custom legalization for addition and
1554   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1555   // than generic legalization for 64-bit multiplication-with-overflow, though.
1556   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1557     // Add/Sub/Mul with overflow operations are custom lowered.
1558     MVT VT = IntVTs[i];
1559     setOperationAction(ISD::SADDO, VT, Custom);
1560     setOperationAction(ISD::UADDO, VT, Custom);
1561     setOperationAction(ISD::SSUBO, VT, Custom);
1562     setOperationAction(ISD::USUBO, VT, Custom);
1563     setOperationAction(ISD::SMULO, VT, Custom);
1564     setOperationAction(ISD::UMULO, VT, Custom);
1565   }
1566
1567   // There are no 8-bit 3-address imul/mul instructions
1568   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1569   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1570
1571   if (!Subtarget->is64Bit()) {
1572     // These libcalls are not available in 32-bit.
1573     setLibcallName(RTLIB::SHL_I128, nullptr);
1574     setLibcallName(RTLIB::SRL_I128, nullptr);
1575     setLibcallName(RTLIB::SRA_I128, nullptr);
1576   }
1577
1578   // Combine sin / cos into one node or libcall if possible.
1579   if (Subtarget->hasSinCos()) {
1580     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1581     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1582     if (Subtarget->isTargetDarwin()) {
1583       // For MacOSX, we don't want to the normal expansion of a libcall to
1584       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1585       // traffic.
1586       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1587       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1588     }
1589   }
1590
1591   if (Subtarget->isTargetWin64()) {
1592     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1593     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1594     setOperationAction(ISD::SREM, MVT::i128, Custom);
1595     setOperationAction(ISD::UREM, MVT::i128, Custom);
1596     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1597     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1598   }
1599
1600   // We have target-specific dag combine patterns for the following nodes:
1601   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1602   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1603   setTargetDAGCombine(ISD::VSELECT);
1604   setTargetDAGCombine(ISD::SELECT);
1605   setTargetDAGCombine(ISD::SHL);
1606   setTargetDAGCombine(ISD::SRA);
1607   setTargetDAGCombine(ISD::SRL);
1608   setTargetDAGCombine(ISD::OR);
1609   setTargetDAGCombine(ISD::AND);
1610   setTargetDAGCombine(ISD::ADD);
1611   setTargetDAGCombine(ISD::FADD);
1612   setTargetDAGCombine(ISD::FSUB);
1613   setTargetDAGCombine(ISD::FMA);
1614   setTargetDAGCombine(ISD::SUB);
1615   setTargetDAGCombine(ISD::LOAD);
1616   setTargetDAGCombine(ISD::STORE);
1617   setTargetDAGCombine(ISD::ZERO_EXTEND);
1618   setTargetDAGCombine(ISD::ANY_EXTEND);
1619   setTargetDAGCombine(ISD::SIGN_EXTEND);
1620   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1621   setTargetDAGCombine(ISD::TRUNCATE);
1622   setTargetDAGCombine(ISD::SINT_TO_FP);
1623   setTargetDAGCombine(ISD::SETCC);
1624   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1625   setTargetDAGCombine(ISD::BUILD_VECTOR);
1626   if (Subtarget->is64Bit())
1627     setTargetDAGCombine(ISD::MUL);
1628   setTargetDAGCombine(ISD::XOR);
1629
1630   computeRegisterProperties();
1631
1632   // On Darwin, -Os means optimize for size without hurting performance,
1633   // do not reduce the limit.
1634   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1635   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1636   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1637   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1638   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1639   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1640   setPrefLoopAlignment(4); // 2^4 bytes.
1641
1642   // Predictable cmov don't hurt on atom because it's in-order.
1643   PredictableSelectIsExpensive = !Subtarget->isAtom();
1644
1645   setPrefFunctionAlignment(4); // 2^4 bytes.
1646 }
1647
1648 // This has so far only been implemented for 64-bit MachO.
1649 bool X86TargetLowering::useLoadStackGuardNode() const {
1650   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1651          Subtarget->is64Bit();
1652 }
1653
1654 TargetLoweringBase::LegalizeTypeAction
1655 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1656   if (ExperimentalVectorWideningLegalization &&
1657       VT.getVectorNumElements() != 1 &&
1658       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1659     return TypeWidenVector;
1660
1661   return TargetLoweringBase::getPreferredVectorAction(VT);
1662 }
1663
1664 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1665   if (!VT.isVector())
1666     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1667
1668   if (Subtarget->hasAVX512())
1669     switch(VT.getVectorNumElements()) {
1670     case  8: return MVT::v8i1;
1671     case 16: return MVT::v16i1;
1672   }
1673
1674   return VT.changeVectorElementTypeToInteger();
1675 }
1676
1677 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1678 /// the desired ByVal argument alignment.
1679 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1680   if (MaxAlign == 16)
1681     return;
1682   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1683     if (VTy->getBitWidth() == 128)
1684       MaxAlign = 16;
1685   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1686     unsigned EltAlign = 0;
1687     getMaxByValAlign(ATy->getElementType(), EltAlign);
1688     if (EltAlign > MaxAlign)
1689       MaxAlign = EltAlign;
1690   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1691     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1692       unsigned EltAlign = 0;
1693       getMaxByValAlign(STy->getElementType(i), EltAlign);
1694       if (EltAlign > MaxAlign)
1695         MaxAlign = EltAlign;
1696       if (MaxAlign == 16)
1697         break;
1698     }
1699   }
1700 }
1701
1702 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1703 /// function arguments in the caller parameter area. For X86, aggregates
1704 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1705 /// are at 4-byte boundaries.
1706 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1707   if (Subtarget->is64Bit()) {
1708     // Max of 8 and alignment of type.
1709     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1710     if (TyAlign > 8)
1711       return TyAlign;
1712     return 8;
1713   }
1714
1715   unsigned Align = 4;
1716   if (Subtarget->hasSSE1())
1717     getMaxByValAlign(Ty, Align);
1718   return Align;
1719 }
1720
1721 /// getOptimalMemOpType - Returns the target specific optimal type for load
1722 /// and store operations as a result of memset, memcpy, and memmove
1723 /// lowering. If DstAlign is zero that means it's safe to destination
1724 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1725 /// means there isn't a need to check it against alignment requirement,
1726 /// probably because the source does not need to be loaded. If 'IsMemset' is
1727 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1728 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1729 /// source is constant so it does not need to be loaded.
1730 /// It returns EVT::Other if the type should be determined using generic
1731 /// target-independent logic.
1732 EVT
1733 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1734                                        unsigned DstAlign, unsigned SrcAlign,
1735                                        bool IsMemset, bool ZeroMemset,
1736                                        bool MemcpyStrSrc,
1737                                        MachineFunction &MF) const {
1738   const Function *F = MF.getFunction();
1739   if ((!IsMemset || ZeroMemset) &&
1740       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1741                                        Attribute::NoImplicitFloat)) {
1742     if (Size >= 16 &&
1743         (Subtarget->isUnalignedMemAccessFast() ||
1744          ((DstAlign == 0 || DstAlign >= 16) &&
1745           (SrcAlign == 0 || SrcAlign >= 16)))) {
1746       if (Size >= 32) {
1747         if (Subtarget->hasInt256())
1748           return MVT::v8i32;
1749         if (Subtarget->hasFp256())
1750           return MVT::v8f32;
1751       }
1752       if (Subtarget->hasSSE2())
1753         return MVT::v4i32;
1754       if (Subtarget->hasSSE1())
1755         return MVT::v4f32;
1756     } else if (!MemcpyStrSrc && Size >= 8 &&
1757                !Subtarget->is64Bit() &&
1758                Subtarget->hasSSE2()) {
1759       // Do not use f64 to lower memcpy if source is string constant. It's
1760       // better to use i32 to avoid the loads.
1761       return MVT::f64;
1762     }
1763   }
1764   if (Subtarget->is64Bit() && Size >= 8)
1765     return MVT::i64;
1766   return MVT::i32;
1767 }
1768
1769 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1770   if (VT == MVT::f32)
1771     return X86ScalarSSEf32;
1772   else if (VT == MVT::f64)
1773     return X86ScalarSSEf64;
1774   return true;
1775 }
1776
1777 bool
1778 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
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, MF.getTarget(),
1904                  RVLocs, Context);
1905   return CCInfo.CheckReturn(Outs, RetCC_X86);
1906 }
1907
1908 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1909   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1910   return ScratchRegs;
1911 }
1912
1913 SDValue
1914 X86TargetLowering::LowerReturn(SDValue Chain,
1915                                CallingConv::ID CallConv, bool isVarArg,
1916                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1917                                const SmallVectorImpl<SDValue> &OutVals,
1918                                SDLoc dl, SelectionDAG &DAG) const {
1919   MachineFunction &MF = DAG.getMachineFunction();
1920   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1921
1922   SmallVector<CCValAssign, 16> RVLocs;
1923   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1924                  RVLocs, *DAG.getContext());
1925   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1926
1927   SDValue Flag;
1928   SmallVector<SDValue, 6> RetOps;
1929   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1930   // Operand #1 = Bytes To Pop
1931   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1932                    MVT::i16));
1933
1934   // Copy the result values into the output registers.
1935   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1936     CCValAssign &VA = RVLocs[i];
1937     assert(VA.isRegLoc() && "Can only return in registers!");
1938     SDValue ValToCopy = OutVals[i];
1939     EVT ValVT = ValToCopy.getValueType();
1940
1941     // Promote values to the appropriate types
1942     if (VA.getLocInfo() == CCValAssign::SExt)
1943       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1944     else if (VA.getLocInfo() == CCValAssign::ZExt)
1945       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1946     else if (VA.getLocInfo() == CCValAssign::AExt)
1947       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1948     else if (VA.getLocInfo() == CCValAssign::BCvt)
1949       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1950
1951     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1952            "Unexpected FP-extend for return value.");  
1953
1954     // If this is x86-64, and we disabled SSE, we can't return FP values,
1955     // or SSE or MMX vectors.
1956     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1957          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1958           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1959       report_fatal_error("SSE register return with SSE disabled");
1960     }
1961     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1962     // llvm-gcc has never done it right and no one has noticed, so this
1963     // should be OK for now.
1964     if (ValVT == MVT::f64 &&
1965         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1966       report_fatal_error("SSE2 register return with SSE2 disabled");
1967
1968     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1969     // the RET instruction and handled by the FP Stackifier.
1970     if (VA.getLocReg() == X86::ST0 ||
1971         VA.getLocReg() == X86::ST1) {
1972       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1973       // change the value to the FP stack register class.
1974       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1975         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1976       RetOps.push_back(ValToCopy);
1977       // Don't emit a copytoreg.
1978       continue;
1979     }
1980
1981     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1982     // which is returned in RAX / RDX.
1983     if (Subtarget->is64Bit()) {
1984       if (ValVT == MVT::x86mmx) {
1985         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1986           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1987           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1988                                   ValToCopy);
1989           // If we don't have SSE2 available, convert to v4f32 so the generated
1990           // register is legal.
1991           if (!Subtarget->hasSSE2())
1992             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1993         }
1994       }
1995     }
1996
1997     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1998     Flag = Chain.getValue(1);
1999     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2000   }
2001
2002   // The x86-64 ABIs require that for returning structs by value we copy
2003   // the sret argument into %rax/%eax (depending on ABI) for the return.
2004   // Win32 requires us to put the sret argument to %eax as well.
2005   // We saved the argument into a virtual register in the entry block,
2006   // so now we copy the value out and into %rax/%eax.
2007   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2008       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2009     MachineFunction &MF = DAG.getMachineFunction();
2010     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2011     unsigned Reg = FuncInfo->getSRetReturnReg();
2012     assert(Reg &&
2013            "SRetReturnReg should have been set in LowerFormalArguments().");
2014     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2015
2016     unsigned RetValReg
2017         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2018           X86::RAX : X86::EAX;
2019     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2020     Flag = Chain.getValue(1);
2021
2022     // RAX/EAX now acts like a return value.
2023     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2024   }
2025
2026   RetOps[0] = Chain;  // Update chain.
2027
2028   // Add the flag if we have it.
2029   if (Flag.getNode())
2030     RetOps.push_back(Flag);
2031
2032   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2033 }
2034
2035 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2036   if (N->getNumValues() != 1)
2037     return false;
2038   if (!N->hasNUsesOfValue(1, 0))
2039     return false;
2040
2041   SDValue TCChain = Chain;
2042   SDNode *Copy = *N->use_begin();
2043   if (Copy->getOpcode() == ISD::CopyToReg) {
2044     // If the copy has a glue operand, we conservatively assume it isn't safe to
2045     // perform a tail call.
2046     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2047       return false;
2048     TCChain = Copy->getOperand(0);
2049   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2050     return false;
2051
2052   bool HasRet = false;
2053   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2054        UI != UE; ++UI) {
2055     if (UI->getOpcode() != X86ISD::RET_FLAG)
2056       return false;
2057     HasRet = true;
2058   }
2059
2060   if (!HasRet)
2061     return false;
2062
2063   Chain = TCChain;
2064   return true;
2065 }
2066
2067 MVT
2068 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2069                                             ISD::NodeType ExtendKind) const {
2070   MVT ReturnMVT;
2071   // TODO: Is this also valid on 32-bit?
2072   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2073     ReturnMVT = MVT::i8;
2074   else
2075     ReturnMVT = MVT::i32;
2076
2077   MVT MinVT = getRegisterType(ReturnMVT);
2078   return VT.bitsLT(MinVT) ? MinVT : VT;
2079 }
2080
2081 /// LowerCallResult - Lower the result values of a call into the
2082 /// appropriate copies out of appropriate physical registers.
2083 ///
2084 SDValue
2085 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2086                                    CallingConv::ID CallConv, bool isVarArg,
2087                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2088                                    SDLoc dl, SelectionDAG &DAG,
2089                                    SmallVectorImpl<SDValue> &InVals) const {
2090
2091   // Assign locations to each value returned by this call.
2092   SmallVector<CCValAssign, 16> RVLocs;
2093   bool Is64Bit = Subtarget->is64Bit();
2094   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2095                  DAG.getTarget(), RVLocs, *DAG.getContext());
2096   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2097
2098   // Copy all of the result registers out of their specified physreg.
2099   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2100     CCValAssign &VA = RVLocs[i];
2101     EVT CopyVT = VA.getValVT();
2102
2103     // If this is x86-64, and we disabled SSE, we can't return FP values
2104     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2105         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2106       report_fatal_error("SSE register return with SSE disabled");
2107     }
2108
2109     SDValue Val;
2110
2111     // If this is a call to a function that returns an fp value on the floating
2112     // point stack, we must guarantee the value is popped from the stack, so
2113     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2114     // if the return value is not used. We use the FpPOP_RETVAL instruction
2115     // instead.
2116     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2117       // If we prefer to use the value in xmm registers, copy it out as f80 and
2118       // use a truncate to move it from fp stack reg to xmm reg.
2119       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2120       SDValue Ops[] = { Chain, InFlag };
2121       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2122                                          MVT::Other, MVT::Glue, Ops), 1);
2123       Val = Chain.getValue(0);
2124
2125       // Round the f80 to the right size, which also moves it to the appropriate
2126       // xmm register.
2127       if (CopyVT != VA.getValVT())
2128         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2129                           // This truncation won't change the value.
2130                           DAG.getIntPtrConstant(1));
2131     } else {
2132       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2133                                  CopyVT, InFlag).getValue(1);
2134       Val = Chain.getValue(0);
2135     }
2136     InFlag = Chain.getValue(2);
2137     InVals.push_back(Val);
2138   }
2139
2140   return Chain;
2141 }
2142
2143 //===----------------------------------------------------------------------===//
2144 //                C & StdCall & Fast Calling Convention implementation
2145 //===----------------------------------------------------------------------===//
2146 //  StdCall calling convention seems to be standard for many Windows' API
2147 //  routines and around. It differs from C calling convention just a little:
2148 //  callee should clean up the stack, not caller. Symbols should be also
2149 //  decorated in some fancy way :) It doesn't support any vector arguments.
2150 //  For info on fast calling convention see Fast Calling Convention (tail call)
2151 //  implementation LowerX86_32FastCCCallTo.
2152
2153 /// CallIsStructReturn - Determines whether a call uses struct return
2154 /// semantics.
2155 enum StructReturnType {
2156   NotStructReturn,
2157   RegStructReturn,
2158   StackStructReturn
2159 };
2160 static StructReturnType
2161 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2162   if (Outs.empty())
2163     return NotStructReturn;
2164
2165   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2166   if (!Flags.isSRet())
2167     return NotStructReturn;
2168   if (Flags.isInReg())
2169     return RegStructReturn;
2170   return StackStructReturn;
2171 }
2172
2173 /// ArgsAreStructReturn - Determines whether a function uses struct
2174 /// return semantics.
2175 static StructReturnType
2176 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2177   if (Ins.empty())
2178     return NotStructReturn;
2179
2180   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2181   if (!Flags.isSRet())
2182     return NotStructReturn;
2183   if (Flags.isInReg())
2184     return RegStructReturn;
2185   return StackStructReturn;
2186 }
2187
2188 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2189 /// by "Src" to address "Dst" with size and alignment information specified by
2190 /// the specific parameter attribute. The copy will be passed as a byval
2191 /// function parameter.
2192 static SDValue
2193 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2194                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2195                           SDLoc dl) {
2196   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2197
2198   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2199                        /*isVolatile*/false, /*AlwaysInline=*/true,
2200                        MachinePointerInfo(), MachinePointerInfo());
2201 }
2202
2203 /// IsTailCallConvention - Return true if the calling convention is one that
2204 /// supports tail call optimization.
2205 static bool IsTailCallConvention(CallingConv::ID CC) {
2206   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2207           CC == CallingConv::HiPE);
2208 }
2209
2210 /// \brief Return true if the calling convention is a C calling convention.
2211 static bool IsCCallConvention(CallingConv::ID CC) {
2212   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2213           CC == CallingConv::X86_64_SysV);
2214 }
2215
2216 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2217   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2218     return false;
2219
2220   CallSite CS(CI);
2221   CallingConv::ID CalleeCC = CS.getCallingConv();
2222   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2223     return false;
2224
2225   return true;
2226 }
2227
2228 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2229 /// a tailcall target by changing its ABI.
2230 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2231                                    bool GuaranteedTailCallOpt) {
2232   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2233 }
2234
2235 SDValue
2236 X86TargetLowering::LowerMemArgument(SDValue Chain,
2237                                     CallingConv::ID CallConv,
2238                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2239                                     SDLoc dl, SelectionDAG &DAG,
2240                                     const CCValAssign &VA,
2241                                     MachineFrameInfo *MFI,
2242                                     unsigned i) const {
2243   // Create the nodes corresponding to a load from this parameter slot.
2244   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2245   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2246       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2247   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2248   EVT ValVT;
2249
2250   // If value is passed by pointer we have address passed instead of the value
2251   // itself.
2252   if (VA.getLocInfo() == CCValAssign::Indirect)
2253     ValVT = VA.getLocVT();
2254   else
2255     ValVT = VA.getValVT();
2256
2257   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2258   // changed with more analysis.
2259   // In case of tail call optimization mark all arguments mutable. Since they
2260   // could be overwritten by lowering of arguments in case of a tail call.
2261   if (Flags.isByVal()) {
2262     unsigned Bytes = Flags.getByValSize();
2263     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2264     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2265     return DAG.getFrameIndex(FI, getPointerTy());
2266   } else {
2267     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2268                                     VA.getLocMemOffset(), isImmutable);
2269     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2270     return DAG.getLoad(ValVT, dl, Chain, FIN,
2271                        MachinePointerInfo::getFixedStack(FI),
2272                        false, false, false, 0);
2273   }
2274 }
2275
2276 SDValue
2277 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2278                                         CallingConv::ID CallConv,
2279                                         bool isVarArg,
2280                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2281                                         SDLoc dl,
2282                                         SelectionDAG &DAG,
2283                                         SmallVectorImpl<SDValue> &InVals)
2284                                           const {
2285   MachineFunction &MF = DAG.getMachineFunction();
2286   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2287
2288   const Function* Fn = MF.getFunction();
2289   if (Fn->hasExternalLinkage() &&
2290       Subtarget->isTargetCygMing() &&
2291       Fn->getName() == "main")
2292     FuncInfo->setForceFramePointer(true);
2293
2294   MachineFrameInfo *MFI = MF.getFrameInfo();
2295   bool Is64Bit = Subtarget->is64Bit();
2296   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2297
2298   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2299          "Var args not supported with calling convention fastcc, ghc or hipe");
2300
2301   // Assign locations to all of the incoming arguments.
2302   SmallVector<CCValAssign, 16> ArgLocs;
2303   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2304                  ArgLocs, *DAG.getContext());
2305
2306   // Allocate shadow area for Win64
2307   if (IsWin64)
2308     CCInfo.AllocateStack(32, 8);
2309
2310   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2311
2312   unsigned LastVal = ~0U;
2313   SDValue ArgValue;
2314   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2315     CCValAssign &VA = ArgLocs[i];
2316     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2317     // places.
2318     assert(VA.getValNo() != LastVal &&
2319            "Don't support value assigned to multiple locs yet");
2320     (void)LastVal;
2321     LastVal = VA.getValNo();
2322
2323     if (VA.isRegLoc()) {
2324       EVT RegVT = VA.getLocVT();
2325       const TargetRegisterClass *RC;
2326       if (RegVT == MVT::i32)
2327         RC = &X86::GR32RegClass;
2328       else if (Is64Bit && RegVT == MVT::i64)
2329         RC = &X86::GR64RegClass;
2330       else if (RegVT == MVT::f32)
2331         RC = &X86::FR32RegClass;
2332       else if (RegVT == MVT::f64)
2333         RC = &X86::FR64RegClass;
2334       else if (RegVT.is512BitVector())
2335         RC = &X86::VR512RegClass;
2336       else if (RegVT.is256BitVector())
2337         RC = &X86::VR256RegClass;
2338       else if (RegVT.is128BitVector())
2339         RC = &X86::VR128RegClass;
2340       else if (RegVT == MVT::x86mmx)
2341         RC = &X86::VR64RegClass;
2342       else if (RegVT == MVT::i1)
2343         RC = &X86::VK1RegClass;
2344       else if (RegVT == MVT::v8i1)
2345         RC = &X86::VK8RegClass;
2346       else if (RegVT == MVT::v16i1)
2347         RC = &X86::VK16RegClass;
2348       else if (RegVT == MVT::v32i1)
2349         RC = &X86::VK32RegClass;
2350       else if (RegVT == MVT::v64i1)
2351         RC = &X86::VK64RegClass;
2352       else
2353         llvm_unreachable("Unknown argument type!");
2354
2355       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2356       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2357
2358       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2359       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2360       // right size.
2361       if (VA.getLocInfo() == CCValAssign::SExt)
2362         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2363                                DAG.getValueType(VA.getValVT()));
2364       else if (VA.getLocInfo() == CCValAssign::ZExt)
2365         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2366                                DAG.getValueType(VA.getValVT()));
2367       else if (VA.getLocInfo() == CCValAssign::BCvt)
2368         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2369
2370       if (VA.isExtInLoc()) {
2371         // Handle MMX values passed in XMM regs.
2372         if (RegVT.isVector())
2373           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2374         else
2375           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2376       }
2377     } else {
2378       assert(VA.isMemLoc());
2379       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2380     }
2381
2382     // If value is passed via pointer - do a load.
2383     if (VA.getLocInfo() == CCValAssign::Indirect)
2384       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2385                              MachinePointerInfo(), false, false, false, 0);
2386
2387     InVals.push_back(ArgValue);
2388   }
2389
2390   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2391     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2392       // The x86-64 ABIs require that for returning structs by value we copy
2393       // the sret argument into %rax/%eax (depending on ABI) for the return.
2394       // Win32 requires us to put the sret argument to %eax as well.
2395       // Save the argument into a virtual register so that we can access it
2396       // from the return points.
2397       if (Ins[i].Flags.isSRet()) {
2398         unsigned Reg = FuncInfo->getSRetReturnReg();
2399         if (!Reg) {
2400           MVT PtrTy = getPointerTy();
2401           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2402           FuncInfo->setSRetReturnReg(Reg);
2403         }
2404         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2405         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2406         break;
2407       }
2408     }
2409   }
2410
2411   unsigned StackSize = CCInfo.getNextStackOffset();
2412   // Align stack specially for tail calls.
2413   if (FuncIsMadeTailCallSafe(CallConv,
2414                              MF.getTarget().Options.GuaranteedTailCallOpt))
2415     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2416
2417   // If the function takes variable number of arguments, make a frame index for
2418   // the start of the first vararg value... for expansion of llvm.va_start.
2419   if (isVarArg) {
2420     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2421                     CallConv != CallingConv::X86_ThisCall)) {
2422       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2423     }
2424     if (Is64Bit) {
2425       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2426
2427       // FIXME: We should really autogenerate these arrays
2428       static const MCPhysReg GPR64ArgRegsWin64[] = {
2429         X86::RCX, X86::RDX, X86::R8,  X86::R9
2430       };
2431       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2432         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2433       };
2434       static const MCPhysReg XMMArgRegs64Bit[] = {
2435         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2436         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2437       };
2438       const MCPhysReg *GPR64ArgRegs;
2439       unsigned NumXMMRegs = 0;
2440
2441       if (IsWin64) {
2442         // The XMM registers which might contain var arg parameters are shadowed
2443         // in their paired GPR.  So we only need to save the GPR to their home
2444         // slots.
2445         TotalNumIntRegs = 4;
2446         GPR64ArgRegs = GPR64ArgRegsWin64;
2447       } else {
2448         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2449         GPR64ArgRegs = GPR64ArgRegs64Bit;
2450
2451         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2452                                                 TotalNumXMMRegs);
2453       }
2454       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2455                                                        TotalNumIntRegs);
2456
2457       bool NoImplicitFloatOps = Fn->getAttributes().
2458         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2459       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2460              "SSE register cannot be used when SSE is disabled!");
2461       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2462                NoImplicitFloatOps) &&
2463              "SSE register cannot be used when SSE is disabled!");
2464       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2465           !Subtarget->hasSSE1())
2466         // Kernel mode asks for SSE to be disabled, so don't push them
2467         // on the stack.
2468         TotalNumXMMRegs = 0;
2469
2470       if (IsWin64) {
2471         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2472         // Get to the caller-allocated home save location.  Add 8 to account
2473         // for the return address.
2474         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2475         FuncInfo->setRegSaveFrameIndex(
2476           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2477         // Fixup to set vararg frame on shadow area (4 x i64).
2478         if (NumIntRegs < 4)
2479           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2480       } else {
2481         // For X86-64, if there are vararg parameters that are passed via
2482         // registers, then we must store them to their spots on the stack so
2483         // they may be loaded by deferencing the result of va_next.
2484         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2485         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2486         FuncInfo->setRegSaveFrameIndex(
2487           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2488                                false));
2489       }
2490
2491       // Store the integer parameter registers.
2492       SmallVector<SDValue, 8> MemOps;
2493       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2494                                         getPointerTy());
2495       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2496       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2497         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2498                                   DAG.getIntPtrConstant(Offset));
2499         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2500                                      &X86::GR64RegClass);
2501         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2502         SDValue Store =
2503           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2504                        MachinePointerInfo::getFixedStack(
2505                          FuncInfo->getRegSaveFrameIndex(), Offset),
2506                        false, false, 0);
2507         MemOps.push_back(Store);
2508         Offset += 8;
2509       }
2510
2511       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2512         // Now store the XMM (fp + vector) parameter registers.
2513         SmallVector<SDValue, 11> SaveXMMOps;
2514         SaveXMMOps.push_back(Chain);
2515
2516         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2517         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2518         SaveXMMOps.push_back(ALVal);
2519
2520         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2521                                FuncInfo->getRegSaveFrameIndex()));
2522         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2523                                FuncInfo->getVarArgsFPOffset()));
2524
2525         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2526           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2527                                        &X86::VR128RegClass);
2528           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2529           SaveXMMOps.push_back(Val);
2530         }
2531         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2532                                      MVT::Other, SaveXMMOps));
2533       }
2534
2535       if (!MemOps.empty())
2536         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2537     }
2538   }
2539
2540   // Some CCs need callee pop.
2541   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2542                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2543     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2544   } else {
2545     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2546     // If this is an sret function, the return should pop the hidden pointer.
2547     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2548         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2549         argsAreStructReturn(Ins) == StackStructReturn)
2550       FuncInfo->setBytesToPopOnReturn(4);
2551   }
2552
2553   if (!Is64Bit) {
2554     // RegSaveFrameIndex is X86-64 only.
2555     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2556     if (CallConv == CallingConv::X86_FastCall ||
2557         CallConv == CallingConv::X86_ThisCall)
2558       // fastcc functions can't have varargs.
2559       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2560   }
2561
2562   FuncInfo->setArgumentStackSize(StackSize);
2563
2564   return Chain;
2565 }
2566
2567 SDValue
2568 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2569                                     SDValue StackPtr, SDValue Arg,
2570                                     SDLoc dl, SelectionDAG &DAG,
2571                                     const CCValAssign &VA,
2572                                     ISD::ArgFlagsTy Flags) const {
2573   unsigned LocMemOffset = VA.getLocMemOffset();
2574   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2575   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2576   if (Flags.isByVal())
2577     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2578
2579   return DAG.getStore(Chain, dl, Arg, PtrOff,
2580                       MachinePointerInfo::getStack(LocMemOffset),
2581                       false, false, 0);
2582 }
2583
2584 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2585 /// optimization is performed and it is required.
2586 SDValue
2587 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2588                                            SDValue &OutRetAddr, SDValue Chain,
2589                                            bool IsTailCall, bool Is64Bit,
2590                                            int FPDiff, SDLoc dl) const {
2591   // Adjust the Return address stack slot.
2592   EVT VT = getPointerTy();
2593   OutRetAddr = getReturnAddressFrameIndex(DAG);
2594
2595   // Load the "old" Return address.
2596   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2597                            false, false, false, 0);
2598   return SDValue(OutRetAddr.getNode(), 1);
2599 }
2600
2601 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2602 /// optimization is performed and it is required (FPDiff!=0).
2603 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2604                                         SDValue Chain, SDValue RetAddrFrIdx,
2605                                         EVT PtrVT, unsigned SlotSize,
2606                                         int FPDiff, SDLoc dl) {
2607   // Store the return address to the appropriate stack slot.
2608   if (!FPDiff) return Chain;
2609   // Calculate the new stack slot for the return address.
2610   int NewReturnAddrFI =
2611     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2612                                          false);
2613   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2614   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2615                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2616                        false, false, 0);
2617   return Chain;
2618 }
2619
2620 SDValue
2621 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2622                              SmallVectorImpl<SDValue> &InVals) const {
2623   SelectionDAG &DAG                     = CLI.DAG;
2624   SDLoc &dl                             = CLI.DL;
2625   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2626   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2627   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2628   SDValue Chain                         = CLI.Chain;
2629   SDValue Callee                        = CLI.Callee;
2630   CallingConv::ID CallConv              = CLI.CallConv;
2631   bool &isTailCall                      = CLI.IsTailCall;
2632   bool isVarArg                         = CLI.IsVarArg;
2633
2634   MachineFunction &MF = DAG.getMachineFunction();
2635   bool Is64Bit        = Subtarget->is64Bit();
2636   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2637   StructReturnType SR = callIsStructReturn(Outs);
2638   bool IsSibcall      = false;
2639
2640   if (MF.getTarget().Options.DisableTailCalls)
2641     isTailCall = false;
2642
2643   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2644   if (IsMustTail) {
2645     // Force this to be a tail call.  The verifier rules are enough to ensure
2646     // that we can lower this successfully without moving the return address
2647     // around.
2648     isTailCall = true;
2649   } else if (isTailCall) {
2650     // Check if it's really possible to do a tail call.
2651     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2652                     isVarArg, SR != NotStructReturn,
2653                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2654                     Outs, OutVals, Ins, DAG);
2655
2656     // Sibcalls are automatically detected tailcalls which do not require
2657     // ABI changes.
2658     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2659       IsSibcall = true;
2660
2661     if (isTailCall)
2662       ++NumTailCalls;
2663   }
2664
2665   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2666          "Var args not supported with calling convention fastcc, ghc or hipe");
2667
2668   // Analyze operands of the call, assigning locations to each operand.
2669   SmallVector<CCValAssign, 16> ArgLocs;
2670   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2671                  ArgLocs, *DAG.getContext());
2672
2673   // Allocate shadow area for Win64
2674   if (IsWin64)
2675     CCInfo.AllocateStack(32, 8);
2676
2677   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2678
2679   // Get a count of how many bytes are to be pushed on the stack.
2680   unsigned NumBytes = CCInfo.getNextStackOffset();
2681   if (IsSibcall)
2682     // This is a sibcall. The memory operands are available in caller's
2683     // own caller's stack.
2684     NumBytes = 0;
2685   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2686            IsTailCallConvention(CallConv))
2687     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2688
2689   int FPDiff = 0;
2690   if (isTailCall && !IsSibcall && !IsMustTail) {
2691     // Lower arguments at fp - stackoffset + fpdiff.
2692     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2693     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2694
2695     FPDiff = NumBytesCallerPushed - NumBytes;
2696
2697     // Set the delta of movement of the returnaddr stackslot.
2698     // But only set if delta is greater than previous delta.
2699     if (FPDiff < X86Info->getTCReturnAddrDelta())
2700       X86Info->setTCReturnAddrDelta(FPDiff);
2701   }
2702
2703   unsigned NumBytesToPush = NumBytes;
2704   unsigned NumBytesToPop = NumBytes;
2705
2706   // If we have an inalloca argument, all stack space has already been allocated
2707   // for us and be right at the top of the stack.  We don't support multiple
2708   // arguments passed in memory when using inalloca.
2709   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2710     NumBytesToPush = 0;
2711     if (!ArgLocs.back().isMemLoc())
2712       report_fatal_error("cannot use inalloca attribute on a register "
2713                          "parameter");
2714     if (ArgLocs.back().getLocMemOffset() != 0)
2715       report_fatal_error("any parameter with the inalloca attribute must be "
2716                          "the only memory argument");
2717   }
2718
2719   if (!IsSibcall)
2720     Chain = DAG.getCALLSEQ_START(
2721         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2722
2723   SDValue RetAddrFrIdx;
2724   // Load return address for tail calls.
2725   if (isTailCall && FPDiff)
2726     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2727                                     Is64Bit, FPDiff, dl);
2728
2729   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2730   SmallVector<SDValue, 8> MemOpChains;
2731   SDValue StackPtr;
2732
2733   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2734   // of tail call optimization arguments are handle later.
2735   const X86RegisterInfo *RegInfo =
2736     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2737   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2738     // Skip inalloca arguments, they have already been written.
2739     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2740     if (Flags.isInAlloca())
2741       continue;
2742
2743     CCValAssign &VA = ArgLocs[i];
2744     EVT RegVT = VA.getLocVT();
2745     SDValue Arg = OutVals[i];
2746     bool isByVal = Flags.isByVal();
2747
2748     // Promote the value if needed.
2749     switch (VA.getLocInfo()) {
2750     default: llvm_unreachable("Unknown loc info!");
2751     case CCValAssign::Full: break;
2752     case CCValAssign::SExt:
2753       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2754       break;
2755     case CCValAssign::ZExt:
2756       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2757       break;
2758     case CCValAssign::AExt:
2759       if (RegVT.is128BitVector()) {
2760         // Special case: passing MMX values in XMM registers.
2761         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2762         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2763         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2764       } else
2765         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2766       break;
2767     case CCValAssign::BCvt:
2768       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2769       break;
2770     case CCValAssign::Indirect: {
2771       // Store the argument.
2772       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2773       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2774       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2775                            MachinePointerInfo::getFixedStack(FI),
2776                            false, false, 0);
2777       Arg = SpillSlot;
2778       break;
2779     }
2780     }
2781
2782     if (VA.isRegLoc()) {
2783       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2784       if (isVarArg && IsWin64) {
2785         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2786         // shadow reg if callee is a varargs function.
2787         unsigned ShadowReg = 0;
2788         switch (VA.getLocReg()) {
2789         case X86::XMM0: ShadowReg = X86::RCX; break;
2790         case X86::XMM1: ShadowReg = X86::RDX; break;
2791         case X86::XMM2: ShadowReg = X86::R8; break;
2792         case X86::XMM3: ShadowReg = X86::R9; break;
2793         }
2794         if (ShadowReg)
2795           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2796       }
2797     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2798       assert(VA.isMemLoc());
2799       if (!StackPtr.getNode())
2800         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2801                                       getPointerTy());
2802       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2803                                              dl, DAG, VA, Flags));
2804     }
2805   }
2806
2807   if (!MemOpChains.empty())
2808     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2809
2810   if (Subtarget->isPICStyleGOT()) {
2811     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2812     // GOT pointer.
2813     if (!isTailCall) {
2814       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2815                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2816     } else {
2817       // If we are tail calling and generating PIC/GOT style code load the
2818       // address of the callee into ECX. The value in ecx is used as target of
2819       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2820       // for tail calls on PIC/GOT architectures. Normally we would just put the
2821       // address of GOT into ebx and then call target@PLT. But for tail calls
2822       // ebx would be restored (since ebx is callee saved) before jumping to the
2823       // target@PLT.
2824
2825       // Note: The actual moving to ECX is done further down.
2826       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2827       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2828           !G->getGlobal()->hasProtectedVisibility())
2829         Callee = LowerGlobalAddress(Callee, DAG);
2830       else if (isa<ExternalSymbolSDNode>(Callee))
2831         Callee = LowerExternalSymbol(Callee, DAG);
2832     }
2833   }
2834
2835   if (Is64Bit && isVarArg && !IsWin64) {
2836     // From AMD64 ABI document:
2837     // For calls that may call functions that use varargs or stdargs
2838     // (prototype-less calls or calls to functions containing ellipsis (...) in
2839     // the declaration) %al is used as hidden argument to specify the number
2840     // of SSE registers used. The contents of %al do not need to match exactly
2841     // the number of registers, but must be an ubound on the number of SSE
2842     // registers used and is in the range 0 - 8 inclusive.
2843
2844     // Count the number of XMM registers allocated.
2845     static const MCPhysReg XMMArgRegs[] = {
2846       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2847       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2848     };
2849     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2850     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2851            && "SSE registers cannot be used when SSE is disabled");
2852
2853     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2854                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2855   }
2856
2857   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2858   // don't need this because the eligibility check rejects calls that require
2859   // shuffling arguments passed in memory.
2860   if (!IsSibcall && isTailCall) {
2861     // Force all the incoming stack arguments to be loaded from the stack
2862     // before any new outgoing arguments are stored to the stack, because the
2863     // outgoing stack slots may alias the incoming argument stack slots, and
2864     // the alias isn't otherwise explicit. This is slightly more conservative
2865     // than necessary, because it means that each store effectively depends
2866     // on every argument instead of just those arguments it would clobber.
2867     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2868
2869     SmallVector<SDValue, 8> MemOpChains2;
2870     SDValue FIN;
2871     int FI = 0;
2872     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2873       CCValAssign &VA = ArgLocs[i];
2874       if (VA.isRegLoc())
2875         continue;
2876       assert(VA.isMemLoc());
2877       SDValue Arg = OutVals[i];
2878       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2879       // Skip inalloca arguments.  They don't require any work.
2880       if (Flags.isInAlloca())
2881         continue;
2882       // Create frame index.
2883       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2884       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2885       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2886       FIN = DAG.getFrameIndex(FI, getPointerTy());
2887
2888       if (Flags.isByVal()) {
2889         // Copy relative to framepointer.
2890         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2891         if (!StackPtr.getNode())
2892           StackPtr = DAG.getCopyFromReg(Chain, dl,
2893                                         RegInfo->getStackRegister(),
2894                                         getPointerTy());
2895         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2896
2897         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2898                                                          ArgChain,
2899                                                          Flags, DAG, dl));
2900       } else {
2901         // Store relative to framepointer.
2902         MemOpChains2.push_back(
2903           DAG.getStore(ArgChain, dl, Arg, FIN,
2904                        MachinePointerInfo::getFixedStack(FI),
2905                        false, false, 0));
2906       }
2907     }
2908
2909     if (!MemOpChains2.empty())
2910       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2911
2912     // Store the return address to the appropriate stack slot.
2913     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2914                                      getPointerTy(), RegInfo->getSlotSize(),
2915                                      FPDiff, dl);
2916   }
2917
2918   // Build a sequence of copy-to-reg nodes chained together with token chain
2919   // and flag operands which copy the outgoing args into registers.
2920   SDValue InFlag;
2921   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2922     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2923                              RegsToPass[i].second, InFlag);
2924     InFlag = Chain.getValue(1);
2925   }
2926
2927   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2928     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2929     // In the 64-bit large code model, we have to make all calls
2930     // through a register, since the call instruction's 32-bit
2931     // pc-relative offset may not be large enough to hold the whole
2932     // address.
2933   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2934     // If the callee is a GlobalAddress node (quite common, every direct call
2935     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2936     // it.
2937
2938     // We should use extra load for direct calls to dllimported functions in
2939     // non-JIT mode.
2940     const GlobalValue *GV = G->getGlobal();
2941     if (!GV->hasDLLImportStorageClass()) {
2942       unsigned char OpFlags = 0;
2943       bool ExtraLoad = false;
2944       unsigned WrapperKind = ISD::DELETED_NODE;
2945
2946       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2947       // external symbols most go through the PLT in PIC mode.  If the symbol
2948       // has hidden or protected visibility, or if it is static or local, then
2949       // we don't need to use the PLT - we can directly call it.
2950       if (Subtarget->isTargetELF() &&
2951           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2952           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2953         OpFlags = X86II::MO_PLT;
2954       } else if (Subtarget->isPICStyleStubAny() &&
2955                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2956                  (!Subtarget->getTargetTriple().isMacOSX() ||
2957                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2958         // PC-relative references to external symbols should go through $stub,
2959         // unless we're building with the leopard linker or later, which
2960         // automatically synthesizes these stubs.
2961         OpFlags = X86II::MO_DARWIN_STUB;
2962       } else if (Subtarget->isPICStyleRIPRel() &&
2963                  isa<Function>(GV) &&
2964                  cast<Function>(GV)->getAttributes().
2965                    hasAttribute(AttributeSet::FunctionIndex,
2966                                 Attribute::NonLazyBind)) {
2967         // If the function is marked as non-lazy, generate an indirect call
2968         // which loads from the GOT directly. This avoids runtime overhead
2969         // at the cost of eager binding (and one extra byte of encoding).
2970         OpFlags = X86II::MO_GOTPCREL;
2971         WrapperKind = X86ISD::WrapperRIP;
2972         ExtraLoad = true;
2973       }
2974
2975       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2976                                           G->getOffset(), OpFlags);
2977
2978       // Add a wrapper if needed.
2979       if (WrapperKind != ISD::DELETED_NODE)
2980         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2981       // Add extra indirection if needed.
2982       if (ExtraLoad)
2983         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2984                              MachinePointerInfo::getGOT(),
2985                              false, false, false, 0);
2986     }
2987   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2988     unsigned char OpFlags = 0;
2989
2990     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2991     // external symbols should go through the PLT.
2992     if (Subtarget->isTargetELF() &&
2993         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2994       OpFlags = X86II::MO_PLT;
2995     } else if (Subtarget->isPICStyleStubAny() &&
2996                (!Subtarget->getTargetTriple().isMacOSX() ||
2997                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2998       // PC-relative references to external symbols should go through $stub,
2999       // unless we're building with the leopard linker or later, which
3000       // automatically synthesizes these stubs.
3001       OpFlags = X86II::MO_DARWIN_STUB;
3002     }
3003
3004     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3005                                          OpFlags);
3006   }
3007
3008   // Returns a chain & a flag for retval copy to use.
3009   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3010   SmallVector<SDValue, 8> Ops;
3011
3012   if (!IsSibcall && isTailCall) {
3013     Chain = DAG.getCALLSEQ_END(Chain,
3014                                DAG.getIntPtrConstant(NumBytesToPop, true),
3015                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3016     InFlag = Chain.getValue(1);
3017   }
3018
3019   Ops.push_back(Chain);
3020   Ops.push_back(Callee);
3021
3022   if (isTailCall)
3023     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3024
3025   // Add argument registers to the end of the list so that they are known live
3026   // into the call.
3027   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3028     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3029                                   RegsToPass[i].second.getValueType()));
3030
3031   // Add a register mask operand representing the call-preserved registers.
3032   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3033   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3034   assert(Mask && "Missing call preserved mask for calling convention");
3035   Ops.push_back(DAG.getRegisterMask(Mask));
3036
3037   if (InFlag.getNode())
3038     Ops.push_back(InFlag);
3039
3040   if (isTailCall) {
3041     // We used to do:
3042     //// If this is the first return lowered for this function, add the regs
3043     //// to the liveout set for the function.
3044     // This isn't right, although it's probably harmless on x86; liveouts
3045     // should be computed from returns not tail calls.  Consider a void
3046     // function making a tail call to a function returning int.
3047     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3048   }
3049
3050   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3051   InFlag = Chain.getValue(1);
3052
3053   // Create the CALLSEQ_END node.
3054   unsigned NumBytesForCalleeToPop;
3055   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3056                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3057     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3058   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3059            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3060            SR == StackStructReturn)
3061     // If this is a call to a struct-return function, the callee
3062     // pops the hidden struct pointer, so we have to push it back.
3063     // This is common for Darwin/X86, Linux & Mingw32 targets.
3064     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3065     NumBytesForCalleeToPop = 4;
3066   else
3067     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3068
3069   // Returns a flag for retval copy to use.
3070   if (!IsSibcall) {
3071     Chain = DAG.getCALLSEQ_END(Chain,
3072                                DAG.getIntPtrConstant(NumBytesToPop, true),
3073                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3074                                                      true),
3075                                InFlag, dl);
3076     InFlag = Chain.getValue(1);
3077   }
3078
3079   // Handle result values, copying them out of physregs into vregs that we
3080   // return.
3081   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3082                          Ins, dl, DAG, InVals);
3083 }
3084
3085 //===----------------------------------------------------------------------===//
3086 //                Fast Calling Convention (tail call) implementation
3087 //===----------------------------------------------------------------------===//
3088
3089 //  Like std call, callee cleans arguments, convention except that ECX is
3090 //  reserved for storing the tail called function address. Only 2 registers are
3091 //  free for argument passing (inreg). Tail call optimization is performed
3092 //  provided:
3093 //                * tailcallopt is enabled
3094 //                * caller/callee are fastcc
3095 //  On X86_64 architecture with GOT-style position independent code only local
3096 //  (within module) calls are supported at the moment.
3097 //  To keep the stack aligned according to platform abi the function
3098 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3099 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3100 //  If a tail called function callee has more arguments than the caller the
3101 //  caller needs to make sure that there is room to move the RETADDR to. This is
3102 //  achieved by reserving an area the size of the argument delta right after the
3103 //  original RETADDR, but before the saved framepointer or the spilled registers
3104 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3105 //  stack layout:
3106 //    arg1
3107 //    arg2
3108 //    RETADDR
3109 //    [ new RETADDR
3110 //      move area ]
3111 //    (possible EBP)
3112 //    ESI
3113 //    EDI
3114 //    local1 ..
3115
3116 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3117 /// for a 16 byte align requirement.
3118 unsigned
3119 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3120                                                SelectionDAG& DAG) const {
3121   MachineFunction &MF = DAG.getMachineFunction();
3122   const TargetMachine &TM = MF.getTarget();
3123   const X86RegisterInfo *RegInfo =
3124     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3125   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3126   unsigned StackAlignment = TFI.getStackAlignment();
3127   uint64_t AlignMask = StackAlignment - 1;
3128   int64_t Offset = StackSize;
3129   unsigned SlotSize = RegInfo->getSlotSize();
3130   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3131     // Number smaller than 12 so just add the difference.
3132     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3133   } else {
3134     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3135     Offset = ((~AlignMask) & Offset) + StackAlignment +
3136       (StackAlignment-SlotSize);
3137   }
3138   return Offset;
3139 }
3140
3141 /// MatchingStackOffset - Return true if the given stack call argument is
3142 /// already available in the same position (relatively) of the caller's
3143 /// incoming argument stack.
3144 static
3145 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3146                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3147                          const X86InstrInfo *TII) {
3148   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3149   int FI = INT_MAX;
3150   if (Arg.getOpcode() == ISD::CopyFromReg) {
3151     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3152     if (!TargetRegisterInfo::isVirtualRegister(VR))
3153       return false;
3154     MachineInstr *Def = MRI->getVRegDef(VR);
3155     if (!Def)
3156       return false;
3157     if (!Flags.isByVal()) {
3158       if (!TII->isLoadFromStackSlot(Def, FI))
3159         return false;
3160     } else {
3161       unsigned Opcode = Def->getOpcode();
3162       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3163           Def->getOperand(1).isFI()) {
3164         FI = Def->getOperand(1).getIndex();
3165         Bytes = Flags.getByValSize();
3166       } else
3167         return false;
3168     }
3169   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3170     if (Flags.isByVal())
3171       // ByVal argument is passed in as a pointer but it's now being
3172       // dereferenced. e.g.
3173       // define @foo(%struct.X* %A) {
3174       //   tail call @bar(%struct.X* byval %A)
3175       // }
3176       return false;
3177     SDValue Ptr = Ld->getBasePtr();
3178     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3179     if (!FINode)
3180       return false;
3181     FI = FINode->getIndex();
3182   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3183     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3184     FI = FINode->getIndex();
3185     Bytes = Flags.getByValSize();
3186   } else
3187     return false;
3188
3189   assert(FI != INT_MAX);
3190   if (!MFI->isFixedObjectIndex(FI))
3191     return false;
3192   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3193 }
3194
3195 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3196 /// for tail call optimization. Targets which want to do tail call
3197 /// optimization should implement this function.
3198 bool
3199 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3200                                                      CallingConv::ID CalleeCC,
3201                                                      bool isVarArg,
3202                                                      bool isCalleeStructRet,
3203                                                      bool isCallerStructRet,
3204                                                      Type *RetTy,
3205                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3206                                     const SmallVectorImpl<SDValue> &OutVals,
3207                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3208                                                      SelectionDAG &DAG) const {
3209   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3210     return false;
3211
3212   // If -tailcallopt is specified, make fastcc functions tail-callable.
3213   const MachineFunction &MF = DAG.getMachineFunction();
3214   const Function *CallerF = MF.getFunction();
3215
3216   // If the function return type is x86_fp80 and the callee return type is not,
3217   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3218   // perform a tailcall optimization here.
3219   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3220     return false;
3221
3222   CallingConv::ID CallerCC = CallerF->getCallingConv();
3223   bool CCMatch = CallerCC == CalleeCC;
3224   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3225   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3226
3227   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3228     if (IsTailCallConvention(CalleeCC) && CCMatch)
3229       return true;
3230     return false;
3231   }
3232
3233   // Look for obvious safe cases to perform tail call optimization that do not
3234   // require ABI changes. This is what gcc calls sibcall.
3235
3236   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3237   // emit a special epilogue.
3238   const X86RegisterInfo *RegInfo =
3239     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3240   if (RegInfo->needsStackRealignment(MF))
3241     return false;
3242
3243   // Also avoid sibcall optimization if either caller or callee uses struct
3244   // return semantics.
3245   if (isCalleeStructRet || isCallerStructRet)
3246     return false;
3247
3248   // An stdcall/thiscall caller is expected to clean up its arguments; the
3249   // callee isn't going to do that.
3250   // FIXME: this is more restrictive than needed. We could produce a tailcall
3251   // when the stack adjustment matches. For example, with a thiscall that takes
3252   // only one argument.
3253   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3254                    CallerCC == CallingConv::X86_ThisCall))
3255     return false;
3256
3257   // Do not sibcall optimize vararg calls unless all arguments are passed via
3258   // registers.
3259   if (isVarArg && !Outs.empty()) {
3260
3261     // Optimizing for varargs on Win64 is unlikely to be safe without
3262     // additional testing.
3263     if (IsCalleeWin64 || IsCallerWin64)
3264       return false;
3265
3266     SmallVector<CCValAssign, 16> ArgLocs;
3267     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3268                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3269
3270     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3271     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3272       if (!ArgLocs[i].isRegLoc())
3273         return false;
3274   }
3275
3276   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3277   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3278   // this into a sibcall.
3279   bool Unused = false;
3280   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3281     if (!Ins[i].Used) {
3282       Unused = true;
3283       break;
3284     }
3285   }
3286   if (Unused) {
3287     SmallVector<CCValAssign, 16> RVLocs;
3288     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3289                    DAG.getTarget(), RVLocs, *DAG.getContext());
3290     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3291     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3292       CCValAssign &VA = RVLocs[i];
3293       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3294         return false;
3295     }
3296   }
3297
3298   // If the calling conventions do not match, then we'd better make sure the
3299   // results are returned in the same way as what the caller expects.
3300   if (!CCMatch) {
3301     SmallVector<CCValAssign, 16> RVLocs1;
3302     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3303                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3304     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3305
3306     SmallVector<CCValAssign, 16> RVLocs2;
3307     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3308                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3309     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3310
3311     if (RVLocs1.size() != RVLocs2.size())
3312       return false;
3313     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3314       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3315         return false;
3316       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3317         return false;
3318       if (RVLocs1[i].isRegLoc()) {
3319         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3320           return false;
3321       } else {
3322         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3323           return false;
3324       }
3325     }
3326   }
3327
3328   // If the callee takes no arguments then go on to check the results of the
3329   // call.
3330   if (!Outs.empty()) {
3331     // Check if stack adjustment is needed. For now, do not do this if any
3332     // argument is passed on the stack.
3333     SmallVector<CCValAssign, 16> ArgLocs;
3334     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3335                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3336
3337     // Allocate shadow area for Win64
3338     if (IsCalleeWin64)
3339       CCInfo.AllocateStack(32, 8);
3340
3341     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3342     if (CCInfo.getNextStackOffset()) {
3343       MachineFunction &MF = DAG.getMachineFunction();
3344       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3345         return false;
3346
3347       // Check if the arguments are already laid out in the right way as
3348       // the caller's fixed stack objects.
3349       MachineFrameInfo *MFI = MF.getFrameInfo();
3350       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3351       const X86InstrInfo *TII =
3352           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3353       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3354         CCValAssign &VA = ArgLocs[i];
3355         SDValue Arg = OutVals[i];
3356         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3357         if (VA.getLocInfo() == CCValAssign::Indirect)
3358           return false;
3359         if (!VA.isRegLoc()) {
3360           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3361                                    MFI, MRI, TII))
3362             return false;
3363         }
3364       }
3365     }
3366
3367     // If the tailcall address may be in a register, then make sure it's
3368     // possible to register allocate for it. In 32-bit, the call address can
3369     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3370     // callee-saved registers are restored. These happen to be the same
3371     // registers used to pass 'inreg' arguments so watch out for those.
3372     if (!Subtarget->is64Bit() &&
3373         ((!isa<GlobalAddressSDNode>(Callee) &&
3374           !isa<ExternalSymbolSDNode>(Callee)) ||
3375          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3376       unsigned NumInRegs = 0;
3377       // In PIC we need an extra register to formulate the address computation
3378       // for the callee.
3379       unsigned MaxInRegs =
3380         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3381
3382       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3383         CCValAssign &VA = ArgLocs[i];
3384         if (!VA.isRegLoc())
3385           continue;
3386         unsigned Reg = VA.getLocReg();
3387         switch (Reg) {
3388         default: break;
3389         case X86::EAX: case X86::EDX: case X86::ECX:
3390           if (++NumInRegs == MaxInRegs)
3391             return false;
3392           break;
3393         }
3394       }
3395     }
3396   }
3397
3398   return true;
3399 }
3400
3401 FastISel *
3402 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3403                                   const TargetLibraryInfo *libInfo) const {
3404   return X86::createFastISel(funcInfo, libInfo);
3405 }
3406
3407 //===----------------------------------------------------------------------===//
3408 //                           Other Lowering Hooks
3409 //===----------------------------------------------------------------------===//
3410
3411 static bool MayFoldLoad(SDValue Op) {
3412   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3413 }
3414
3415 static bool MayFoldIntoStore(SDValue Op) {
3416   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3417 }
3418
3419 static bool isTargetShuffle(unsigned Opcode) {
3420   switch(Opcode) {
3421   default: return false;
3422   case X86ISD::PSHUFD:
3423   case X86ISD::PSHUFHW:
3424   case X86ISD::PSHUFLW:
3425   case X86ISD::SHUFP:
3426   case X86ISD::PALIGNR:
3427   case X86ISD::MOVLHPS:
3428   case X86ISD::MOVLHPD:
3429   case X86ISD::MOVHLPS:
3430   case X86ISD::MOVLPS:
3431   case X86ISD::MOVLPD:
3432   case X86ISD::MOVSHDUP:
3433   case X86ISD::MOVSLDUP:
3434   case X86ISD::MOVDDUP:
3435   case X86ISD::MOVSS:
3436   case X86ISD::MOVSD:
3437   case X86ISD::UNPCKL:
3438   case X86ISD::UNPCKH:
3439   case X86ISD::VPERMILP:
3440   case X86ISD::VPERM2X128:
3441   case X86ISD::VPERMI:
3442     return true;
3443   }
3444 }
3445
3446 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3447                                     SDValue V1, SelectionDAG &DAG) {
3448   switch(Opc) {
3449   default: llvm_unreachable("Unknown x86 shuffle node");
3450   case X86ISD::MOVSHDUP:
3451   case X86ISD::MOVSLDUP:
3452   case X86ISD::MOVDDUP:
3453     return DAG.getNode(Opc, dl, VT, V1);
3454   }
3455 }
3456
3457 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3458                                     SDValue V1, unsigned TargetMask,
3459                                     SelectionDAG &DAG) {
3460   switch(Opc) {
3461   default: llvm_unreachable("Unknown x86 shuffle node");
3462   case X86ISD::PSHUFD:
3463   case X86ISD::PSHUFHW:
3464   case X86ISD::PSHUFLW:
3465   case X86ISD::VPERMILP:
3466   case X86ISD::VPERMI:
3467     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3468   }
3469 }
3470
3471 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3472                                     SDValue V1, SDValue V2, unsigned TargetMask,
3473                                     SelectionDAG &DAG) {
3474   switch(Opc) {
3475   default: llvm_unreachable("Unknown x86 shuffle node");
3476   case X86ISD::PALIGNR:
3477   case X86ISD::SHUFP:
3478   case X86ISD::VPERM2X128:
3479     return DAG.getNode(Opc, dl, VT, V1, V2,
3480                        DAG.getConstant(TargetMask, MVT::i8));
3481   }
3482 }
3483
3484 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3485                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3486   switch(Opc) {
3487   default: llvm_unreachable("Unknown x86 shuffle node");
3488   case X86ISD::MOVLHPS:
3489   case X86ISD::MOVLHPD:
3490   case X86ISD::MOVHLPS:
3491   case X86ISD::MOVLPS:
3492   case X86ISD::MOVLPD:
3493   case X86ISD::MOVSS:
3494   case X86ISD::MOVSD:
3495   case X86ISD::UNPCKL:
3496   case X86ISD::UNPCKH:
3497     return DAG.getNode(Opc, dl, VT, V1, V2);
3498   }
3499 }
3500
3501 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3502   MachineFunction &MF = DAG.getMachineFunction();
3503   const X86RegisterInfo *RegInfo =
3504     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3505   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3506   int ReturnAddrIndex = FuncInfo->getRAIndex();
3507
3508   if (ReturnAddrIndex == 0) {
3509     // Set up a frame object for the return address.
3510     unsigned SlotSize = RegInfo->getSlotSize();
3511     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3512                                                            -(int64_t)SlotSize,
3513                                                            false);
3514     FuncInfo->setRAIndex(ReturnAddrIndex);
3515   }
3516
3517   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3518 }
3519
3520 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3521                                        bool hasSymbolicDisplacement) {
3522   // Offset should fit into 32 bit immediate field.
3523   if (!isInt<32>(Offset))
3524     return false;
3525
3526   // If we don't have a symbolic displacement - we don't have any extra
3527   // restrictions.
3528   if (!hasSymbolicDisplacement)
3529     return true;
3530
3531   // FIXME: Some tweaks might be needed for medium code model.
3532   if (M != CodeModel::Small && M != CodeModel::Kernel)
3533     return false;
3534
3535   // For small code model we assume that latest object is 16MB before end of 31
3536   // bits boundary. We may also accept pretty large negative constants knowing
3537   // that all objects are in the positive half of address space.
3538   if (M == CodeModel::Small && Offset < 16*1024*1024)
3539     return true;
3540
3541   // For kernel code model we know that all object resist in the negative half
3542   // of 32bits address space. We may not accept negative offsets, since they may
3543   // be just off and we may accept pretty large positive ones.
3544   if (M == CodeModel::Kernel && Offset > 0)
3545     return true;
3546
3547   return false;
3548 }
3549
3550 /// isCalleePop - Determines whether the callee is required to pop its
3551 /// own arguments. Callee pop is necessary to support tail calls.
3552 bool X86::isCalleePop(CallingConv::ID CallingConv,
3553                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3554   if (IsVarArg)
3555     return false;
3556
3557   switch (CallingConv) {
3558   default:
3559     return false;
3560   case CallingConv::X86_StdCall:
3561     return !is64Bit;
3562   case CallingConv::X86_FastCall:
3563     return !is64Bit;
3564   case CallingConv::X86_ThisCall:
3565     return !is64Bit;
3566   case CallingConv::Fast:
3567     return TailCallOpt;
3568   case CallingConv::GHC:
3569     return TailCallOpt;
3570   case CallingConv::HiPE:
3571     return TailCallOpt;
3572   }
3573 }
3574
3575 /// \brief Return true if the condition is an unsigned comparison operation.
3576 static bool isX86CCUnsigned(unsigned X86CC) {
3577   switch (X86CC) {
3578   default: llvm_unreachable("Invalid integer condition!");
3579   case X86::COND_E:     return true;
3580   case X86::COND_G:     return false;
3581   case X86::COND_GE:    return false;
3582   case X86::COND_L:     return false;
3583   case X86::COND_LE:    return false;
3584   case X86::COND_NE:    return true;
3585   case X86::COND_B:     return true;
3586   case X86::COND_A:     return true;
3587   case X86::COND_BE:    return true;
3588   case X86::COND_AE:    return true;
3589   }
3590   llvm_unreachable("covered switch fell through?!");
3591 }
3592
3593 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3594 /// specific condition code, returning the condition code and the LHS/RHS of the
3595 /// comparison to make.
3596 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3597                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3598   if (!isFP) {
3599     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3600       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3601         // X > -1   -> X == 0, jump !sign.
3602         RHS = DAG.getConstant(0, RHS.getValueType());
3603         return X86::COND_NS;
3604       }
3605       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3606         // X < 0   -> X == 0, jump on sign.
3607         return X86::COND_S;
3608       }
3609       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3610         // X < 1   -> X <= 0
3611         RHS = DAG.getConstant(0, RHS.getValueType());
3612         return X86::COND_LE;
3613       }
3614     }
3615
3616     switch (SetCCOpcode) {
3617     default: llvm_unreachable("Invalid integer condition!");
3618     case ISD::SETEQ:  return X86::COND_E;
3619     case ISD::SETGT:  return X86::COND_G;
3620     case ISD::SETGE:  return X86::COND_GE;
3621     case ISD::SETLT:  return X86::COND_L;
3622     case ISD::SETLE:  return X86::COND_LE;
3623     case ISD::SETNE:  return X86::COND_NE;
3624     case ISD::SETULT: return X86::COND_B;
3625     case ISD::SETUGT: return X86::COND_A;
3626     case ISD::SETULE: return X86::COND_BE;
3627     case ISD::SETUGE: return X86::COND_AE;
3628     }
3629   }
3630
3631   // First determine if it is required or is profitable to flip the operands.
3632
3633   // If LHS is a foldable load, but RHS is not, flip the condition.
3634   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3635       !ISD::isNON_EXTLoad(RHS.getNode())) {
3636     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3637     std::swap(LHS, RHS);
3638   }
3639
3640   switch (SetCCOpcode) {
3641   default: break;
3642   case ISD::SETOLT:
3643   case ISD::SETOLE:
3644   case ISD::SETUGT:
3645   case ISD::SETUGE:
3646     std::swap(LHS, RHS);
3647     break;
3648   }
3649
3650   // On a floating point condition, the flags are set as follows:
3651   // ZF  PF  CF   op
3652   //  0 | 0 | 0 | X > Y
3653   //  0 | 0 | 1 | X < Y
3654   //  1 | 0 | 0 | X == Y
3655   //  1 | 1 | 1 | unordered
3656   switch (SetCCOpcode) {
3657   default: llvm_unreachable("Condcode should be pre-legalized away");
3658   case ISD::SETUEQ:
3659   case ISD::SETEQ:   return X86::COND_E;
3660   case ISD::SETOLT:              // flipped
3661   case ISD::SETOGT:
3662   case ISD::SETGT:   return X86::COND_A;
3663   case ISD::SETOLE:              // flipped
3664   case ISD::SETOGE:
3665   case ISD::SETGE:   return X86::COND_AE;
3666   case ISD::SETUGT:              // flipped
3667   case ISD::SETULT:
3668   case ISD::SETLT:   return X86::COND_B;
3669   case ISD::SETUGE:              // flipped
3670   case ISD::SETULE:
3671   case ISD::SETLE:   return X86::COND_BE;
3672   case ISD::SETONE:
3673   case ISD::SETNE:   return X86::COND_NE;
3674   case ISD::SETUO:   return X86::COND_P;
3675   case ISD::SETO:    return X86::COND_NP;
3676   case ISD::SETOEQ:
3677   case ISD::SETUNE:  return X86::COND_INVALID;
3678   }
3679 }
3680
3681 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3682 /// code. Current x86 isa includes the following FP cmov instructions:
3683 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3684 static bool hasFPCMov(unsigned X86CC) {
3685   switch (X86CC) {
3686   default:
3687     return false;
3688   case X86::COND_B:
3689   case X86::COND_BE:
3690   case X86::COND_E:
3691   case X86::COND_P:
3692   case X86::COND_A:
3693   case X86::COND_AE:
3694   case X86::COND_NE:
3695   case X86::COND_NP:
3696     return true;
3697   }
3698 }
3699
3700 /// isFPImmLegal - Returns true if the target can instruction select the
3701 /// specified FP immediate natively. If false, the legalizer will
3702 /// materialize the FP immediate as a load from a constant pool.
3703 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3704   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3705     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3706       return true;
3707   }
3708   return false;
3709 }
3710
3711 /// \brief Returns true if it is beneficial to convert a load of a constant
3712 /// to just the constant itself.
3713 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3714                                                           Type *Ty) const {
3715   assert(Ty->isIntegerTy());
3716
3717   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3718   if (BitSize == 0 || BitSize > 64)
3719     return false;
3720   return true;
3721 }
3722
3723 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3724 /// the specified range (L, H].
3725 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3726   return (Val < 0) || (Val >= Low && Val < Hi);
3727 }
3728
3729 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3730 /// specified value.
3731 static bool isUndefOrEqual(int Val, int CmpVal) {
3732   return (Val < 0 || Val == CmpVal);
3733 }
3734
3735 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3736 /// from position Pos and ending in Pos+Size, falls within the specified
3737 /// sequential range (L, L+Pos]. or is undef.
3738 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3739                                        unsigned Pos, unsigned Size, int Low) {
3740   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3741     if (!isUndefOrEqual(Mask[i], Low))
3742       return false;
3743   return true;
3744 }
3745
3746 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3747 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3748 /// the second operand.
3749 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3750   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3751     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3752   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3753     return (Mask[0] < 2 && Mask[1] < 2);
3754   return false;
3755 }
3756
3757 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3758 /// is suitable for input to PSHUFHW.
3759 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3760   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3761     return false;
3762
3763   // Lower quadword copied in order or undef.
3764   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3765     return false;
3766
3767   // Upper quadword shuffled.
3768   for (unsigned i = 4; i != 8; ++i)
3769     if (!isUndefOrInRange(Mask[i], 4, 8))
3770       return false;
3771
3772   if (VT == MVT::v16i16) {
3773     // Lower quadword copied in order or undef.
3774     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3775       return false;
3776
3777     // Upper quadword shuffled.
3778     for (unsigned i = 12; i != 16; ++i)
3779       if (!isUndefOrInRange(Mask[i], 12, 16))
3780         return false;
3781   }
3782
3783   return true;
3784 }
3785
3786 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3787 /// is suitable for input to PSHUFLW.
3788 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3789   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3790     return false;
3791
3792   // Upper quadword copied in order.
3793   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3794     return false;
3795
3796   // Lower quadword shuffled.
3797   for (unsigned i = 0; i != 4; ++i)
3798     if (!isUndefOrInRange(Mask[i], 0, 4))
3799       return false;
3800
3801   if (VT == MVT::v16i16) {
3802     // Upper quadword copied in order.
3803     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3804       return false;
3805
3806     // Lower quadword shuffled.
3807     for (unsigned i = 8; i != 12; ++i)
3808       if (!isUndefOrInRange(Mask[i], 8, 12))
3809         return false;
3810   }
3811
3812   return true;
3813 }
3814
3815 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3816 /// is suitable for input to PALIGNR.
3817 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3818                           const X86Subtarget *Subtarget) {
3819   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3820       (VT.is256BitVector() && !Subtarget->hasInt256()))
3821     return false;
3822
3823   unsigned NumElts = VT.getVectorNumElements();
3824   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3825   unsigned NumLaneElts = NumElts/NumLanes;
3826
3827   // Do not handle 64-bit element shuffles with palignr.
3828   if (NumLaneElts == 2)
3829     return false;
3830
3831   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3832     unsigned i;
3833     for (i = 0; i != NumLaneElts; ++i) {
3834       if (Mask[i+l] >= 0)
3835         break;
3836     }
3837
3838     // Lane is all undef, go to next lane
3839     if (i == NumLaneElts)
3840       continue;
3841
3842     int Start = Mask[i+l];
3843
3844     // Make sure its in this lane in one of the sources
3845     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3846         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3847       return false;
3848
3849     // If not lane 0, then we must match lane 0
3850     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3851       return false;
3852
3853     // Correct second source to be contiguous with first source
3854     if (Start >= (int)NumElts)
3855       Start -= NumElts - NumLaneElts;
3856
3857     // Make sure we're shifting in the right direction.
3858     if (Start <= (int)(i+l))
3859       return false;
3860
3861     Start -= i;
3862
3863     // Check the rest of the elements to see if they are consecutive.
3864     for (++i; i != NumLaneElts; ++i) {
3865       int Idx = Mask[i+l];
3866
3867       // Make sure its in this lane
3868       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3869           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3870         return false;
3871
3872       // If not lane 0, then we must match lane 0
3873       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3874         return false;
3875
3876       if (Idx >= (int)NumElts)
3877         Idx -= NumElts - NumLaneElts;
3878
3879       if (!isUndefOrEqual(Idx, Start+i))
3880         return false;
3881
3882     }
3883   }
3884
3885   return true;
3886 }
3887
3888 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3889 /// the two vector operands have swapped position.
3890 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3891                                      unsigned NumElems) {
3892   for (unsigned i = 0; i != NumElems; ++i) {
3893     int idx = Mask[i];
3894     if (idx < 0)
3895       continue;
3896     else if (idx < (int)NumElems)
3897       Mask[i] = idx + NumElems;
3898     else
3899       Mask[i] = idx - NumElems;
3900   }
3901 }
3902
3903 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3904 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3905 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3906 /// reverse of what x86 shuffles want.
3907 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3908
3909   unsigned NumElems = VT.getVectorNumElements();
3910   unsigned NumLanes = VT.getSizeInBits()/128;
3911   unsigned NumLaneElems = NumElems/NumLanes;
3912
3913   if (NumLaneElems != 2 && NumLaneElems != 4)
3914     return false;
3915
3916   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3917   bool symetricMaskRequired =
3918     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3919
3920   // VSHUFPSY divides the resulting vector into 4 chunks.
3921   // The sources are also splitted into 4 chunks, and each destination
3922   // chunk must come from a different source chunk.
3923   //
3924   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3925   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3926   //
3927   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3928   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3929   //
3930   // VSHUFPDY divides the resulting vector into 4 chunks.
3931   // The sources are also splitted into 4 chunks, and each destination
3932   // chunk must come from a different source chunk.
3933   //
3934   //  SRC1 =>      X3       X2       X1       X0
3935   //  SRC2 =>      Y3       Y2       Y1       Y0
3936   //
3937   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3938   //
3939   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3940   unsigned HalfLaneElems = NumLaneElems/2;
3941   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3942     for (unsigned i = 0; i != NumLaneElems; ++i) {
3943       int Idx = Mask[i+l];
3944       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3945       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3946         return false;
3947       // For VSHUFPSY, the mask of the second half must be the same as the
3948       // first but with the appropriate offsets. This works in the same way as
3949       // VPERMILPS works with masks.
3950       if (!symetricMaskRequired || Idx < 0)
3951         continue;
3952       if (MaskVal[i] < 0) {
3953         MaskVal[i] = Idx - l;
3954         continue;
3955       }
3956       if ((signed)(Idx - l) != MaskVal[i])
3957         return false;
3958     }
3959   }
3960
3961   return true;
3962 }
3963
3964 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3965 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3966 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3967   if (!VT.is128BitVector())
3968     return false;
3969
3970   unsigned NumElems = VT.getVectorNumElements();
3971
3972   if (NumElems != 4)
3973     return false;
3974
3975   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3976   return isUndefOrEqual(Mask[0], 6) &&
3977          isUndefOrEqual(Mask[1], 7) &&
3978          isUndefOrEqual(Mask[2], 2) &&
3979          isUndefOrEqual(Mask[3], 3);
3980 }
3981
3982 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3983 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3984 /// <2, 3, 2, 3>
3985 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3986   if (!VT.is128BitVector())
3987     return false;
3988
3989   unsigned NumElems = VT.getVectorNumElements();
3990
3991   if (NumElems != 4)
3992     return false;
3993
3994   return isUndefOrEqual(Mask[0], 2) &&
3995          isUndefOrEqual(Mask[1], 3) &&
3996          isUndefOrEqual(Mask[2], 2) &&
3997          isUndefOrEqual(Mask[3], 3);
3998 }
3999
4000 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4001 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4002 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4003   if (!VT.is128BitVector())
4004     return false;
4005
4006   unsigned NumElems = VT.getVectorNumElements();
4007
4008   if (NumElems != 2 && NumElems != 4)
4009     return false;
4010
4011   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4012     if (!isUndefOrEqual(Mask[i], i + NumElems))
4013       return false;
4014
4015   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4016     if (!isUndefOrEqual(Mask[i], i))
4017       return false;
4018
4019   return true;
4020 }
4021
4022 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4023 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4024 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4025   if (!VT.is128BitVector())
4026     return false;
4027
4028   unsigned NumElems = VT.getVectorNumElements();
4029
4030   if (NumElems != 2 && NumElems != 4)
4031     return false;
4032
4033   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4034     if (!isUndefOrEqual(Mask[i], i))
4035       return false;
4036
4037   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4038     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4039       return false;
4040
4041   return true;
4042 }
4043
4044 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4045 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4046 /// i. e: If all but one element come from the same vector.
4047 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4048   // TODO: Deal with AVX's VINSERTPS
4049   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4050     return false;
4051
4052   unsigned CorrectPosV1 = 0;
4053   unsigned CorrectPosV2 = 0;
4054   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4055     if (Mask[i] == -1) {
4056       ++CorrectPosV1;
4057       ++CorrectPosV2;
4058       continue;
4059     }
4060
4061     if (Mask[i] == i)
4062       ++CorrectPosV1;
4063     else if (Mask[i] == i + 4)
4064       ++CorrectPosV2;
4065   }
4066
4067   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4068     // We have 3 elements (undefs count as elements from any vector) from one
4069     // vector, and one from another.
4070     return true;
4071
4072   return false;
4073 }
4074
4075 //
4076 // Some special combinations that can be optimized.
4077 //
4078 static
4079 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4080                                SelectionDAG &DAG) {
4081   MVT VT = SVOp->getSimpleValueType(0);
4082   SDLoc dl(SVOp);
4083
4084   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4085     return SDValue();
4086
4087   ArrayRef<int> Mask = SVOp->getMask();
4088
4089   // These are the special masks that may be optimized.
4090   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4091   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4092   bool MatchEvenMask = true;
4093   bool MatchOddMask  = true;
4094   for (int i=0; i<8; ++i) {
4095     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4096       MatchEvenMask = false;
4097     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4098       MatchOddMask = false;
4099   }
4100
4101   if (!MatchEvenMask && !MatchOddMask)
4102     return SDValue();
4103
4104   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4105
4106   SDValue Op0 = SVOp->getOperand(0);
4107   SDValue Op1 = SVOp->getOperand(1);
4108
4109   if (MatchEvenMask) {
4110     // Shift the second operand right to 32 bits.
4111     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4112     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4113   } else {
4114     // Shift the first operand left to 32 bits.
4115     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4116     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4117   }
4118   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4119   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4120 }
4121
4122 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4123 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4124 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4125                          bool HasInt256, bool V2IsSplat = false) {
4126
4127   assert(VT.getSizeInBits() >= 128 &&
4128          "Unsupported vector type for unpckl");
4129
4130   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4131   unsigned NumLanes;
4132   unsigned NumOf256BitLanes;
4133   unsigned NumElts = VT.getVectorNumElements();
4134   if (VT.is256BitVector()) {
4135     if (NumElts != 4 && NumElts != 8 &&
4136         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4137     return false;
4138     NumLanes = 2;
4139     NumOf256BitLanes = 1;
4140   } else if (VT.is512BitVector()) {
4141     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4142            "Unsupported vector type for unpckh");
4143     NumLanes = 2;
4144     NumOf256BitLanes = 2;
4145   } else {
4146     NumLanes = 1;
4147     NumOf256BitLanes = 1;
4148   }
4149
4150   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4151   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4152
4153   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4154     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4155       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4156         int BitI  = Mask[l256*NumEltsInStride+l+i];
4157         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4158         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4159           return false;
4160         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4161           return false;
4162         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4163           return false;
4164       }
4165     }
4166   }
4167   return true;
4168 }
4169
4170 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4171 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4172 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4173                          bool HasInt256, bool V2IsSplat = false) {
4174   assert(VT.getSizeInBits() >= 128 &&
4175          "Unsupported vector type for unpckh");
4176
4177   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4178   unsigned NumLanes;
4179   unsigned NumOf256BitLanes;
4180   unsigned NumElts = VT.getVectorNumElements();
4181   if (VT.is256BitVector()) {
4182     if (NumElts != 4 && NumElts != 8 &&
4183         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4184     return false;
4185     NumLanes = 2;
4186     NumOf256BitLanes = 1;
4187   } else if (VT.is512BitVector()) {
4188     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4189            "Unsupported vector type for unpckh");
4190     NumLanes = 2;
4191     NumOf256BitLanes = 2;
4192   } else {
4193     NumLanes = 1;
4194     NumOf256BitLanes = 1;
4195   }
4196
4197   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4198   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4199
4200   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4201     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4202       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4203         int BitI  = Mask[l256*NumEltsInStride+l+i];
4204         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4205         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4206           return false;
4207         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4208           return false;
4209         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4210           return false;
4211       }
4212     }
4213   }
4214   return true;
4215 }
4216
4217 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4218 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4219 /// <0, 0, 1, 1>
4220 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4221   unsigned NumElts = VT.getVectorNumElements();
4222   bool Is256BitVec = VT.is256BitVector();
4223
4224   if (VT.is512BitVector())
4225     return false;
4226   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4227          "Unsupported vector type for unpckh");
4228
4229   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4230       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4231     return false;
4232
4233   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4234   // FIXME: Need a better way to get rid of this, there's no latency difference
4235   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4236   // the former later. We should also remove the "_undef" special mask.
4237   if (NumElts == 4 && Is256BitVec)
4238     return false;
4239
4240   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4241   // independently on 128-bit lanes.
4242   unsigned NumLanes = VT.getSizeInBits()/128;
4243   unsigned NumLaneElts = NumElts/NumLanes;
4244
4245   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4246     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4247       int BitI  = Mask[l+i];
4248       int BitI1 = Mask[l+i+1];
4249
4250       if (!isUndefOrEqual(BitI, j))
4251         return false;
4252       if (!isUndefOrEqual(BitI1, j))
4253         return false;
4254     }
4255   }
4256
4257   return true;
4258 }
4259
4260 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4261 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4262 /// <2, 2, 3, 3>
4263 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4264   unsigned NumElts = VT.getVectorNumElements();
4265
4266   if (VT.is512BitVector())
4267     return false;
4268
4269   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4270          "Unsupported vector type for unpckh");
4271
4272   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4273       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4274     return false;
4275
4276   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4277   // independently on 128-bit lanes.
4278   unsigned NumLanes = VT.getSizeInBits()/128;
4279   unsigned NumLaneElts = NumElts/NumLanes;
4280
4281   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4282     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4283       int BitI  = Mask[l+i];
4284       int BitI1 = Mask[l+i+1];
4285       if (!isUndefOrEqual(BitI, j))
4286         return false;
4287       if (!isUndefOrEqual(BitI1, j))
4288         return false;
4289     }
4290   }
4291   return true;
4292 }
4293
4294 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4295 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4296 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4297   if (!VT.is512BitVector())
4298     return false;
4299
4300   unsigned NumElts = VT.getVectorNumElements();
4301   unsigned HalfSize = NumElts/2;
4302   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4303     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4304       *Imm = 1;
4305       return true;
4306     }
4307   }
4308   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4309     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4310       *Imm = 0;
4311       return true;
4312     }
4313   }
4314   return false;
4315 }
4316
4317 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4318 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4319 /// MOVSD, and MOVD, i.e. setting the lowest element.
4320 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4321   if (VT.getVectorElementType().getSizeInBits() < 32)
4322     return false;
4323   if (!VT.is128BitVector())
4324     return false;
4325
4326   unsigned NumElts = VT.getVectorNumElements();
4327
4328   if (!isUndefOrEqual(Mask[0], NumElts))
4329     return false;
4330
4331   for (unsigned i = 1; i != NumElts; ++i)
4332     if (!isUndefOrEqual(Mask[i], i))
4333       return false;
4334
4335   return true;
4336 }
4337
4338 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4339 /// as permutations between 128-bit chunks or halves. As an example: this
4340 /// shuffle bellow:
4341 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4342 /// The first half comes from the second half of V1 and the second half from the
4343 /// the second half of V2.
4344 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4345   if (!HasFp256 || !VT.is256BitVector())
4346     return false;
4347
4348   // The shuffle result is divided into half A and half B. In total the two
4349   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4350   // B must come from C, D, E or F.
4351   unsigned HalfSize = VT.getVectorNumElements()/2;
4352   bool MatchA = false, MatchB = false;
4353
4354   // Check if A comes from one of C, D, E, F.
4355   for (unsigned Half = 0; Half != 4; ++Half) {
4356     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4357       MatchA = true;
4358       break;
4359     }
4360   }
4361
4362   // Check if B comes from one of C, D, E, F.
4363   for (unsigned Half = 0; Half != 4; ++Half) {
4364     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4365       MatchB = true;
4366       break;
4367     }
4368   }
4369
4370   return MatchA && MatchB;
4371 }
4372
4373 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4374 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4375 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4376   MVT VT = SVOp->getSimpleValueType(0);
4377
4378   unsigned HalfSize = VT.getVectorNumElements()/2;
4379
4380   unsigned FstHalf = 0, SndHalf = 0;
4381   for (unsigned i = 0; i < HalfSize; ++i) {
4382     if (SVOp->getMaskElt(i) > 0) {
4383       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4384       break;
4385     }
4386   }
4387   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4388     if (SVOp->getMaskElt(i) > 0) {
4389       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4390       break;
4391     }
4392   }
4393
4394   return (FstHalf | (SndHalf << 4));
4395 }
4396
4397 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4398 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4399   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4400   if (EltSize < 32)
4401     return false;
4402
4403   unsigned NumElts = VT.getVectorNumElements();
4404   Imm8 = 0;
4405   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4406     for (unsigned i = 0; i != NumElts; ++i) {
4407       if (Mask[i] < 0)
4408         continue;
4409       Imm8 |= Mask[i] << (i*2);
4410     }
4411     return true;
4412   }
4413
4414   unsigned LaneSize = 4;
4415   SmallVector<int, 4> MaskVal(LaneSize, -1);
4416
4417   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4418     for (unsigned i = 0; i != LaneSize; ++i) {
4419       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4420         return false;
4421       if (Mask[i+l] < 0)
4422         continue;
4423       if (MaskVal[i] < 0) {
4424         MaskVal[i] = Mask[i+l] - l;
4425         Imm8 |= MaskVal[i] << (i*2);
4426         continue;
4427       }
4428       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4429         return false;
4430     }
4431   }
4432   return true;
4433 }
4434
4435 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4436 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4437 /// Note that VPERMIL mask matching is different depending whether theunderlying
4438 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4439 /// to the same elements of the low, but to the higher half of the source.
4440 /// In VPERMILPD the two lanes could be shuffled independently of each other
4441 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4442 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4443   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4444   if (VT.getSizeInBits() < 256 || EltSize < 32)
4445     return false;
4446   bool symetricMaskRequired = (EltSize == 32);
4447   unsigned NumElts = VT.getVectorNumElements();
4448
4449   unsigned NumLanes = VT.getSizeInBits()/128;
4450   unsigned LaneSize = NumElts/NumLanes;
4451   // 2 or 4 elements in one lane
4452
4453   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4454   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4455     for (unsigned i = 0; i != LaneSize; ++i) {
4456       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4457         return false;
4458       if (symetricMaskRequired) {
4459         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4460           ExpectedMaskVal[i] = Mask[i+l] - l;
4461           continue;
4462         }
4463         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4464           return false;
4465       }
4466     }
4467   }
4468   return true;
4469 }
4470
4471 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4472 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4473 /// element of vector 2 and the other elements to come from vector 1 in order.
4474 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4475                                bool V2IsSplat = false, bool V2IsUndef = false) {
4476   if (!VT.is128BitVector())
4477     return false;
4478
4479   unsigned NumOps = VT.getVectorNumElements();
4480   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4481     return false;
4482
4483   if (!isUndefOrEqual(Mask[0], 0))
4484     return false;
4485
4486   for (unsigned i = 1; i != NumOps; ++i)
4487     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4488           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4489           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4490       return false;
4491
4492   return true;
4493 }
4494
4495 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4496 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4497 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4498 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4499                            const X86Subtarget *Subtarget) {
4500   if (!Subtarget->hasSSE3())
4501     return false;
4502
4503   unsigned NumElems = VT.getVectorNumElements();
4504
4505   if ((VT.is128BitVector() && NumElems != 4) ||
4506       (VT.is256BitVector() && NumElems != 8) ||
4507       (VT.is512BitVector() && NumElems != 16))
4508     return false;
4509
4510   // "i+1" is the value the indexed mask element must have
4511   for (unsigned i = 0; i != NumElems; i += 2)
4512     if (!isUndefOrEqual(Mask[i], i+1) ||
4513         !isUndefOrEqual(Mask[i+1], i+1))
4514       return false;
4515
4516   return true;
4517 }
4518
4519 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4520 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4521 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4522 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4523                            const X86Subtarget *Subtarget) {
4524   if (!Subtarget->hasSSE3())
4525     return false;
4526
4527   unsigned NumElems = VT.getVectorNumElements();
4528
4529   if ((VT.is128BitVector() && NumElems != 4) ||
4530       (VT.is256BitVector() && NumElems != 8) ||
4531       (VT.is512BitVector() && NumElems != 16))
4532     return false;
4533
4534   // "i" is the value the indexed mask element must have
4535   for (unsigned i = 0; i != NumElems; i += 2)
4536     if (!isUndefOrEqual(Mask[i], i) ||
4537         !isUndefOrEqual(Mask[i+1], i))
4538       return false;
4539
4540   return true;
4541 }
4542
4543 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4544 /// specifies a shuffle of elements that is suitable for input to 256-bit
4545 /// version of MOVDDUP.
4546 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4547   if (!HasFp256 || !VT.is256BitVector())
4548     return false;
4549
4550   unsigned NumElts = VT.getVectorNumElements();
4551   if (NumElts != 4)
4552     return false;
4553
4554   for (unsigned i = 0; i != NumElts/2; ++i)
4555     if (!isUndefOrEqual(Mask[i], 0))
4556       return false;
4557   for (unsigned i = NumElts/2; i != NumElts; ++i)
4558     if (!isUndefOrEqual(Mask[i], NumElts/2))
4559       return false;
4560   return true;
4561 }
4562
4563 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4564 /// specifies a shuffle of elements that is suitable for input to 128-bit
4565 /// version of MOVDDUP.
4566 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4567   if (!VT.is128BitVector())
4568     return false;
4569
4570   unsigned e = VT.getVectorNumElements() / 2;
4571   for (unsigned i = 0; i != e; ++i)
4572     if (!isUndefOrEqual(Mask[i], i))
4573       return false;
4574   for (unsigned i = 0; i != e; ++i)
4575     if (!isUndefOrEqual(Mask[e+i], i))
4576       return false;
4577   return true;
4578 }
4579
4580 /// isVEXTRACTIndex - Return true if the specified
4581 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4582 /// suitable for instruction that extract 128 or 256 bit vectors
4583 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4584   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4585   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4586     return false;
4587
4588   // The index should be aligned on a vecWidth-bit boundary.
4589   uint64_t Index =
4590     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4591
4592   MVT VT = N->getSimpleValueType(0);
4593   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4594   bool Result = (Index * ElSize) % vecWidth == 0;
4595
4596   return Result;
4597 }
4598
4599 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4600 /// operand specifies a subvector insert that is suitable for input to
4601 /// insertion of 128 or 256-bit subvectors
4602 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4603   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4604   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4605     return false;
4606   // The index should be aligned on a vecWidth-bit boundary.
4607   uint64_t Index =
4608     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4609
4610   MVT VT = N->getSimpleValueType(0);
4611   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4612   bool Result = (Index * ElSize) % vecWidth == 0;
4613
4614   return Result;
4615 }
4616
4617 bool X86::isVINSERT128Index(SDNode *N) {
4618   return isVINSERTIndex(N, 128);
4619 }
4620
4621 bool X86::isVINSERT256Index(SDNode *N) {
4622   return isVINSERTIndex(N, 256);
4623 }
4624
4625 bool X86::isVEXTRACT128Index(SDNode *N) {
4626   return isVEXTRACTIndex(N, 128);
4627 }
4628
4629 bool X86::isVEXTRACT256Index(SDNode *N) {
4630   return isVEXTRACTIndex(N, 256);
4631 }
4632
4633 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4634 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4635 /// Handles 128-bit and 256-bit.
4636 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4637   MVT VT = N->getSimpleValueType(0);
4638
4639   assert((VT.getSizeInBits() >= 128) &&
4640          "Unsupported vector type for PSHUF/SHUFP");
4641
4642   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4643   // independently on 128-bit lanes.
4644   unsigned NumElts = VT.getVectorNumElements();
4645   unsigned NumLanes = VT.getSizeInBits()/128;
4646   unsigned NumLaneElts = NumElts/NumLanes;
4647
4648   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4649          "Only supports 2, 4 or 8 elements per lane");
4650
4651   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4652   unsigned Mask = 0;
4653   for (unsigned i = 0; i != NumElts; ++i) {
4654     int Elt = N->getMaskElt(i);
4655     if (Elt < 0) continue;
4656     Elt &= NumLaneElts - 1;
4657     unsigned ShAmt = (i << Shift) % 8;
4658     Mask |= Elt << ShAmt;
4659   }
4660
4661   return Mask;
4662 }
4663
4664 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4665 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4666 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4667   MVT VT = N->getSimpleValueType(0);
4668
4669   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4670          "Unsupported vector type for PSHUFHW");
4671
4672   unsigned NumElts = VT.getVectorNumElements();
4673
4674   unsigned Mask = 0;
4675   for (unsigned l = 0; l != NumElts; l += 8) {
4676     // 8 nodes per lane, but we only care about the last 4.
4677     for (unsigned i = 0; i < 4; ++i) {
4678       int Elt = N->getMaskElt(l+i+4);
4679       if (Elt < 0) continue;
4680       Elt &= 0x3; // only 2-bits.
4681       Mask |= Elt << (i * 2);
4682     }
4683   }
4684
4685   return Mask;
4686 }
4687
4688 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4689 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4690 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4691   MVT VT = N->getSimpleValueType(0);
4692
4693   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4694          "Unsupported vector type for PSHUFHW");
4695
4696   unsigned NumElts = VT.getVectorNumElements();
4697
4698   unsigned Mask = 0;
4699   for (unsigned l = 0; l != NumElts; l += 8) {
4700     // 8 nodes per lane, but we only care about the first 4.
4701     for (unsigned i = 0; i < 4; ++i) {
4702       int Elt = N->getMaskElt(l+i);
4703       if (Elt < 0) continue;
4704       Elt &= 0x3; // only 2-bits
4705       Mask |= Elt << (i * 2);
4706     }
4707   }
4708
4709   return Mask;
4710 }
4711
4712 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4713 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4714 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4715   MVT VT = SVOp->getSimpleValueType(0);
4716   unsigned EltSize = VT.is512BitVector() ? 1 :
4717     VT.getVectorElementType().getSizeInBits() >> 3;
4718
4719   unsigned NumElts = VT.getVectorNumElements();
4720   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4721   unsigned NumLaneElts = NumElts/NumLanes;
4722
4723   int Val = 0;
4724   unsigned i;
4725   for (i = 0; i != NumElts; ++i) {
4726     Val = SVOp->getMaskElt(i);
4727     if (Val >= 0)
4728       break;
4729   }
4730   if (Val >= (int)NumElts)
4731     Val -= NumElts - NumLaneElts;
4732
4733   assert(Val - i > 0 && "PALIGNR imm should be positive");
4734   return (Val - i) * EltSize;
4735 }
4736
4737 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4738   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4739   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4740     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4741
4742   uint64_t Index =
4743     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4744
4745   MVT VecVT = N->getOperand(0).getSimpleValueType();
4746   MVT ElVT = VecVT.getVectorElementType();
4747
4748   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4749   return Index / NumElemsPerChunk;
4750 }
4751
4752 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4753   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4754   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4755     llvm_unreachable("Illegal insert subvector for VINSERT");
4756
4757   uint64_t Index =
4758     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4759
4760   MVT VecVT = N->getSimpleValueType(0);
4761   MVT ElVT = VecVT.getVectorElementType();
4762
4763   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4764   return Index / NumElemsPerChunk;
4765 }
4766
4767 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4768 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4769 /// and VINSERTI128 instructions.
4770 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4771   return getExtractVEXTRACTImmediate(N, 128);
4772 }
4773
4774 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4775 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4776 /// and VINSERTI64x4 instructions.
4777 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4778   return getExtractVEXTRACTImmediate(N, 256);
4779 }
4780
4781 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4782 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4783 /// and VINSERTI128 instructions.
4784 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4785   return getInsertVINSERTImmediate(N, 128);
4786 }
4787
4788 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4789 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4790 /// and VINSERTI64x4 instructions.
4791 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4792   return getInsertVINSERTImmediate(N, 256);
4793 }
4794
4795 /// isZero - Returns true if Elt is a constant integer zero
4796 static bool isZero(SDValue V) {
4797   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4798   return C && C->isNullValue();
4799 }
4800
4801 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4802 /// constant +0.0.
4803 bool X86::isZeroNode(SDValue Elt) {
4804   if (isZero(Elt))
4805     return true;
4806   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4807     return CFP->getValueAPF().isPosZero();
4808   return false;
4809 }
4810
4811 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4812 /// match movhlps. The lower half elements should come from upper half of
4813 /// V1 (and in order), and the upper half elements should come from the upper
4814 /// half of V2 (and in order).
4815 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4816   if (!VT.is128BitVector())
4817     return false;
4818   if (VT.getVectorNumElements() != 4)
4819     return false;
4820   for (unsigned i = 0, e = 2; i != e; ++i)
4821     if (!isUndefOrEqual(Mask[i], i+2))
4822       return false;
4823   for (unsigned i = 2; i != 4; ++i)
4824     if (!isUndefOrEqual(Mask[i], i+4))
4825       return false;
4826   return true;
4827 }
4828
4829 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4830 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4831 /// required.
4832 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4833   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4834     return false;
4835   N = N->getOperand(0).getNode();
4836   if (!ISD::isNON_EXTLoad(N))
4837     return false;
4838   if (LD)
4839     *LD = cast<LoadSDNode>(N);
4840   return true;
4841 }
4842
4843 // Test whether the given value is a vector value which will be legalized
4844 // into a load.
4845 static bool WillBeConstantPoolLoad(SDNode *N) {
4846   if (N->getOpcode() != ISD::BUILD_VECTOR)
4847     return false;
4848
4849   // Check for any non-constant elements.
4850   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4851     switch (N->getOperand(i).getNode()->getOpcode()) {
4852     case ISD::UNDEF:
4853     case ISD::ConstantFP:
4854     case ISD::Constant:
4855       break;
4856     default:
4857       return false;
4858     }
4859
4860   // Vectors of all-zeros and all-ones are materialized with special
4861   // instructions rather than being loaded.
4862   return !ISD::isBuildVectorAllZeros(N) &&
4863          !ISD::isBuildVectorAllOnes(N);
4864 }
4865
4866 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4867 /// match movlp{s|d}. The lower half elements should come from lower half of
4868 /// V1 (and in order), and the upper half elements should come from the upper
4869 /// half of V2 (and in order). And since V1 will become the source of the
4870 /// MOVLP, it must be either a vector load or a scalar load to vector.
4871 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4872                                ArrayRef<int> Mask, MVT VT) {
4873   if (!VT.is128BitVector())
4874     return false;
4875
4876   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4877     return false;
4878   // Is V2 is a vector load, don't do this transformation. We will try to use
4879   // load folding shufps op.
4880   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4881     return false;
4882
4883   unsigned NumElems = VT.getVectorNumElements();
4884
4885   if (NumElems != 2 && NumElems != 4)
4886     return false;
4887   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4888     if (!isUndefOrEqual(Mask[i], i))
4889       return false;
4890   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4891     if (!isUndefOrEqual(Mask[i], i+NumElems))
4892       return false;
4893   return true;
4894 }
4895
4896 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4897 /// to an zero vector.
4898 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4899 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4900   SDValue V1 = N->getOperand(0);
4901   SDValue V2 = N->getOperand(1);
4902   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4903   for (unsigned i = 0; i != NumElems; ++i) {
4904     int Idx = N->getMaskElt(i);
4905     if (Idx >= (int)NumElems) {
4906       unsigned Opc = V2.getOpcode();
4907       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4908         continue;
4909       if (Opc != ISD::BUILD_VECTOR ||
4910           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4911         return false;
4912     } else if (Idx >= 0) {
4913       unsigned Opc = V1.getOpcode();
4914       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4915         continue;
4916       if (Opc != ISD::BUILD_VECTOR ||
4917           !X86::isZeroNode(V1.getOperand(Idx)))
4918         return false;
4919     }
4920   }
4921   return true;
4922 }
4923
4924 /// getZeroVector - Returns a vector of specified type with all zero elements.
4925 ///
4926 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4927                              SelectionDAG &DAG, SDLoc dl) {
4928   assert(VT.isVector() && "Expected a vector type");
4929
4930   // Always build SSE zero vectors as <4 x i32> bitcasted
4931   // to their dest type. This ensures they get CSE'd.
4932   SDValue Vec;
4933   if (VT.is128BitVector()) {  // SSE
4934     if (Subtarget->hasSSE2()) {  // SSE2
4935       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4936       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4937     } else { // SSE1
4938       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4939       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4940     }
4941   } else if (VT.is256BitVector()) { // AVX
4942     if (Subtarget->hasInt256()) { // AVX2
4943       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4944       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4945       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4946     } else {
4947       // 256-bit logic and arithmetic instructions in AVX are all
4948       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4949       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4950       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4951       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4952     }
4953   } else if (VT.is512BitVector()) { // AVX-512
4954       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4955       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4956                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4957       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4958   } else if (VT.getScalarType() == MVT::i1) {
4959     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4960     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4961     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4962     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4963   } else
4964     llvm_unreachable("Unexpected vector type");
4965
4966   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4967 }
4968
4969 /// getOnesVector - Returns a vector of specified type with all bits set.
4970 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4971 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4972 /// Then bitcast to their original type, ensuring they get CSE'd.
4973 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4974                              SDLoc dl) {
4975   assert(VT.isVector() && "Expected a vector type");
4976
4977   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4978   SDValue Vec;
4979   if (VT.is256BitVector()) {
4980     if (HasInt256) { // AVX2
4981       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4982       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4983     } else { // AVX
4984       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4985       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4986     }
4987   } else if (VT.is128BitVector()) {
4988     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4989   } else
4990     llvm_unreachable("Unexpected vector type");
4991
4992   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4993 }
4994
4995 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4996 /// that point to V2 points to its first element.
4997 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4998   for (unsigned i = 0; i != NumElems; ++i) {
4999     if (Mask[i] > (int)NumElems) {
5000       Mask[i] = NumElems;
5001     }
5002   }
5003 }
5004
5005 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5006 /// operation of specified width.
5007 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5008                        SDValue V2) {
5009   unsigned NumElems = VT.getVectorNumElements();
5010   SmallVector<int, 8> Mask;
5011   Mask.push_back(NumElems);
5012   for (unsigned i = 1; i != NumElems; ++i)
5013     Mask.push_back(i);
5014   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5015 }
5016
5017 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5018 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5019                           SDValue V2) {
5020   unsigned NumElems = VT.getVectorNumElements();
5021   SmallVector<int, 8> Mask;
5022   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5023     Mask.push_back(i);
5024     Mask.push_back(i + NumElems);
5025   }
5026   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5027 }
5028
5029 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5030 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5031                           SDValue V2) {
5032   unsigned NumElems = VT.getVectorNumElements();
5033   SmallVector<int, 8> Mask;
5034   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5035     Mask.push_back(i + Half);
5036     Mask.push_back(i + NumElems + Half);
5037   }
5038   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5039 }
5040
5041 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5042 // a generic shuffle instruction because the target has no such instructions.
5043 // Generate shuffles which repeat i16 and i8 several times until they can be
5044 // represented by v4f32 and then be manipulated by target suported shuffles.
5045 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5046   MVT VT = V.getSimpleValueType();
5047   int NumElems = VT.getVectorNumElements();
5048   SDLoc dl(V);
5049
5050   while (NumElems > 4) {
5051     if (EltNo < NumElems/2) {
5052       V = getUnpackl(DAG, dl, VT, V, V);
5053     } else {
5054       V = getUnpackh(DAG, dl, VT, V, V);
5055       EltNo -= NumElems/2;
5056     }
5057     NumElems >>= 1;
5058   }
5059   return V;
5060 }
5061
5062 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5063 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5064   MVT VT = V.getSimpleValueType();
5065   SDLoc dl(V);
5066
5067   if (VT.is128BitVector()) {
5068     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5069     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5070     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5071                              &SplatMask[0]);
5072   } else if (VT.is256BitVector()) {
5073     // To use VPERMILPS to splat scalars, the second half of indicies must
5074     // refer to the higher part, which is a duplication of the lower one,
5075     // because VPERMILPS can only handle in-lane permutations.
5076     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5077                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5078
5079     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5080     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5081                              &SplatMask[0]);
5082   } else
5083     llvm_unreachable("Vector size not supported");
5084
5085   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5086 }
5087
5088 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5089 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5090   MVT SrcVT = SV->getSimpleValueType(0);
5091   SDValue V1 = SV->getOperand(0);
5092   SDLoc dl(SV);
5093
5094   int EltNo = SV->getSplatIndex();
5095   int NumElems = SrcVT.getVectorNumElements();
5096   bool Is256BitVec = SrcVT.is256BitVector();
5097
5098   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5099          "Unknown how to promote splat for type");
5100
5101   // Extract the 128-bit part containing the splat element and update
5102   // the splat element index when it refers to the higher register.
5103   if (Is256BitVec) {
5104     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5105     if (EltNo >= NumElems/2)
5106       EltNo -= NumElems/2;
5107   }
5108
5109   // All i16 and i8 vector types can't be used directly by a generic shuffle
5110   // instruction because the target has no such instruction. Generate shuffles
5111   // which repeat i16 and i8 several times until they fit in i32, and then can
5112   // be manipulated by target suported shuffles.
5113   MVT EltVT = SrcVT.getVectorElementType();
5114   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5115     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5116
5117   // Recreate the 256-bit vector and place the same 128-bit vector
5118   // into the low and high part. This is necessary because we want
5119   // to use VPERM* to shuffle the vectors
5120   if (Is256BitVec) {
5121     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5122   }
5123
5124   return getLegalSplat(DAG, V1, EltNo);
5125 }
5126
5127 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5128 /// vector of zero or undef vector.  This produces a shuffle where the low
5129 /// element of V2 is swizzled into the zero/undef vector, landing at element
5130 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5131 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5132                                            bool IsZero,
5133                                            const X86Subtarget *Subtarget,
5134                                            SelectionDAG &DAG) {
5135   MVT VT = V2.getSimpleValueType();
5136   SDValue V1 = IsZero
5137     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5138   unsigned NumElems = VT.getVectorNumElements();
5139   SmallVector<int, 16> MaskVec;
5140   for (unsigned i = 0; i != NumElems; ++i)
5141     // If this is the insertion idx, put the low elt of V2 here.
5142     MaskVec.push_back(i == Idx ? NumElems : i);
5143   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5144 }
5145
5146 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5147 /// target specific opcode. Returns true if the Mask could be calculated.
5148 /// Sets IsUnary to true if only uses one source.
5149 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5150                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5151   unsigned NumElems = VT.getVectorNumElements();
5152   SDValue ImmN;
5153
5154   IsUnary = false;
5155   switch(N->getOpcode()) {
5156   case X86ISD::SHUFP:
5157     ImmN = N->getOperand(N->getNumOperands()-1);
5158     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5159     break;
5160   case X86ISD::UNPCKH:
5161     DecodeUNPCKHMask(VT, Mask);
5162     break;
5163   case X86ISD::UNPCKL:
5164     DecodeUNPCKLMask(VT, Mask);
5165     break;
5166   case X86ISD::MOVHLPS:
5167     DecodeMOVHLPSMask(NumElems, Mask);
5168     break;
5169   case X86ISD::MOVLHPS:
5170     DecodeMOVLHPSMask(NumElems, Mask);
5171     break;
5172   case X86ISD::PALIGNR:
5173     ImmN = N->getOperand(N->getNumOperands()-1);
5174     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5175     break;
5176   case X86ISD::PSHUFD:
5177   case X86ISD::VPERMILP:
5178     ImmN = N->getOperand(N->getNumOperands()-1);
5179     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5180     IsUnary = true;
5181     break;
5182   case X86ISD::PSHUFHW:
5183     ImmN = N->getOperand(N->getNumOperands()-1);
5184     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5185     IsUnary = true;
5186     break;
5187   case X86ISD::PSHUFLW:
5188     ImmN = N->getOperand(N->getNumOperands()-1);
5189     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5190     IsUnary = true;
5191     break;
5192   case X86ISD::VPERMI:
5193     ImmN = N->getOperand(N->getNumOperands()-1);
5194     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5195     IsUnary = true;
5196     break;
5197   case X86ISD::MOVSS:
5198   case X86ISD::MOVSD: {
5199     // The index 0 always comes from the first element of the second source,
5200     // this is why MOVSS and MOVSD are used in the first place. The other
5201     // elements come from the other positions of the first source vector
5202     Mask.push_back(NumElems);
5203     for (unsigned i = 1; i != NumElems; ++i) {
5204       Mask.push_back(i);
5205     }
5206     break;
5207   }
5208   case X86ISD::VPERM2X128:
5209     ImmN = N->getOperand(N->getNumOperands()-1);
5210     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5211     if (Mask.empty()) return false;
5212     break;
5213   case X86ISD::MOVDDUP:
5214   case X86ISD::MOVLHPD:
5215   case X86ISD::MOVLPD:
5216   case X86ISD::MOVLPS:
5217   case X86ISD::MOVSHDUP:
5218   case X86ISD::MOVSLDUP:
5219     // Not yet implemented
5220     return false;
5221   default: llvm_unreachable("unknown target shuffle node");
5222   }
5223
5224   return true;
5225 }
5226
5227 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5228 /// element of the result of the vector shuffle.
5229 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5230                                    unsigned Depth) {
5231   if (Depth == 6)
5232     return SDValue();  // Limit search depth.
5233
5234   SDValue V = SDValue(N, 0);
5235   EVT VT = V.getValueType();
5236   unsigned Opcode = V.getOpcode();
5237
5238   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5239   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5240     int Elt = SV->getMaskElt(Index);
5241
5242     if (Elt < 0)
5243       return DAG.getUNDEF(VT.getVectorElementType());
5244
5245     unsigned NumElems = VT.getVectorNumElements();
5246     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5247                                          : SV->getOperand(1);
5248     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5249   }
5250
5251   // Recurse into target specific vector shuffles to find scalars.
5252   if (isTargetShuffle(Opcode)) {
5253     MVT ShufVT = V.getSimpleValueType();
5254     unsigned NumElems = ShufVT.getVectorNumElements();
5255     SmallVector<int, 16> ShuffleMask;
5256     bool IsUnary;
5257
5258     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5259       return SDValue();
5260
5261     int Elt = ShuffleMask[Index];
5262     if (Elt < 0)
5263       return DAG.getUNDEF(ShufVT.getVectorElementType());
5264
5265     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5266                                          : N->getOperand(1);
5267     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5268                                Depth+1);
5269   }
5270
5271   // Actual nodes that may contain scalar elements
5272   if (Opcode == ISD::BITCAST) {
5273     V = V.getOperand(0);
5274     EVT SrcVT = V.getValueType();
5275     unsigned NumElems = VT.getVectorNumElements();
5276
5277     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5278       return SDValue();
5279   }
5280
5281   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5282     return (Index == 0) ? V.getOperand(0)
5283                         : DAG.getUNDEF(VT.getVectorElementType());
5284
5285   if (V.getOpcode() == ISD::BUILD_VECTOR)
5286     return V.getOperand(Index);
5287
5288   return SDValue();
5289 }
5290
5291 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5292 /// shuffle operation which come from a consecutively from a zero. The
5293 /// search can start in two different directions, from left or right.
5294 /// We count undefs as zeros until PreferredNum is reached.
5295 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5296                                          unsigned NumElems, bool ZerosFromLeft,
5297                                          SelectionDAG &DAG,
5298                                          unsigned PreferredNum = -1U) {
5299   unsigned NumZeros = 0;
5300   for (unsigned i = 0; i != NumElems; ++i) {
5301     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5302     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5303     if (!Elt.getNode())
5304       break;
5305
5306     if (X86::isZeroNode(Elt))
5307       ++NumZeros;
5308     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5309       NumZeros = std::min(NumZeros + 1, PreferredNum);
5310     else
5311       break;
5312   }
5313
5314   return NumZeros;
5315 }
5316
5317 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5318 /// correspond consecutively to elements from one of the vector operands,
5319 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5320 static
5321 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5322                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5323                               unsigned NumElems, unsigned &OpNum) {
5324   bool SeenV1 = false;
5325   bool SeenV2 = false;
5326
5327   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5328     int Idx = SVOp->getMaskElt(i);
5329     // Ignore undef indicies
5330     if (Idx < 0)
5331       continue;
5332
5333     if (Idx < (int)NumElems)
5334       SeenV1 = true;
5335     else
5336       SeenV2 = true;
5337
5338     // Only accept consecutive elements from the same vector
5339     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5340       return false;
5341   }
5342
5343   OpNum = SeenV1 ? 0 : 1;
5344   return true;
5345 }
5346
5347 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5348 /// logical left shift of a vector.
5349 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5350                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5351   unsigned NumElems =
5352     SVOp->getSimpleValueType(0).getVectorNumElements();
5353   unsigned NumZeros = getNumOfConsecutiveZeros(
5354       SVOp, NumElems, false /* check zeros from right */, DAG,
5355       SVOp->getMaskElt(0));
5356   unsigned OpSrc;
5357
5358   if (!NumZeros)
5359     return false;
5360
5361   // Considering the elements in the mask that are not consecutive zeros,
5362   // check if they consecutively come from only one of the source vectors.
5363   //
5364   //               V1 = {X, A, B, C}     0
5365   //                         \  \  \    /
5366   //   vector_shuffle V1, V2 <1, 2, 3, X>
5367   //
5368   if (!isShuffleMaskConsecutive(SVOp,
5369             0,                   // Mask Start Index
5370             NumElems-NumZeros,   // Mask End Index(exclusive)
5371             NumZeros,            // Where to start looking in the src vector
5372             NumElems,            // Number of elements in vector
5373             OpSrc))              // Which source operand ?
5374     return false;
5375
5376   isLeft = false;
5377   ShAmt = NumZeros;
5378   ShVal = SVOp->getOperand(OpSrc);
5379   return true;
5380 }
5381
5382 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5383 /// logical left shift of a vector.
5384 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5385                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5386   unsigned NumElems =
5387     SVOp->getSimpleValueType(0).getVectorNumElements();
5388   unsigned NumZeros = getNumOfConsecutiveZeros(
5389       SVOp, NumElems, true /* check zeros from left */, DAG,
5390       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5391   unsigned OpSrc;
5392
5393   if (!NumZeros)
5394     return false;
5395
5396   // Considering the elements in the mask that are not consecutive zeros,
5397   // check if they consecutively come from only one of the source vectors.
5398   //
5399   //                           0    { A, B, X, X } = V2
5400   //                          / \    /  /
5401   //   vector_shuffle V1, V2 <X, X, 4, 5>
5402   //
5403   if (!isShuffleMaskConsecutive(SVOp,
5404             NumZeros,     // Mask Start Index
5405             NumElems,     // Mask End Index(exclusive)
5406             0,            // Where to start looking in the src vector
5407             NumElems,     // Number of elements in vector
5408             OpSrc))       // Which source operand ?
5409     return false;
5410
5411   isLeft = true;
5412   ShAmt = NumZeros;
5413   ShVal = SVOp->getOperand(OpSrc);
5414   return true;
5415 }
5416
5417 /// isVectorShift - Returns true if the shuffle can be implemented as a
5418 /// logical left or right shift of a vector.
5419 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5420                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5421   // Although the logic below support any bitwidth size, there are no
5422   // shift instructions which handle more than 128-bit vectors.
5423   if (!SVOp->getSimpleValueType(0).is128BitVector())
5424     return false;
5425
5426   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5427       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5428     return true;
5429
5430   return false;
5431 }
5432
5433 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5434 ///
5435 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5436                                        unsigned NumNonZero, unsigned NumZero,
5437                                        SelectionDAG &DAG,
5438                                        const X86Subtarget* Subtarget,
5439                                        const TargetLowering &TLI) {
5440   if (NumNonZero > 8)
5441     return SDValue();
5442
5443   SDLoc dl(Op);
5444   SDValue V;
5445   bool First = true;
5446   for (unsigned i = 0; i < 16; ++i) {
5447     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5448     if (ThisIsNonZero && First) {
5449       if (NumZero)
5450         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5451       else
5452         V = DAG.getUNDEF(MVT::v8i16);
5453       First = false;
5454     }
5455
5456     if ((i & 1) != 0) {
5457       SDValue ThisElt, LastElt;
5458       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5459       if (LastIsNonZero) {
5460         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5461                               MVT::i16, Op.getOperand(i-1));
5462       }
5463       if (ThisIsNonZero) {
5464         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5465         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5466                               ThisElt, DAG.getConstant(8, MVT::i8));
5467         if (LastIsNonZero)
5468           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5469       } else
5470         ThisElt = LastElt;
5471
5472       if (ThisElt.getNode())
5473         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5474                         DAG.getIntPtrConstant(i/2));
5475     }
5476   }
5477
5478   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5479 }
5480
5481 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5482 ///
5483 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5484                                      unsigned NumNonZero, unsigned NumZero,
5485                                      SelectionDAG &DAG,
5486                                      const X86Subtarget* Subtarget,
5487                                      const TargetLowering &TLI) {
5488   if (NumNonZero > 4)
5489     return SDValue();
5490
5491   SDLoc dl(Op);
5492   SDValue V;
5493   bool First = true;
5494   for (unsigned i = 0; i < 8; ++i) {
5495     bool isNonZero = (NonZeros & (1 << i)) != 0;
5496     if (isNonZero) {
5497       if (First) {
5498         if (NumZero)
5499           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5500         else
5501           V = DAG.getUNDEF(MVT::v8i16);
5502         First = false;
5503       }
5504       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5505                       MVT::v8i16, V, Op.getOperand(i),
5506                       DAG.getIntPtrConstant(i));
5507     }
5508   }
5509
5510   return V;
5511 }
5512
5513 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5514 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5515                                      unsigned NonZeros, unsigned NumNonZero,
5516                                      unsigned NumZero, SelectionDAG &DAG,
5517                                      const X86Subtarget *Subtarget,
5518                                      const TargetLowering &TLI) {
5519   // We know there's at least one non-zero element
5520   unsigned FirstNonZeroIdx = 0;
5521   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5522   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5523          X86::isZeroNode(FirstNonZero)) {
5524     ++FirstNonZeroIdx;
5525     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5526   }
5527
5528   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5529       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5530     return SDValue();
5531
5532   SDValue V = FirstNonZero.getOperand(0);
5533   MVT VVT = V.getSimpleValueType();
5534   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5535     return SDValue();
5536
5537   unsigned FirstNonZeroDst =
5538       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5539   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5540   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5541   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5542
5543   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5544     SDValue Elem = Op.getOperand(Idx);
5545     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5546       continue;
5547
5548     // TODO: What else can be here? Deal with it.
5549     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5550       return SDValue();
5551
5552     // TODO: Some optimizations are still possible here
5553     // ex: Getting one element from a vector, and the rest from another.
5554     if (Elem.getOperand(0) != V)
5555       return SDValue();
5556
5557     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5558     if (Dst == Idx)
5559       ++CorrectIdx;
5560     else if (IncorrectIdx == -1U) {
5561       IncorrectIdx = Idx;
5562       IncorrectDst = Dst;
5563     } else
5564       // There was already one element with an incorrect index.
5565       // We can't optimize this case to an insertps.
5566       return SDValue();
5567   }
5568
5569   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5570     SDLoc dl(Op);
5571     EVT VT = Op.getSimpleValueType();
5572     unsigned ElementMoveMask = 0;
5573     if (IncorrectIdx == -1U)
5574       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5575     else
5576       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5577
5578     SDValue InsertpsMask =
5579         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5580     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5581   }
5582
5583   return SDValue();
5584 }
5585
5586 /// getVShift - Return a vector logical shift node.
5587 ///
5588 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5589                          unsigned NumBits, SelectionDAG &DAG,
5590                          const TargetLowering &TLI, SDLoc dl) {
5591   assert(VT.is128BitVector() && "Unknown type for VShift");
5592   EVT ShVT = MVT::v2i64;
5593   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5594   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5595   return DAG.getNode(ISD::BITCAST, dl, VT,
5596                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5597                              DAG.getConstant(NumBits,
5598                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5599 }
5600
5601 static SDValue
5602 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5603
5604   // Check if the scalar load can be widened into a vector load. And if
5605   // the address is "base + cst" see if the cst can be "absorbed" into
5606   // the shuffle mask.
5607   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5608     SDValue Ptr = LD->getBasePtr();
5609     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5610       return SDValue();
5611     EVT PVT = LD->getValueType(0);
5612     if (PVT != MVT::i32 && PVT != MVT::f32)
5613       return SDValue();
5614
5615     int FI = -1;
5616     int64_t Offset = 0;
5617     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5618       FI = FINode->getIndex();
5619       Offset = 0;
5620     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5621                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5622       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5623       Offset = Ptr.getConstantOperandVal(1);
5624       Ptr = Ptr.getOperand(0);
5625     } else {
5626       return SDValue();
5627     }
5628
5629     // FIXME: 256-bit vector instructions don't require a strict alignment,
5630     // improve this code to support it better.
5631     unsigned RequiredAlign = VT.getSizeInBits()/8;
5632     SDValue Chain = LD->getChain();
5633     // Make sure the stack object alignment is at least 16 or 32.
5634     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5635     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5636       if (MFI->isFixedObjectIndex(FI)) {
5637         // Can't change the alignment. FIXME: It's possible to compute
5638         // the exact stack offset and reference FI + adjust offset instead.
5639         // If someone *really* cares about this. That's the way to implement it.
5640         return SDValue();
5641       } else {
5642         MFI->setObjectAlignment(FI, RequiredAlign);
5643       }
5644     }
5645
5646     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5647     // Ptr + (Offset & ~15).
5648     if (Offset < 0)
5649       return SDValue();
5650     if ((Offset % RequiredAlign) & 3)
5651       return SDValue();
5652     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5653     if (StartOffset)
5654       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5655                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5656
5657     int EltNo = (Offset - StartOffset) >> 2;
5658     unsigned NumElems = VT.getVectorNumElements();
5659
5660     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5661     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5662                              LD->getPointerInfo().getWithOffset(StartOffset),
5663                              false, false, false, 0);
5664
5665     SmallVector<int, 8> Mask;
5666     for (unsigned i = 0; i != NumElems; ++i)
5667       Mask.push_back(EltNo);
5668
5669     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5670   }
5671
5672   return SDValue();
5673 }
5674
5675 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5676 /// vector of type 'VT', see if the elements can be replaced by a single large
5677 /// load which has the same value as a build_vector whose operands are 'elts'.
5678 ///
5679 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5680 ///
5681 /// FIXME: we'd also like to handle the case where the last elements are zero
5682 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5683 /// There's even a handy isZeroNode for that purpose.
5684 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5685                                         SDLoc &DL, SelectionDAG &DAG,
5686                                         bool isAfterLegalize) {
5687   EVT EltVT = VT.getVectorElementType();
5688   unsigned NumElems = Elts.size();
5689
5690   LoadSDNode *LDBase = nullptr;
5691   unsigned LastLoadedElt = -1U;
5692
5693   // For each element in the initializer, see if we've found a load or an undef.
5694   // If we don't find an initial load element, or later load elements are
5695   // non-consecutive, bail out.
5696   for (unsigned i = 0; i < NumElems; ++i) {
5697     SDValue Elt = Elts[i];
5698
5699     if (!Elt.getNode() ||
5700         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5701       return SDValue();
5702     if (!LDBase) {
5703       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5704         return SDValue();
5705       LDBase = cast<LoadSDNode>(Elt.getNode());
5706       LastLoadedElt = i;
5707       continue;
5708     }
5709     if (Elt.getOpcode() == ISD::UNDEF)
5710       continue;
5711
5712     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5713     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5714       return SDValue();
5715     LastLoadedElt = i;
5716   }
5717
5718   // If we have found an entire vector of loads and undefs, then return a large
5719   // load of the entire vector width starting at the base pointer.  If we found
5720   // consecutive loads for the low half, generate a vzext_load node.
5721   if (LastLoadedElt == NumElems - 1) {
5722
5723     if (isAfterLegalize &&
5724         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5725       return SDValue();
5726
5727     SDValue NewLd = SDValue();
5728
5729     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5730       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5731                           LDBase->getPointerInfo(),
5732                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5733                           LDBase->isInvariant(), 0);
5734     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5735                         LDBase->getPointerInfo(),
5736                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5737                         LDBase->isInvariant(), LDBase->getAlignment());
5738
5739     if (LDBase->hasAnyUseOfValue(1)) {
5740       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5741                                      SDValue(LDBase, 1),
5742                                      SDValue(NewLd.getNode(), 1));
5743       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5744       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5745                              SDValue(NewLd.getNode(), 1));
5746     }
5747
5748     return NewLd;
5749   }
5750   if (NumElems == 4 && LastLoadedElt == 1 &&
5751       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5752     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5753     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5754     SDValue ResNode =
5755         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5756                                 LDBase->getPointerInfo(),
5757                                 LDBase->getAlignment(),
5758                                 false/*isVolatile*/, true/*ReadMem*/,
5759                                 false/*WriteMem*/);
5760
5761     // Make sure the newly-created LOAD is in the same position as LDBase in
5762     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5763     // update uses of LDBase's output chain to use the TokenFactor.
5764     if (LDBase->hasAnyUseOfValue(1)) {
5765       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5766                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5767       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5768       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5769                              SDValue(ResNode.getNode(), 1));
5770     }
5771
5772     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5773   }
5774   return SDValue();
5775 }
5776
5777 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5778 /// to generate a splat value for the following cases:
5779 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5780 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5781 /// a scalar load, or a constant.
5782 /// The VBROADCAST node is returned when a pattern is found,
5783 /// or SDValue() otherwise.
5784 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5785                                     SelectionDAG &DAG) {
5786   if (!Subtarget->hasFp256())
5787     return SDValue();
5788
5789   MVT VT = Op.getSimpleValueType();
5790   SDLoc dl(Op);
5791
5792   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5793          "Unsupported vector type for broadcast.");
5794
5795   SDValue Ld;
5796   bool ConstSplatVal;
5797
5798   switch (Op.getOpcode()) {
5799     default:
5800       // Unknown pattern found.
5801       return SDValue();
5802
5803     case ISD::BUILD_VECTOR: {
5804       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5805       BitVector UndefElements;
5806       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5807
5808       // We need a splat of a single value to use broadcast, and it doesn't
5809       // make any sense if the value is only in one element of the vector.
5810       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5811         return SDValue();
5812
5813       Ld = Splat;
5814       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5815                        Ld.getOpcode() == ISD::ConstantFP);
5816
5817       // Make sure that all of the users of a non-constant load are from the
5818       // BUILD_VECTOR node.
5819       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5820         return SDValue();
5821       break;
5822     }
5823
5824     case ISD::VECTOR_SHUFFLE: {
5825       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5826
5827       // Shuffles must have a splat mask where the first element is
5828       // broadcasted.
5829       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5830         return SDValue();
5831
5832       SDValue Sc = Op.getOperand(0);
5833       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5834           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5835
5836         if (!Subtarget->hasInt256())
5837           return SDValue();
5838
5839         // Use the register form of the broadcast instruction available on AVX2.
5840         if (VT.getSizeInBits() >= 256)
5841           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5842         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5843       }
5844
5845       Ld = Sc.getOperand(0);
5846       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5847                        Ld.getOpcode() == ISD::ConstantFP);
5848
5849       // The scalar_to_vector node and the suspected
5850       // load node must have exactly one user.
5851       // Constants may have multiple users.
5852
5853       // AVX-512 has register version of the broadcast
5854       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5855         Ld.getValueType().getSizeInBits() >= 32;
5856       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5857           !hasRegVer))
5858         return SDValue();
5859       break;
5860     }
5861   }
5862
5863   bool IsGE256 = (VT.getSizeInBits() >= 256);
5864
5865   // Handle the broadcasting a single constant scalar from the constant pool
5866   // into a vector. On Sandybridge it is still better to load a constant vector
5867   // from the constant pool and not to broadcast it from a scalar.
5868   if (ConstSplatVal && Subtarget->hasInt256()) {
5869     EVT CVT = Ld.getValueType();
5870     assert(!CVT.isVector() && "Must not broadcast a vector type");
5871     unsigned ScalarSize = CVT.getSizeInBits();
5872
5873     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5874       const Constant *C = nullptr;
5875       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5876         C = CI->getConstantIntValue();
5877       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5878         C = CF->getConstantFPValue();
5879
5880       assert(C && "Invalid constant type");
5881
5882       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5883       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5884       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5885       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5886                        MachinePointerInfo::getConstantPool(),
5887                        false, false, false, Alignment);
5888
5889       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5890     }
5891   }
5892
5893   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5894   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5895
5896   // Handle AVX2 in-register broadcasts.
5897   if (!IsLoad && Subtarget->hasInt256() &&
5898       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5899     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5900
5901   // The scalar source must be a normal load.
5902   if (!IsLoad)
5903     return SDValue();
5904
5905   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5906     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5907
5908   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5909   // double since there is no vbroadcastsd xmm
5910   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5911     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5912       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5913   }
5914
5915   // Unsupported broadcast.
5916   return SDValue();
5917 }
5918
5919 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5920 /// underlying vector and index.
5921 ///
5922 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5923 /// index.
5924 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5925                                          SDValue ExtIdx) {
5926   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5927   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5928     return Idx;
5929
5930   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5931   // lowered this:
5932   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5933   // to:
5934   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5935   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5936   //                           undef)
5937   //                       Constant<0>)
5938   // In this case the vector is the extract_subvector expression and the index
5939   // is 2, as specified by the shuffle.
5940   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5941   SDValue ShuffleVec = SVOp->getOperand(0);
5942   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5943   assert(ShuffleVecVT.getVectorElementType() ==
5944          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5945
5946   int ShuffleIdx = SVOp->getMaskElt(Idx);
5947   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5948     ExtractedFromVec = ShuffleVec;
5949     return ShuffleIdx;
5950   }
5951   return Idx;
5952 }
5953
5954 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5955   MVT VT = Op.getSimpleValueType();
5956
5957   // Skip if insert_vec_elt is not supported.
5958   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5959   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5960     return SDValue();
5961
5962   SDLoc DL(Op);
5963   unsigned NumElems = Op.getNumOperands();
5964
5965   SDValue VecIn1;
5966   SDValue VecIn2;
5967   SmallVector<unsigned, 4> InsertIndices;
5968   SmallVector<int, 8> Mask(NumElems, -1);
5969
5970   for (unsigned i = 0; i != NumElems; ++i) {
5971     unsigned Opc = Op.getOperand(i).getOpcode();
5972
5973     if (Opc == ISD::UNDEF)
5974       continue;
5975
5976     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5977       // Quit if more than 1 elements need inserting.
5978       if (InsertIndices.size() > 1)
5979         return SDValue();
5980
5981       InsertIndices.push_back(i);
5982       continue;
5983     }
5984
5985     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5986     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5987     // Quit if non-constant index.
5988     if (!isa<ConstantSDNode>(ExtIdx))
5989       return SDValue();
5990     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5991
5992     // Quit if extracted from vector of different type.
5993     if (ExtractedFromVec.getValueType() != VT)
5994       return SDValue();
5995
5996     if (!VecIn1.getNode())
5997       VecIn1 = ExtractedFromVec;
5998     else if (VecIn1 != ExtractedFromVec) {
5999       if (!VecIn2.getNode())
6000         VecIn2 = ExtractedFromVec;
6001       else if (VecIn2 != ExtractedFromVec)
6002         // Quit if more than 2 vectors to shuffle
6003         return SDValue();
6004     }
6005
6006     if (ExtractedFromVec == VecIn1)
6007       Mask[i] = Idx;
6008     else if (ExtractedFromVec == VecIn2)
6009       Mask[i] = Idx + NumElems;
6010   }
6011
6012   if (!VecIn1.getNode())
6013     return SDValue();
6014
6015   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6016   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6017   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6018     unsigned Idx = InsertIndices[i];
6019     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6020                      DAG.getIntPtrConstant(Idx));
6021   }
6022
6023   return NV;
6024 }
6025
6026 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6027 SDValue
6028 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6029
6030   MVT VT = Op.getSimpleValueType();
6031   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6032          "Unexpected type in LowerBUILD_VECTORvXi1!");
6033
6034   SDLoc dl(Op);
6035   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6036     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6037     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6038     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6039   }
6040
6041   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6042     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6043     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6044     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6045   }
6046
6047   bool AllContants = true;
6048   uint64_t Immediate = 0;
6049   int NonConstIdx = -1;
6050   bool IsSplat = true;
6051   unsigned NumNonConsts = 0;
6052   unsigned NumConsts = 0;
6053   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6054     SDValue In = Op.getOperand(idx);
6055     if (In.getOpcode() == ISD::UNDEF)
6056       continue;
6057     if (!isa<ConstantSDNode>(In)) {
6058       AllContants = false;
6059       NonConstIdx = idx;
6060       NumNonConsts++;
6061     }
6062     else {
6063       NumConsts++;
6064       if (cast<ConstantSDNode>(In)->getZExtValue())
6065       Immediate |= (1ULL << idx);
6066     }
6067     if (In != Op.getOperand(0))
6068       IsSplat = false;
6069   }
6070
6071   if (AllContants) {
6072     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6073       DAG.getConstant(Immediate, MVT::i16));
6074     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6075                        DAG.getIntPtrConstant(0));
6076   }
6077
6078   if (NumNonConsts == 1 && NonConstIdx != 0) {
6079     SDValue DstVec;
6080     if (NumConsts) {
6081       SDValue VecAsImm = DAG.getConstant(Immediate,
6082                                          MVT::getIntegerVT(VT.getSizeInBits()));
6083       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6084     }
6085     else 
6086       DstVec = DAG.getUNDEF(VT);
6087     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6088                        Op.getOperand(NonConstIdx),
6089                        DAG.getIntPtrConstant(NonConstIdx));
6090   }
6091   if (!IsSplat && (NonConstIdx != 0))
6092     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6093   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6094   SDValue Select;
6095   if (IsSplat)
6096     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6097                           DAG.getConstant(-1, SelectVT),
6098                           DAG.getConstant(0, SelectVT));
6099   else
6100     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6101                          DAG.getConstant((Immediate | 1), SelectVT),
6102                          DAG.getConstant(Immediate, SelectVT));
6103   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6104 }
6105
6106 /// \brief Return true if \p N implements a horizontal binop and return the
6107 /// operands for the horizontal binop into V0 and V1.
6108 /// 
6109 /// This is a helper function of PerformBUILD_VECTORCombine.
6110 /// This function checks that the build_vector \p N in input implements a
6111 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6112 /// operation to match.
6113 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6114 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6115 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6116 /// arithmetic sub.
6117 ///
6118 /// This function only analyzes elements of \p N whose indices are
6119 /// in range [BaseIdx, LastIdx).
6120 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6121                               SelectionDAG &DAG,
6122                               unsigned BaseIdx, unsigned LastIdx,
6123                               SDValue &V0, SDValue &V1) {
6124   EVT VT = N->getValueType(0);
6125
6126   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6127   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6128          "Invalid Vector in input!");
6129   
6130   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6131   bool CanFold = true;
6132   unsigned ExpectedVExtractIdx = BaseIdx;
6133   unsigned NumElts = LastIdx - BaseIdx;
6134   V0 = DAG.getUNDEF(VT);
6135   V1 = DAG.getUNDEF(VT);
6136
6137   // Check if N implements a horizontal binop.
6138   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6139     SDValue Op = N->getOperand(i + BaseIdx);
6140
6141     // Skip UNDEFs.
6142     if (Op->getOpcode() == ISD::UNDEF) {
6143       // Update the expected vector extract index.
6144       if (i * 2 == NumElts)
6145         ExpectedVExtractIdx = BaseIdx;
6146       ExpectedVExtractIdx += 2;
6147       continue;
6148     }
6149
6150     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6151
6152     if (!CanFold)
6153       break;
6154
6155     SDValue Op0 = Op.getOperand(0);
6156     SDValue Op1 = Op.getOperand(1);
6157
6158     // Try to match the following pattern:
6159     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6160     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6161         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6162         Op0.getOperand(0) == Op1.getOperand(0) &&
6163         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6164         isa<ConstantSDNode>(Op1.getOperand(1)));
6165     if (!CanFold)
6166       break;
6167
6168     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6169     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6170
6171     if (i * 2 < NumElts) {
6172       if (V0.getOpcode() == ISD::UNDEF)
6173         V0 = Op0.getOperand(0);
6174     } else {
6175       if (V1.getOpcode() == ISD::UNDEF)
6176         V1 = Op0.getOperand(0);
6177       if (i * 2 == NumElts)
6178         ExpectedVExtractIdx = BaseIdx;
6179     }
6180
6181     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6182     if (I0 == ExpectedVExtractIdx)
6183       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6184     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6185       // Try to match the following dag sequence:
6186       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6187       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6188     } else
6189       CanFold = false;
6190
6191     ExpectedVExtractIdx += 2;
6192   }
6193
6194   return CanFold;
6195 }
6196
6197 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6198 /// a concat_vector. 
6199 ///
6200 /// This is a helper function of PerformBUILD_VECTORCombine.
6201 /// This function expects two 256-bit vectors called V0 and V1.
6202 /// At first, each vector is split into two separate 128-bit vectors.
6203 /// Then, the resulting 128-bit vectors are used to implement two
6204 /// horizontal binary operations. 
6205 ///
6206 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6207 ///
6208 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6209 /// the two new horizontal binop.
6210 /// When Mode is set, the first horizontal binop dag node would take as input
6211 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6212 /// horizontal binop dag node would take as input the lower 128-bit of V1
6213 /// and the upper 128-bit of V1.
6214 ///   Example:
6215 ///     HADD V0_LO, V0_HI
6216 ///     HADD V1_LO, V1_HI
6217 ///
6218 /// Otherwise, the first horizontal binop dag node takes as input the lower
6219 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6220 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6221 ///   Example:
6222 ///     HADD V0_LO, V1_LO
6223 ///     HADD V0_HI, V1_HI
6224 ///
6225 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6226 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6227 /// the upper 128-bits of the result.
6228 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6229                                      SDLoc DL, SelectionDAG &DAG,
6230                                      unsigned X86Opcode, bool Mode,
6231                                      bool isUndefLO, bool isUndefHI) {
6232   EVT VT = V0.getValueType();
6233   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6234          "Invalid nodes in input!");
6235
6236   unsigned NumElts = VT.getVectorNumElements();
6237   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6238   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6239   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6240   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6241   EVT NewVT = V0_LO.getValueType();
6242
6243   SDValue LO = DAG.getUNDEF(NewVT);
6244   SDValue HI = DAG.getUNDEF(NewVT);
6245
6246   if (Mode) {
6247     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6248     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6249       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6250     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6251       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6252   } else {
6253     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6254     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6255                        V1_LO->getOpcode() != ISD::UNDEF))
6256       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6257
6258     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6259                        V1_HI->getOpcode() != ISD::UNDEF))
6260       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6261   }
6262
6263   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6264 }
6265
6266 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6267 /// sequence of 'vadd + vsub + blendi'.
6268 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6269                            const X86Subtarget *Subtarget) {
6270   SDLoc DL(BV);
6271   EVT VT = BV->getValueType(0);
6272   unsigned NumElts = VT.getVectorNumElements();
6273   SDValue InVec0 = DAG.getUNDEF(VT);
6274   SDValue InVec1 = DAG.getUNDEF(VT);
6275
6276   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6277           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6278
6279   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6280   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6281   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6282     return SDValue();
6283
6284   // Odd-numbered elements in the input build vector are obtained from
6285   // adding two integer/float elements.
6286   // Even-numbered elements in the input build vector are obtained from
6287   // subtracting two integer/float elements.
6288   unsigned ExpectedOpcode = ISD::FSUB;
6289   unsigned NextExpectedOpcode = ISD::FADD;
6290   bool AddFound = false;
6291   bool SubFound = false;
6292
6293   for (unsigned i = 0, e = NumElts; i != e; i++) {
6294     SDValue Op = BV->getOperand(i);
6295       
6296     // Skip 'undef' values.
6297     unsigned Opcode = Op.getOpcode();
6298     if (Opcode == ISD::UNDEF) {
6299       std::swap(ExpectedOpcode, NextExpectedOpcode);
6300       continue;
6301     }
6302       
6303     // Early exit if we found an unexpected opcode.
6304     if (Opcode != ExpectedOpcode)
6305       return SDValue();
6306
6307     SDValue Op0 = Op.getOperand(0);
6308     SDValue Op1 = Op.getOperand(1);
6309
6310     // Try to match the following pattern:
6311     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6312     // Early exit if we cannot match that sequence.
6313     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6314         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6315         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6316         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6317         Op0.getOperand(1) != Op1.getOperand(1))
6318       return SDValue();
6319
6320     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6321     if (I0 != i)
6322       return SDValue();
6323
6324     // We found a valid add/sub node. Update the information accordingly.
6325     if (i & 1)
6326       AddFound = true;
6327     else
6328       SubFound = true;
6329
6330     // Update InVec0 and InVec1.
6331     if (InVec0.getOpcode() == ISD::UNDEF)
6332       InVec0 = Op0.getOperand(0);
6333     if (InVec1.getOpcode() == ISD::UNDEF)
6334       InVec1 = Op1.getOperand(0);
6335
6336     // Make sure that operands in input to each add/sub node always
6337     // come from a same pair of vectors.
6338     if (InVec0 != Op0.getOperand(0)) {
6339       if (ExpectedOpcode == ISD::FSUB)
6340         return SDValue();
6341
6342       // FADD is commutable. Try to commute the operands
6343       // and then test again.
6344       std::swap(Op0, Op1);
6345       if (InVec0 != Op0.getOperand(0))
6346         return SDValue();
6347     }
6348
6349     if (InVec1 != Op1.getOperand(0))
6350       return SDValue();
6351
6352     // Update the pair of expected opcodes.
6353     std::swap(ExpectedOpcode, NextExpectedOpcode);
6354   }
6355
6356   // Don't try to fold this build_vector into a VSELECT if it has
6357   // too many UNDEF operands.
6358   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6359       InVec1.getOpcode() != ISD::UNDEF) {
6360     // Emit a sequence of vector add and sub followed by a VSELECT.
6361     // The new VSELECT will be lowered into a BLENDI.
6362     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6363     // and emit a single ADDSUB instruction.
6364     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6365     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6366
6367     // Construct the VSELECT mask.
6368     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6369     EVT SVT = MaskVT.getVectorElementType();
6370     unsigned SVTBits = SVT.getSizeInBits();
6371     SmallVector<SDValue, 8> Ops;
6372
6373     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6374       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6375                             APInt::getAllOnesValue(SVTBits);
6376       SDValue Constant = DAG.getConstant(Value, SVT);
6377       Ops.push_back(Constant);
6378     }
6379
6380     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6381     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6382   }
6383   
6384   return SDValue();
6385 }
6386
6387 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6388                                           const X86Subtarget *Subtarget) {
6389   SDLoc DL(N);
6390   EVT VT = N->getValueType(0);
6391   unsigned NumElts = VT.getVectorNumElements();
6392   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6393   SDValue InVec0, InVec1;
6394
6395   // Try to match an ADDSUB.
6396   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6397       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6398     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6399     if (Value.getNode())
6400       return Value;
6401   }
6402
6403   // Try to match horizontal ADD/SUB.
6404   unsigned NumUndefsLO = 0;
6405   unsigned NumUndefsHI = 0;
6406   unsigned Half = NumElts/2;
6407
6408   // Count the number of UNDEF operands in the build_vector in input.
6409   for (unsigned i = 0, e = Half; i != e; ++i)
6410     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6411       NumUndefsLO++;
6412
6413   for (unsigned i = Half, e = NumElts; i != e; ++i)
6414     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6415       NumUndefsHI++;
6416
6417   // Early exit if this is either a build_vector of all UNDEFs or all the
6418   // operands but one are UNDEF.
6419   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6420     return SDValue();
6421
6422   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6423     // Try to match an SSE3 float HADD/HSUB.
6424     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6425       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6426     
6427     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6428       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6429   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6430     // Try to match an SSSE3 integer HADD/HSUB.
6431     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6432       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6433     
6434     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6435       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6436   }
6437   
6438   if (!Subtarget->hasAVX())
6439     return SDValue();
6440
6441   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6442     // Try to match an AVX horizontal add/sub of packed single/double
6443     // precision floating point values from 256-bit vectors.
6444     SDValue InVec2, InVec3;
6445     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6446         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6447         ((InVec0.getOpcode() == ISD::UNDEF ||
6448           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6449         ((InVec1.getOpcode() == ISD::UNDEF ||
6450           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6451       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6452
6453     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6454         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6455         ((InVec0.getOpcode() == ISD::UNDEF ||
6456           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6457         ((InVec1.getOpcode() == ISD::UNDEF ||
6458           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6459       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6460   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6461     // Try to match an AVX2 horizontal add/sub of signed integers.
6462     SDValue InVec2, InVec3;
6463     unsigned X86Opcode;
6464     bool CanFold = true;
6465
6466     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6467         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6468         ((InVec0.getOpcode() == ISD::UNDEF ||
6469           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6470         ((InVec1.getOpcode() == ISD::UNDEF ||
6471           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6472       X86Opcode = X86ISD::HADD;
6473     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6474         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6475         ((InVec0.getOpcode() == ISD::UNDEF ||
6476           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6477         ((InVec1.getOpcode() == ISD::UNDEF ||
6478           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6479       X86Opcode = X86ISD::HSUB;
6480     else
6481       CanFold = false;
6482
6483     if (CanFold) {
6484       // Fold this build_vector into a single horizontal add/sub.
6485       // Do this only if the target has AVX2.
6486       if (Subtarget->hasAVX2())
6487         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6488  
6489       // Do not try to expand this build_vector into a pair of horizontal
6490       // add/sub if we can emit a pair of scalar add/sub.
6491       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6492         return SDValue();
6493
6494       // Convert this build_vector into a pair of horizontal binop followed by
6495       // a concat vector.
6496       bool isUndefLO = NumUndefsLO == Half;
6497       bool isUndefHI = NumUndefsHI == Half;
6498       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6499                                    isUndefLO, isUndefHI);
6500     }
6501   }
6502
6503   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6504        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6505     unsigned X86Opcode;
6506     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6507       X86Opcode = X86ISD::HADD;
6508     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6509       X86Opcode = X86ISD::HSUB;
6510     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6511       X86Opcode = X86ISD::FHADD;
6512     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6513       X86Opcode = X86ISD::FHSUB;
6514     else
6515       return SDValue();
6516
6517     // Don't try to expand this build_vector into a pair of horizontal add/sub
6518     // if we can simply emit a pair of scalar add/sub.
6519     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6520       return SDValue();
6521
6522     // Convert this build_vector into two horizontal add/sub followed by
6523     // a concat vector.
6524     bool isUndefLO = NumUndefsLO == Half;
6525     bool isUndefHI = NumUndefsHI == Half;
6526     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6527                                  isUndefLO, isUndefHI);
6528   }
6529
6530   return SDValue();
6531 }
6532
6533 SDValue
6534 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6535   SDLoc dl(Op);
6536
6537   MVT VT = Op.getSimpleValueType();
6538   MVT ExtVT = VT.getVectorElementType();
6539   unsigned NumElems = Op.getNumOperands();
6540
6541   // Generate vectors for predicate vectors.
6542   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6543     return LowerBUILD_VECTORvXi1(Op, DAG);
6544
6545   // Vectors containing all zeros can be matched by pxor and xorps later
6546   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6547     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6548     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6549     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6550       return Op;
6551
6552     return getZeroVector(VT, Subtarget, DAG, dl);
6553   }
6554
6555   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6556   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6557   // vpcmpeqd on 256-bit vectors.
6558   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6559     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6560       return Op;
6561
6562     if (!VT.is512BitVector())
6563       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6564   }
6565
6566   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6567   if (Broadcast.getNode())
6568     return Broadcast;
6569
6570   unsigned EVTBits = ExtVT.getSizeInBits();
6571
6572   unsigned NumZero  = 0;
6573   unsigned NumNonZero = 0;
6574   unsigned NonZeros = 0;
6575   bool IsAllConstants = true;
6576   SmallSet<SDValue, 8> Values;
6577   for (unsigned i = 0; i < NumElems; ++i) {
6578     SDValue Elt = Op.getOperand(i);
6579     if (Elt.getOpcode() == ISD::UNDEF)
6580       continue;
6581     Values.insert(Elt);
6582     if (Elt.getOpcode() != ISD::Constant &&
6583         Elt.getOpcode() != ISD::ConstantFP)
6584       IsAllConstants = false;
6585     if (X86::isZeroNode(Elt))
6586       NumZero++;
6587     else {
6588       NonZeros |= (1 << i);
6589       NumNonZero++;
6590     }
6591   }
6592
6593   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6594   if (NumNonZero == 0)
6595     return DAG.getUNDEF(VT);
6596
6597   // Special case for single non-zero, non-undef, element.
6598   if (NumNonZero == 1) {
6599     unsigned Idx = countTrailingZeros(NonZeros);
6600     SDValue Item = Op.getOperand(Idx);
6601
6602     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6603     // the value are obviously zero, truncate the value to i32 and do the
6604     // insertion that way.  Only do this if the value is non-constant or if the
6605     // value is a constant being inserted into element 0.  It is cheaper to do
6606     // a constant pool load than it is to do a movd + shuffle.
6607     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6608         (!IsAllConstants || Idx == 0)) {
6609       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6610         // Handle SSE only.
6611         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6612         EVT VecVT = MVT::v4i32;
6613         unsigned VecElts = 4;
6614
6615         // Truncate the value (which may itself be a constant) to i32, and
6616         // convert it to a vector with movd (S2V+shuffle to zero extend).
6617         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6618         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6619         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6620
6621         // Now we have our 32-bit value zero extended in the low element of
6622         // a vector.  If Idx != 0, swizzle it into place.
6623         if (Idx != 0) {
6624           SmallVector<int, 4> Mask;
6625           Mask.push_back(Idx);
6626           for (unsigned i = 1; i != VecElts; ++i)
6627             Mask.push_back(i);
6628           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6629                                       &Mask[0]);
6630         }
6631         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6632       }
6633     }
6634
6635     // If we have a constant or non-constant insertion into the low element of
6636     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6637     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6638     // depending on what the source datatype is.
6639     if (Idx == 0) {
6640       if (NumZero == 0)
6641         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6642
6643       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6644           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6645         if (VT.is256BitVector() || VT.is512BitVector()) {
6646           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6647           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6648                              Item, DAG.getIntPtrConstant(0));
6649         }
6650         assert(VT.is128BitVector() && "Expected an SSE value type!");
6651         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6652         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6653         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6654       }
6655
6656       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6657         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6658         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6659         if (VT.is256BitVector()) {
6660           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6661           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6662         } else {
6663           assert(VT.is128BitVector() && "Expected an SSE value type!");
6664           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6665         }
6666         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6667       }
6668     }
6669
6670     // Is it a vector logical left shift?
6671     if (NumElems == 2 && Idx == 1 &&
6672         X86::isZeroNode(Op.getOperand(0)) &&
6673         !X86::isZeroNode(Op.getOperand(1))) {
6674       unsigned NumBits = VT.getSizeInBits();
6675       return getVShift(true, VT,
6676                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6677                                    VT, Op.getOperand(1)),
6678                        NumBits/2, DAG, *this, dl);
6679     }
6680
6681     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6682       return SDValue();
6683
6684     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6685     // is a non-constant being inserted into an element other than the low one,
6686     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6687     // movd/movss) to move this into the low element, then shuffle it into
6688     // place.
6689     if (EVTBits == 32) {
6690       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6691
6692       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6693       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6694       SmallVector<int, 8> MaskVec;
6695       for (unsigned i = 0; i != NumElems; ++i)
6696         MaskVec.push_back(i == Idx ? 0 : 1);
6697       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6698     }
6699   }
6700
6701   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6702   if (Values.size() == 1) {
6703     if (EVTBits == 32) {
6704       // Instead of a shuffle like this:
6705       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6706       // Check if it's possible to issue this instead.
6707       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6708       unsigned Idx = countTrailingZeros(NonZeros);
6709       SDValue Item = Op.getOperand(Idx);
6710       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6711         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6712     }
6713     return SDValue();
6714   }
6715
6716   // A vector full of immediates; various special cases are already
6717   // handled, so this is best done with a single constant-pool load.
6718   if (IsAllConstants)
6719     return SDValue();
6720
6721   // For AVX-length vectors, build the individual 128-bit pieces and use
6722   // shuffles to put them in place.
6723   if (VT.is256BitVector() || VT.is512BitVector()) {
6724     SmallVector<SDValue, 64> V;
6725     for (unsigned i = 0; i != NumElems; ++i)
6726       V.push_back(Op.getOperand(i));
6727
6728     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6729
6730     // Build both the lower and upper subvector.
6731     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6732                                 makeArrayRef(&V[0], NumElems/2));
6733     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6734                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6735
6736     // Recreate the wider vector with the lower and upper part.
6737     if (VT.is256BitVector())
6738       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6739     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6740   }
6741
6742   // Let legalizer expand 2-wide build_vectors.
6743   if (EVTBits == 64) {
6744     if (NumNonZero == 1) {
6745       // One half is zero or undef.
6746       unsigned Idx = countTrailingZeros(NonZeros);
6747       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6748                                  Op.getOperand(Idx));
6749       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6750     }
6751     return SDValue();
6752   }
6753
6754   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6755   if (EVTBits == 8 && NumElems == 16) {
6756     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6757                                         Subtarget, *this);
6758     if (V.getNode()) return V;
6759   }
6760
6761   if (EVTBits == 16 && NumElems == 8) {
6762     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6763                                       Subtarget, *this);
6764     if (V.getNode()) return V;
6765   }
6766
6767   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6768   if (EVTBits == 32 && NumElems == 4) {
6769     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6770                                       NumZero, DAG, Subtarget, *this);
6771     if (V.getNode())
6772       return V;
6773   }
6774
6775   // If element VT is == 32 bits, turn it into a number of shuffles.
6776   SmallVector<SDValue, 8> V(NumElems);
6777   if (NumElems == 4 && NumZero > 0) {
6778     for (unsigned i = 0; i < 4; ++i) {
6779       bool isZero = !(NonZeros & (1 << i));
6780       if (isZero)
6781         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6782       else
6783         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6784     }
6785
6786     for (unsigned i = 0; i < 2; ++i) {
6787       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6788         default: break;
6789         case 0:
6790           V[i] = V[i*2];  // Must be a zero vector.
6791           break;
6792         case 1:
6793           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6794           break;
6795         case 2:
6796           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6797           break;
6798         case 3:
6799           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6800           break;
6801       }
6802     }
6803
6804     bool Reverse1 = (NonZeros & 0x3) == 2;
6805     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6806     int MaskVec[] = {
6807       Reverse1 ? 1 : 0,
6808       Reverse1 ? 0 : 1,
6809       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6810       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6811     };
6812     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6813   }
6814
6815   if (Values.size() > 1 && VT.is128BitVector()) {
6816     // Check for a build vector of consecutive loads.
6817     for (unsigned i = 0; i < NumElems; ++i)
6818       V[i] = Op.getOperand(i);
6819
6820     // Check for elements which are consecutive loads.
6821     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6822     if (LD.getNode())
6823       return LD;
6824
6825     // Check for a build vector from mostly shuffle plus few inserting.
6826     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6827     if (Sh.getNode())
6828       return Sh;
6829
6830     // For SSE 4.1, use insertps to put the high elements into the low element.
6831     if (getSubtarget()->hasSSE41()) {
6832       SDValue Result;
6833       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6834         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6835       else
6836         Result = DAG.getUNDEF(VT);
6837
6838       for (unsigned i = 1; i < NumElems; ++i) {
6839         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6840         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6841                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6842       }
6843       return Result;
6844     }
6845
6846     // Otherwise, expand into a number of unpckl*, start by extending each of
6847     // our (non-undef) elements to the full vector width with the element in the
6848     // bottom slot of the vector (which generates no code for SSE).
6849     for (unsigned i = 0; i < NumElems; ++i) {
6850       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6851         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6852       else
6853         V[i] = DAG.getUNDEF(VT);
6854     }
6855
6856     // Next, we iteratively mix elements, e.g. for v4f32:
6857     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6858     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6859     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6860     unsigned EltStride = NumElems >> 1;
6861     while (EltStride != 0) {
6862       for (unsigned i = 0; i < EltStride; ++i) {
6863         // If V[i+EltStride] is undef and this is the first round of mixing,
6864         // then it is safe to just drop this shuffle: V[i] is already in the
6865         // right place, the one element (since it's the first round) being
6866         // inserted as undef can be dropped.  This isn't safe for successive
6867         // rounds because they will permute elements within both vectors.
6868         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6869             EltStride == NumElems/2)
6870           continue;
6871
6872         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6873       }
6874       EltStride >>= 1;
6875     }
6876     return V[0];
6877   }
6878   return SDValue();
6879 }
6880
6881 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6882 // to create 256-bit vectors from two other 128-bit ones.
6883 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6884   SDLoc dl(Op);
6885   MVT ResVT = Op.getSimpleValueType();
6886
6887   assert((ResVT.is256BitVector() ||
6888           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6889
6890   SDValue V1 = Op.getOperand(0);
6891   SDValue V2 = Op.getOperand(1);
6892   unsigned NumElems = ResVT.getVectorNumElements();
6893   if(ResVT.is256BitVector())
6894     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6895
6896   if (Op.getNumOperands() == 4) {
6897     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6898                                 ResVT.getVectorNumElements()/2);
6899     SDValue V3 = Op.getOperand(2);
6900     SDValue V4 = Op.getOperand(3);
6901     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6902       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6903   }
6904   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6905 }
6906
6907 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6908   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6909   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6910          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6911           Op.getNumOperands() == 4)));
6912
6913   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6914   // from two other 128-bit ones.
6915
6916   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6917   return LowerAVXCONCAT_VECTORS(Op, DAG);
6918 }
6919
6920
6921 //===----------------------------------------------------------------------===//
6922 // Vector shuffle lowering
6923 //
6924 // This is an experimental code path for lowering vector shuffles on x86. It is
6925 // designed to handle arbitrary vector shuffles and blends, gracefully
6926 // degrading performance as necessary. It works hard to recognize idiomatic
6927 // shuffles and lower them to optimal instruction patterns without leaving
6928 // a framework that allows reasonably efficient handling of all vector shuffle
6929 // patterns.
6930 //===----------------------------------------------------------------------===//
6931
6932 /// \brief Tiny helper function to identify a no-op mask.
6933 ///
6934 /// This is a somewhat boring predicate function. It checks whether the mask
6935 /// array input, which is assumed to be a single-input shuffle mask of the kind
6936 /// used by the X86 shuffle instructions (not a fully general
6937 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6938 /// in-place shuffle are 'no-op's.
6939 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6940   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6941     if (Mask[i] != -1 && Mask[i] != i)
6942       return false;
6943   return true;
6944 }
6945
6946 /// \brief Helper function to classify a mask as a single-input mask.
6947 ///
6948 /// This isn't a generic single-input test because in the vector shuffle
6949 /// lowering we canonicalize single inputs to be the first input operand. This
6950 /// means we can more quickly test for a single input by only checking whether
6951 /// an input from the second operand exists. We also assume that the size of
6952 /// mask corresponds to the size of the input vectors which isn't true in the
6953 /// fully general case.
6954 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6955   for (int M : Mask)
6956     if (M >= (int)Mask.size())
6957       return false;
6958   return true;
6959 }
6960
6961 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6962 ///
6963 /// This helper function produces an 8-bit shuffle immediate corresponding to
6964 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6965 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6966 /// example.
6967 ///
6968 /// NB: We rely heavily on "undef" masks preserving the input lane.
6969 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6970                                           SelectionDAG &DAG) {
6971   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6972   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6973   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6974   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6975   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6976
6977   unsigned Imm = 0;
6978   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6979   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6980   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6981   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6982   return DAG.getConstant(Imm, MVT::i8);
6983 }
6984
6985 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6986 ///
6987 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6988 /// support for floating point shuffles but not integer shuffles. These
6989 /// instructions will incur a domain crossing penalty on some chips though so
6990 /// it is better to avoid lowering through this for integer vectors where
6991 /// possible.
6992 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6993                                        const X86Subtarget *Subtarget,
6994                                        SelectionDAG &DAG) {
6995   SDLoc DL(Op);
6996   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6997   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6998   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6999   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7000   ArrayRef<int> Mask = SVOp->getMask();
7001   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7002
7003   if (isSingleInputShuffleMask(Mask)) {
7004     // Straight shuffle of a single input vector. Simulate this by using the
7005     // single input as both of the "inputs" to this instruction..
7006     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7007     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7008                        DAG.getConstant(SHUFPDMask, MVT::i8));
7009   }
7010   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7011   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7012
7013   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7014   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7015                      DAG.getConstant(SHUFPDMask, MVT::i8));
7016 }
7017
7018 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7019 ///
7020 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7021 /// the integer unit to minimize domain crossing penalties. However, for blends
7022 /// it falls back to the floating point shuffle operation with appropriate bit
7023 /// casting.
7024 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7025                                        const X86Subtarget *Subtarget,
7026                                        SelectionDAG &DAG) {
7027   SDLoc DL(Op);
7028   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7029   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7030   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7031   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7032   ArrayRef<int> Mask = SVOp->getMask();
7033   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7034
7035   if (isSingleInputShuffleMask(Mask)) {
7036     // Straight shuffle of a single input vector. For everything from SSE2
7037     // onward this has a single fast instruction with no scary immediates.
7038     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7039     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7040     int WidenedMask[4] = {
7041         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7042         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7043     return DAG.getNode(
7044         ISD::BITCAST, DL, MVT::v2i64,
7045         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7046                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7047   }
7048
7049   // We implement this with SHUFPD which is pretty lame because it will likely
7050   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7051   // However, all the alternatives are still more cycles and newer chips don't
7052   // have this problem. It would be really nice if x86 had better shuffles here.
7053   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7054   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7055   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7056                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7057 }
7058
7059 /// \brief Lower 4-lane 32-bit floating point shuffles.
7060 ///
7061 /// Uses instructions exclusively from the floating point unit to minimize
7062 /// domain crossing penalties, as these are sufficient to implement all v4f32
7063 /// shuffles.
7064 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7065                                        const X86Subtarget *Subtarget,
7066                                        SelectionDAG &DAG) {
7067   SDLoc DL(Op);
7068   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7069   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7070   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7071   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7072   ArrayRef<int> Mask = SVOp->getMask();
7073   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7074
7075   SDValue LowV = V1, HighV = V2;
7076   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7077
7078   int NumV2Elements =
7079       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7080
7081   if (NumV2Elements == 0)
7082     // Straight shuffle of a single input vector. We pass the input vector to
7083     // both operands to simulate this with a SHUFPS.
7084     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7085                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7086
7087   if (NumV2Elements == 1) {
7088     int V2Index =
7089         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7090         Mask.begin();
7091     // Compute the index adjacent to V2Index and in the same half by toggling
7092     // the low bit.
7093     int V2AdjIndex = V2Index ^ 1;
7094
7095     if (Mask[V2AdjIndex] == -1) {
7096       // Handles all the cases where we have a single V2 element and an undef.
7097       // This will only ever happen in the high lanes because we commute the
7098       // vector otherwise.
7099       if (V2Index < 2)
7100         std::swap(LowV, HighV);
7101       NewMask[V2Index] -= 4;
7102     } else {
7103       // Handle the case where the V2 element ends up adjacent to a V1 element.
7104       // To make this work, blend them together as the first step.
7105       int V1Index = V2AdjIndex;
7106       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7107       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7108                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7109
7110       // Now proceed to reconstruct the final blend as we have the necessary
7111       // high or low half formed.
7112       if (V2Index < 2) {
7113         LowV = V2;
7114         HighV = V1;
7115       } else {
7116         HighV = V2;
7117       }
7118       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7119       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7120     }
7121   } else if (NumV2Elements == 2) {
7122     if (Mask[0] < 4 && Mask[1] < 4) {
7123       // Handle the easy case where we have V1 in the low lanes and V2 in the
7124       // high lanes. We never see this reversed because we sort the shuffle.
7125       NewMask[2] -= 4;
7126       NewMask[3] -= 4;
7127     } else {
7128       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7129       // trying to place elements directly, just blend them and set up the final
7130       // shuffle to place them.
7131
7132       // The first two blend mask elements are for V1, the second two are for
7133       // V2.
7134       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7135                           Mask[2] < 4 ? Mask[2] : Mask[3],
7136                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7137                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7138       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7139                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7140
7141       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7142       // a blend.
7143       LowV = HighV = V1;
7144       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7145       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7146       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7147       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7148     }
7149   }
7150   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7151                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7152 }
7153
7154 /// \brief Lower 4-lane i32 vector shuffles.
7155 ///
7156 /// We try to handle these with integer-domain shuffles where we can, but for
7157 /// blends we use the floating point domain blend instructions.
7158 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7159                                        const X86Subtarget *Subtarget,
7160                                        SelectionDAG &DAG) {
7161   SDLoc DL(Op);
7162   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7163   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7164   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7165   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7166   ArrayRef<int> Mask = SVOp->getMask();
7167   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7168
7169   if (isSingleInputShuffleMask(Mask))
7170     // Straight shuffle of a single input vector. For everything from SSE2
7171     // onward this has a single fast instruction with no scary immediates.
7172     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7173                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7174
7175   // We implement this with SHUFPS because it can blend from two vectors.
7176   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7177   // up the inputs, bypassing domain shift penalties that we would encur if we
7178   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7179   // relevant.
7180   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7181                      DAG.getVectorShuffle(
7182                          MVT::v4f32, DL,
7183                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7184                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7185 }
7186
7187 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7188 /// shuffle lowering, and the most complex part.
7189 ///
7190 /// The lowering strategy is to try to form pairs of input lanes which are
7191 /// targeted at the same half of the final vector, and then use a dword shuffle
7192 /// to place them onto the right half, and finally unpack the paired lanes into
7193 /// their final position.
7194 ///
7195 /// The exact breakdown of how to form these dword pairs and align them on the
7196 /// correct sides is really tricky. See the comments within the function for
7197 /// more of the details.
7198 static SDValue lowerV8I16SingleInputVectorShuffle(
7199     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7200     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7201   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7202   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7203   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7204
7205   SmallVector<int, 4> LoInputs;
7206   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7207                [](int M) { return M >= 0; });
7208   std::sort(LoInputs.begin(), LoInputs.end());
7209   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7210   SmallVector<int, 4> HiInputs;
7211   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7212                [](int M) { return M >= 0; });
7213   std::sort(HiInputs.begin(), HiInputs.end());
7214   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7215   int NumLToL =
7216       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7217   int NumHToL = LoInputs.size() - NumLToL;
7218   int NumLToH =
7219       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7220   int NumHToH = HiInputs.size() - NumLToH;
7221   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7222   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7223   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7224   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7225
7226   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7227   // such inputs we can swap two of the dwords across the half mark and end up
7228   // with <=2 inputs to each half in each half. Once there, we can fall through
7229   // to the generic code below. For example:
7230   //
7231   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7232   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7233   //
7234   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7235   // and 2-2.
7236   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7237                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7238     // Compute the index of dword with only one word among the three inputs in
7239     // a half by taking the sum of the half with three inputs and subtracting
7240     // the sum of the actual three inputs. The difference is the remaining
7241     // slot.
7242     int DWordA = (ThreeInputHalfSum -
7243                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7244                  2;
7245     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7246
7247     int PSHUFDMask[] = {0, 1, 2, 3};
7248     PSHUFDMask[DWordA] = DWordB;
7249     PSHUFDMask[DWordB] = DWordA;
7250     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7251                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7252                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7253                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7254
7255     // Adjust the mask to match the new locations of A and B.
7256     for (int &M : Mask)
7257       if (M != -1 && M/2 == DWordA)
7258         M = 2 * DWordB + M % 2;
7259       else if (M != -1 && M/2 == DWordB)
7260         M = 2 * DWordA + M % 2;
7261
7262     // Recurse back into this routine to re-compute state now that this isn't
7263     // a 3 and 1 problem.
7264     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7265                                 Mask);
7266   };
7267   if (NumLToL == 3 && NumHToL == 1)
7268     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7269   else if (NumLToL == 1 && NumHToL == 3)
7270     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7271   else if (NumLToH == 1 && NumHToH == 3)
7272     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7273   else if (NumLToH == 3 && NumHToH == 1)
7274     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7275
7276   // At this point there are at most two inputs to the low and high halves from
7277   // each half. That means the inputs can always be grouped into dwords and
7278   // those dwords can then be moved to the correct half with a dword shuffle.
7279   // We use at most one low and one high word shuffle to collect these paired
7280   // inputs into dwords, and finally a dword shuffle to place them.
7281   int PSHUFLMask[4] = {-1, -1, -1, -1};
7282   int PSHUFHMask[4] = {-1, -1, -1, -1};
7283   int PSHUFDMask[4] = {-1, -1, -1, -1};
7284
7285   // First fix the masks for all the inputs that are staying in their
7286   // original halves. This will then dictate the targets of the cross-half
7287   // shuffles.
7288   auto fixInPlaceInputs = [&PSHUFDMask](
7289       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7290       MutableArrayRef<int> HalfMask, int HalfOffset) {
7291     if (InPlaceInputs.empty())
7292       return;
7293     if (InPlaceInputs.size() == 1) {
7294       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7295           InPlaceInputs[0] - HalfOffset;
7296       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7297       return;
7298     }
7299
7300     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7301     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7302         InPlaceInputs[0] - HalfOffset;
7303     // Put the second input next to the first so that they are packed into
7304     // a dword. We find the adjacent index by toggling the low bit.
7305     int AdjIndex = InPlaceInputs[0] ^ 1;
7306     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7307     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7308     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7309   };
7310   if (!HToLInputs.empty())
7311     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7312   if (!LToHInputs.empty())
7313     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7314
7315   // Now gather the cross-half inputs and place them into a free dword of
7316   // their target half.
7317   // FIXME: This operation could almost certainly be simplified dramatically to
7318   // look more like the 3-1 fixing operation.
7319   auto moveInputsToRightHalf = [&PSHUFDMask](
7320       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7321       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7322       int SourceOffset, int DestOffset) {
7323     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7324       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7325     };
7326     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7327                                                int Word) {
7328       int LowWord = Word & ~1;
7329       int HighWord = Word | 1;
7330       return isWordClobbered(SourceHalfMask, LowWord) ||
7331              isWordClobbered(SourceHalfMask, HighWord);
7332     };
7333
7334     if (IncomingInputs.empty())
7335       return;
7336
7337     if (ExistingInputs.empty()) {
7338       // Map any dwords with inputs from them into the right half.
7339       for (int Input : IncomingInputs) {
7340         // If the source half mask maps over the inputs, turn those into
7341         // swaps and use the swapped lane.
7342         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7343           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7344             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7345                 Input - SourceOffset;
7346             // We have to swap the uses in our half mask in one sweep.
7347             for (int &M : HalfMask)
7348               if (M == SourceHalfMask[Input - SourceOffset])
7349                 M = Input;
7350               else if (M == Input)
7351                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7352           } else {
7353             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7354                        Input - SourceOffset &&
7355                    "Previous placement doesn't match!");
7356           }
7357           // Note that this correctly re-maps both when we do a swap and when
7358           // we observe the other side of the swap above. We rely on that to
7359           // avoid swapping the members of the input list directly.
7360           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7361         }
7362
7363         // Map the input's dword into the correct half.
7364         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7365           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7366         else
7367           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7368                      Input / 2 &&
7369                  "Previous placement doesn't match!");
7370       }
7371
7372       // And just directly shift any other-half mask elements to be same-half
7373       // as we will have mirrored the dword containing the element into the
7374       // same position within that half.
7375       for (int &M : HalfMask)
7376         if (M >= SourceOffset && M < SourceOffset + 4) {
7377           M = M - SourceOffset + DestOffset;
7378           assert(M >= 0 && "This should never wrap below zero!");
7379         }
7380       return;
7381     }
7382
7383     // Ensure we have the input in a viable dword of its current half. This
7384     // is particularly tricky because the original position may be clobbered
7385     // by inputs being moved and *staying* in that half.
7386     if (IncomingInputs.size() == 1) {
7387       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7388         int InputFixed = std::find(std::begin(SourceHalfMask),
7389                                    std::end(SourceHalfMask), -1) -
7390                          std::begin(SourceHalfMask) + SourceOffset;
7391         SourceHalfMask[InputFixed - SourceOffset] =
7392             IncomingInputs[0] - SourceOffset;
7393         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7394                      InputFixed);
7395         IncomingInputs[0] = InputFixed;
7396       }
7397     } else if (IncomingInputs.size() == 2) {
7398       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7399           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7400         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7401         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7402                "Not all dwords can be clobbered!");
7403         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7404         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7405         for (int &M : HalfMask)
7406           if (M == IncomingInputs[0])
7407             M = SourceDWordBase + SourceOffset;
7408           else if (M == IncomingInputs[1])
7409             M = SourceDWordBase + 1 + SourceOffset;
7410         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7411         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7412       }
7413     } else {
7414       llvm_unreachable("Unhandled input size!");
7415     }
7416
7417     // Now hoist the DWord down to the right half.
7418     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7419     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7420     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7421     for (int Input : IncomingInputs)
7422       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7423                    FreeDWord * 2 + Input % 2);
7424   };
7425   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7426                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7427   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7428                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7429
7430   // Now enact all the shuffles we've computed to move the inputs into their
7431   // target half.
7432   if (!isNoopShuffleMask(PSHUFLMask))
7433     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7434                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7435   if (!isNoopShuffleMask(PSHUFHMask))
7436     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7437                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7438   if (!isNoopShuffleMask(PSHUFDMask))
7439     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7440                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7441                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7442                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7443
7444   // At this point, each half should contain all its inputs, and we can then
7445   // just shuffle them into their final position.
7446   assert(std::count_if(LoMask.begin(), LoMask.end(),
7447                        [](int M) { return M >= 4; }) == 0 &&
7448          "Failed to lift all the high half inputs to the low mask!");
7449   assert(std::count_if(HiMask.begin(), HiMask.end(),
7450                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7451          "Failed to lift all the low half inputs to the high mask!");
7452
7453   // Do a half shuffle for the low mask.
7454   if (!isNoopShuffleMask(LoMask))
7455     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7456                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7457
7458   // Do a half shuffle with the high mask after shifting its values down.
7459   for (int &M : HiMask)
7460     if (M >= 0)
7461       M -= 4;
7462   if (!isNoopShuffleMask(HiMask))
7463     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7464                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7465
7466   return V;
7467 }
7468
7469 /// \brief Detect whether the mask pattern should be lowered through
7470 /// interleaving.
7471 ///
7472 /// This essentially tests whether viewing the mask as an interleaving of two
7473 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7474 /// lowering it through interleaving is a significantly better strategy.
7475 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7476   int NumEvenInputs[2] = {0, 0};
7477   int NumOddInputs[2] = {0, 0};
7478   int NumLoInputs[2] = {0, 0};
7479   int NumHiInputs[2] = {0, 0};
7480   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7481     if (Mask[i] < 0)
7482       continue;
7483
7484     int InputIdx = Mask[i] >= Size;
7485
7486     if (i < Size / 2)
7487       ++NumLoInputs[InputIdx];
7488     else
7489       ++NumHiInputs[InputIdx];
7490
7491     if ((i % 2) == 0)
7492       ++NumEvenInputs[InputIdx];
7493     else
7494       ++NumOddInputs[InputIdx];
7495   }
7496
7497   // The minimum number of cross-input results for both the interleaved and
7498   // split cases. If interleaving results in fewer cross-input results, return
7499   // true.
7500   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7501                                     NumEvenInputs[0] + NumOddInputs[1]);
7502   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7503                               NumLoInputs[0] + NumHiInputs[1]);
7504   return InterleavedCrosses < SplitCrosses;
7505 }
7506
7507 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7508 ///
7509 /// This strategy only works when the inputs from each vector fit into a single
7510 /// half of that vector, and generally there are not so many inputs as to leave
7511 /// the in-place shuffles required highly constrained (and thus expensive). It
7512 /// shifts all the inputs into a single side of both input vectors and then
7513 /// uses an unpack to interleave these inputs in a single vector. At that
7514 /// point, we will fall back on the generic single input shuffle lowering.
7515 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7516                                                  SDValue V2,
7517                                                  MutableArrayRef<int> Mask,
7518                                                  const X86Subtarget *Subtarget,
7519                                                  SelectionDAG &DAG) {
7520   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7521   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7522   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7523   for (int i = 0; i < 8; ++i)
7524     if (Mask[i] >= 0 && Mask[i] < 4)
7525       LoV1Inputs.push_back(i);
7526     else if (Mask[i] >= 4 && Mask[i] < 8)
7527       HiV1Inputs.push_back(i);
7528     else if (Mask[i] >= 8 && Mask[i] < 12)
7529       LoV2Inputs.push_back(i);
7530     else if (Mask[i] >= 12)
7531       HiV2Inputs.push_back(i);
7532
7533   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7534   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7535   (void)NumV1Inputs;
7536   (void)NumV2Inputs;
7537   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7538   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7539   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7540
7541   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7542                      HiV1Inputs.size() + HiV2Inputs.size();
7543
7544   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7545                               ArrayRef<int> HiInputs, bool MoveToLo,
7546                               int MaskOffset) {
7547     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7548     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7549     if (BadInputs.empty())
7550       return V;
7551
7552     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7553     int MoveOffset = MoveToLo ? 0 : 4;
7554
7555     if (GoodInputs.empty()) {
7556       for (int BadInput : BadInputs) {
7557         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7558         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7559       }
7560     } else {
7561       if (GoodInputs.size() == 2) {
7562         // If the low inputs are spread across two dwords, pack them into
7563         // a single dword.
7564         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7565             Mask[GoodInputs[0]] - MaskOffset;
7566         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7567             Mask[GoodInputs[1]] - MaskOffset;
7568         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7569         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7570       } else {
7571         // Otherwise pin the low inputs.
7572         for (int GoodInput : GoodInputs)
7573           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7574       }
7575
7576       int MoveMaskIdx =
7577           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7578           std::begin(MoveMask);
7579       assert(MoveMaskIdx >= MoveOffset && "Established above");
7580
7581       if (BadInputs.size() == 2) {
7582         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7583         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7584         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7585             Mask[BadInputs[0]] - MaskOffset;
7586         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7587             Mask[BadInputs[1]] - MaskOffset;
7588         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7589         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7590       } else {
7591         assert(BadInputs.size() == 1 && "All sizes handled");
7592         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7593         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7594       }
7595     }
7596
7597     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7598                                 MoveMask);
7599   };
7600   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7601                         /*MaskOffset*/ 0);
7602   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7603                         /*MaskOffset*/ 8);
7604
7605   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7606   // cross-half traffic in the final shuffle.
7607
7608   // Munge the mask to be a single-input mask after the unpack merges the
7609   // results.
7610   for (int &M : Mask)
7611     if (M != -1)
7612       M = 2 * (M % 4) + (M / 8);
7613
7614   return DAG.getVectorShuffle(
7615       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7616                                   DL, MVT::v8i16, V1, V2),
7617       DAG.getUNDEF(MVT::v8i16), Mask);
7618 }
7619
7620 /// \brief Generic lowering of 8-lane i16 shuffles.
7621 ///
7622 /// This handles both single-input shuffles and combined shuffle/blends with
7623 /// two inputs. The single input shuffles are immediately delegated to
7624 /// a dedicated lowering routine.
7625 ///
7626 /// The blends are lowered in one of three fundamental ways. If there are few
7627 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7628 /// of the input is significantly cheaper when lowered as an interleaving of
7629 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7630 /// halves of the inputs separately (making them have relatively few inputs)
7631 /// and then concatenate them.
7632 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7633                                        const X86Subtarget *Subtarget,
7634                                        SelectionDAG &DAG) {
7635   SDLoc DL(Op);
7636   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7637   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7638   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7639   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7640   ArrayRef<int> OrigMask = SVOp->getMask();
7641   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7642                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7643   MutableArrayRef<int> Mask(MaskStorage);
7644
7645   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7646
7647   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7648   auto isV2 = [](int M) { return M >= 8; };
7649
7650   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7651   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7652
7653   if (NumV2Inputs == 0)
7654     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7655
7656   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7657                             "to be V1-input shuffles.");
7658
7659   if (NumV1Inputs + NumV2Inputs <= 4)
7660     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7661
7662   // Check whether an interleaving lowering is likely to be more efficient.
7663   // This isn't perfect but it is a strong heuristic that tends to work well on
7664   // the kinds of shuffles that show up in practice.
7665   //
7666   // FIXME: Handle 1x, 2x, and 4x interleaving.
7667   if (shouldLowerAsInterleaving(Mask)) {
7668     // FIXME: Figure out whether we should pack these into the low or high
7669     // halves.
7670
7671     int EMask[8], OMask[8];
7672     for (int i = 0; i < 4; ++i) {
7673       EMask[i] = Mask[2*i];
7674       OMask[i] = Mask[2*i + 1];
7675       EMask[i + 4] = -1;
7676       OMask[i + 4] = -1;
7677     }
7678
7679     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7680     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7681
7682     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7683   }
7684
7685   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7686   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7687
7688   for (int i = 0; i < 4; ++i) {
7689     LoBlendMask[i] = Mask[i];
7690     HiBlendMask[i] = Mask[i + 4];
7691   }
7692
7693   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7694   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7695   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7696   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7697
7698   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7699                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7700 }
7701
7702 /// \brief Generic lowering of v16i8 shuffles.
7703 ///
7704 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7705 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7706 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7707 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7708 /// back together.
7709 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7710                                        const X86Subtarget *Subtarget,
7711                                        SelectionDAG &DAG) {
7712   SDLoc DL(Op);
7713   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7714   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7715   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7716   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7717   ArrayRef<int> OrigMask = SVOp->getMask();
7718   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7719   int MaskStorage[16] = {
7720       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7721       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7722       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7723       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7724   MutableArrayRef<int> Mask(MaskStorage);
7725   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7726   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7727
7728   // For single-input shuffles, there are some nicer lowering tricks we can use.
7729   if (isSingleInputShuffleMask(Mask)) {
7730     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7731     // Notably, this handles splat and partial-splat shuffles more efficiently.
7732     // However, it only makes sense if the pre-duplication shuffle simplifies
7733     // things significantly. Currently, this means we need to be able to
7734     // express the pre-duplication shuffle as an i16 shuffle.
7735     //
7736     // FIXME: We should check for other patterns which can be widened into an
7737     // i16 shuffle as well.
7738     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7739       for (int i = 0; i < 16; i += 2) {
7740         if (Mask[i] != Mask[i + 1])
7741           return false;
7742       }
7743       return true;
7744     };
7745     auto tryToWidenViaDuplication = [&]() -> SDValue {
7746       if (!canWidenViaDuplication(Mask))
7747         return SDValue();
7748       SmallVector<int, 4> LoInputs;
7749       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7750                    [](int M) { return M >= 0 && M < 8; });
7751       std::sort(LoInputs.begin(), LoInputs.end());
7752       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7753                      LoInputs.end());
7754       SmallVector<int, 4> HiInputs;
7755       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7756                    [](int M) { return M >= 8; });
7757       std::sort(HiInputs.begin(), HiInputs.end());
7758       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7759                      HiInputs.end());
7760
7761       bool TargetLo = LoInputs.size() >= HiInputs.size();
7762       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7763       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7764
7765       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7766       SmallDenseMap<int, int, 8> LaneMap;
7767       for (int I : InPlaceInputs) {
7768         PreDupI16Shuffle[I/2] = I/2;
7769         LaneMap[I] = I;
7770       }
7771       int j = TargetLo ? 0 : 4, je = j + 4;
7772       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7773         // Check if j is already a shuffle of this input. This happens when
7774         // there are two adjacent bytes after we move the low one.
7775         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7776           // If we haven't yet mapped the input, search for a slot into which
7777           // we can map it.
7778           while (j < je && PreDupI16Shuffle[j] != -1)
7779             ++j;
7780
7781           if (j == je)
7782             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7783             return SDValue();
7784
7785           // Map this input with the i16 shuffle.
7786           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7787         }
7788
7789         // Update the lane map based on the mapping we ended up with.
7790         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7791       }
7792       V1 = DAG.getNode(
7793           ISD::BITCAST, DL, MVT::v16i8,
7794           DAG.getVectorShuffle(MVT::v8i16, DL,
7795                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7796                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7797
7798       // Unpack the bytes to form the i16s that will be shuffled into place.
7799       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7800                        MVT::v16i8, V1, V1);
7801
7802       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7803       for (int i = 0; i < 16; i += 2) {
7804         if (Mask[i] != -1)
7805           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7806         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7807       }
7808       return DAG.getNode(
7809           ISD::BITCAST, DL, MVT::v16i8,
7810           DAG.getVectorShuffle(MVT::v8i16, DL,
7811                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7812                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7813     };
7814     if (SDValue V = tryToWidenViaDuplication())
7815       return V;
7816   }
7817
7818   // Check whether an interleaving lowering is likely to be more efficient.
7819   // This isn't perfect but it is a strong heuristic that tends to work well on
7820   // the kinds of shuffles that show up in practice.
7821   //
7822   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7823   if (shouldLowerAsInterleaving(Mask)) {
7824     // FIXME: Figure out whether we should pack these into the low or high
7825     // halves.
7826
7827     int EMask[16], OMask[16];
7828     for (int i = 0; i < 8; ++i) {
7829       EMask[i] = Mask[2*i];
7830       OMask[i] = Mask[2*i + 1];
7831       EMask[i + 8] = -1;
7832       OMask[i + 8] = -1;
7833     }
7834
7835     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7836     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7837
7838     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7839   }
7840
7841   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7842   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7843   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7844   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7845
7846   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7847                             MutableArrayRef<int> V1HalfBlendMask,
7848                             MutableArrayRef<int> V2HalfBlendMask) {
7849     for (int i = 0; i < 8; ++i)
7850       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7851         V1HalfBlendMask[i] = HalfMask[i];
7852         HalfMask[i] = i;
7853       } else if (HalfMask[i] >= 16) {
7854         V2HalfBlendMask[i] = HalfMask[i] - 16;
7855         HalfMask[i] = i + 8;
7856       }
7857   };
7858   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7859   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7860
7861   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7862
7863   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
7864                              MutableArrayRef<int> HiBlendMask) {
7865     SDValue V1, V2;
7866     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
7867     // them out and avoid using UNPCK{L,H} to extract the elements of V as
7868     // i16s.
7869     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
7870                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
7871         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
7872                      [](int M) { return M >= 0 && M % 2 == 1; })) {
7873       // Use a mask to drop the high bytes.
7874       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
7875       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
7876                        DAG.getConstant(0x00FF, MVT::v8i16));
7877
7878       // This will be a single vector shuffle instead of a blend so nuke V2.
7879       V2 = DAG.getUNDEF(MVT::v8i16);
7880
7881       // Squash the masks to point directly into V1.
7882       for (int &M : LoBlendMask)
7883         if (M >= 0)
7884           M /= 2;
7885       for (int &M : HiBlendMask)
7886         if (M >= 0)
7887           M /= 2;
7888     } else {
7889       // Otherwise just unpack the low half of V into V1 and the high half into
7890       // V2 so that we can blend them as i16s.
7891       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7892                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
7893       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7894                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
7895     }
7896
7897     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7898     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7899     return std::make_pair(BlendedLo, BlendedHi);
7900   };
7901   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
7902   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
7903   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
7904
7905   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7906   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7907
7908   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7909 }
7910
7911 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7912 ///
7913 /// This routine breaks down the specific type of 128-bit shuffle and
7914 /// dispatches to the lowering routines accordingly.
7915 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7916                                         MVT VT, const X86Subtarget *Subtarget,
7917                                         SelectionDAG &DAG) {
7918   switch (VT.SimpleTy) {
7919   case MVT::v2i64:
7920     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7921   case MVT::v2f64:
7922     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7923   case MVT::v4i32:
7924     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7925   case MVT::v4f32:
7926     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7927   case MVT::v8i16:
7928     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7929   case MVT::v16i8:
7930     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7931
7932   default:
7933     llvm_unreachable("Unimplemented!");
7934   }
7935 }
7936
7937 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7938 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7939   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7940     if (Mask[i] + 1 != Mask[i+1])
7941       return false;
7942
7943   return true;
7944 }
7945
7946 /// \brief Top-level lowering for x86 vector shuffles.
7947 ///
7948 /// This handles decomposition, canonicalization, and lowering of all x86
7949 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7950 /// above in helper routines. The canonicalization attempts to widen shuffles
7951 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7952 /// s.t. only one of the two inputs needs to be tested, etc.
7953 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7954                                   SelectionDAG &DAG) {
7955   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7956   ArrayRef<int> Mask = SVOp->getMask();
7957   SDValue V1 = Op.getOperand(0);
7958   SDValue V2 = Op.getOperand(1);
7959   MVT VT = Op.getSimpleValueType();
7960   int NumElements = VT.getVectorNumElements();
7961   SDLoc dl(Op);
7962
7963   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7964
7965   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7966   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7967   if (V1IsUndef && V2IsUndef)
7968     return DAG.getUNDEF(VT);
7969
7970   // When we create a shuffle node we put the UNDEF node to second operand,
7971   // but in some cases the first operand may be transformed to UNDEF.
7972   // In this case we should just commute the node.
7973   if (V1IsUndef)
7974     return DAG.getCommutedVectorShuffle(*SVOp);
7975
7976   // Check for non-undef masks pointing at an undef vector and make the masks
7977   // undef as well. This makes it easier to match the shuffle based solely on
7978   // the mask.
7979   if (V2IsUndef)
7980     for (int M : Mask)
7981       if (M >= NumElements) {
7982         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7983         for (int &M : NewMask)
7984           if (M >= NumElements)
7985             M = -1;
7986         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7987       }
7988
7989   // For integer vector shuffles, try to collapse them into a shuffle of fewer
7990   // lanes but wider integers. We cap this to not form integers larger than i64
7991   // but it might be interesting to form i128 integers to handle flipping the
7992   // low and high halves of AVX 256-bit vectors.
7993   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7994       areAdjacentMasksSequential(Mask)) {
7995     SmallVector<int, 8> NewMask;
7996     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7997       NewMask.push_back(Mask[i] / 2);
7998     MVT NewVT =
7999         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8000                          VT.getVectorNumElements() / 2);
8001     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8002     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8003     return DAG.getNode(ISD::BITCAST, dl, VT,
8004                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8005   }
8006
8007   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8008   for (int M : SVOp->getMask())
8009     if (M < 0)
8010       ++NumUndefElements;
8011     else if (M < NumElements)
8012       ++NumV1Elements;
8013     else
8014       ++NumV2Elements;
8015
8016   // Commute the shuffle as needed such that more elements come from V1 than
8017   // V2. This allows us to match the shuffle pattern strictly on how many
8018   // elements come from V1 without handling the symmetric cases.
8019   if (NumV2Elements > NumV1Elements)
8020     return DAG.getCommutedVectorShuffle(*SVOp);
8021
8022   // When the number of V1 and V2 elements are the same, try to minimize the
8023   // number of uses of V2 in the low half of the vector.
8024   if (NumV1Elements == NumV2Elements) {
8025     int LowV1Elements = 0, LowV2Elements = 0;
8026     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8027       if (M >= NumElements)
8028         ++LowV2Elements;
8029       else if (M >= 0)
8030         ++LowV1Elements;
8031     if (LowV2Elements > LowV1Elements)
8032       return DAG.getCommutedVectorShuffle(*SVOp);
8033   }
8034
8035   // For each vector width, delegate to a specialized lowering routine.
8036   if (VT.getSizeInBits() == 128)
8037     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8038
8039   llvm_unreachable("Unimplemented!");
8040 }
8041
8042
8043 //===----------------------------------------------------------------------===//
8044 // Legacy vector shuffle lowering
8045 //
8046 // This code is the legacy code handling vector shuffles until the above
8047 // replaces its functionality and performance.
8048 //===----------------------------------------------------------------------===//
8049
8050 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8051                         bool hasInt256, unsigned *MaskOut = nullptr) {
8052   MVT EltVT = VT.getVectorElementType();
8053
8054   // There is no blend with immediate in AVX-512.
8055   if (VT.is512BitVector())
8056     return false;
8057
8058   if (!hasSSE41 || EltVT == MVT::i8)
8059     return false;
8060   if (!hasInt256 && VT == MVT::v16i16)
8061     return false;
8062
8063   unsigned MaskValue = 0;
8064   unsigned NumElems = VT.getVectorNumElements();
8065   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8066   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8067   unsigned NumElemsInLane = NumElems / NumLanes;
8068
8069   // Blend for v16i16 should be symetric for the both lanes.
8070   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8071
8072     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8073     int EltIdx = MaskVals[i];
8074
8075     if ((EltIdx < 0 || EltIdx == (int)i) &&
8076         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8077       continue;
8078
8079     if (((unsigned)EltIdx == (i + NumElems)) &&
8080         (SndLaneEltIdx < 0 ||
8081          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8082       MaskValue |= (1 << i);
8083     else
8084       return false;
8085   }
8086
8087   if (MaskOut)
8088     *MaskOut = MaskValue;
8089   return true;
8090 }
8091
8092 // Try to lower a shuffle node into a simple blend instruction.
8093 // This function assumes isBlendMask returns true for this
8094 // SuffleVectorSDNode
8095 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8096                                           unsigned MaskValue,
8097                                           const X86Subtarget *Subtarget,
8098                                           SelectionDAG &DAG) {
8099   MVT VT = SVOp->getSimpleValueType(0);
8100   MVT EltVT = VT.getVectorElementType();
8101   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8102                      Subtarget->hasInt256() && "Trying to lower a "
8103                                                "VECTOR_SHUFFLE to a Blend but "
8104                                                "with the wrong mask"));
8105   SDValue V1 = SVOp->getOperand(0);
8106   SDValue V2 = SVOp->getOperand(1);
8107   SDLoc dl(SVOp);
8108   unsigned NumElems = VT.getVectorNumElements();
8109
8110   // Convert i32 vectors to floating point if it is not AVX2.
8111   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8112   MVT BlendVT = VT;
8113   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8114     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8115                                NumElems);
8116     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8117     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8118   }
8119
8120   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8121                             DAG.getConstant(MaskValue, MVT::i32));
8122   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8123 }
8124
8125 /// In vector type \p VT, return true if the element at index \p InputIdx
8126 /// falls on a different 128-bit lane than \p OutputIdx.
8127 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8128                                      unsigned OutputIdx) {
8129   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8130   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8131 }
8132
8133 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8134 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8135 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8136 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8137 /// zero.
8138 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8139                          SelectionDAG &DAG) {
8140   MVT VT = V1.getSimpleValueType();
8141   assert(VT.is128BitVector() || VT.is256BitVector());
8142
8143   MVT EltVT = VT.getVectorElementType();
8144   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8145   unsigned NumElts = VT.getVectorNumElements();
8146
8147   SmallVector<SDValue, 32> PshufbMask;
8148   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8149     int InputIdx = MaskVals[OutputIdx];
8150     unsigned InputByteIdx;
8151
8152     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8153       InputByteIdx = 0x80;
8154     else {
8155       // Cross lane is not allowed.
8156       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8157         return SDValue();
8158       InputByteIdx = InputIdx * EltSizeInBytes;
8159       // Index is an byte offset within the 128-bit lane.
8160       InputByteIdx &= 0xf;
8161     }
8162
8163     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8164       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8165       if (InputByteIdx != 0x80)
8166         ++InputByteIdx;
8167     }
8168   }
8169
8170   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8171   if (ShufVT != VT)
8172     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8173   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8174                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8175 }
8176
8177 // v8i16 shuffles - Prefer shuffles in the following order:
8178 // 1. [all]   pshuflw, pshufhw, optional move
8179 // 2. [ssse3] 1 x pshufb
8180 // 3. [ssse3] 2 x pshufb + 1 x por
8181 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8182 static SDValue
8183 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8184                          SelectionDAG &DAG) {
8185   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8186   SDValue V1 = SVOp->getOperand(0);
8187   SDValue V2 = SVOp->getOperand(1);
8188   SDLoc dl(SVOp);
8189   SmallVector<int, 8> MaskVals;
8190
8191   // Determine if more than 1 of the words in each of the low and high quadwords
8192   // of the result come from the same quadword of one of the two inputs.  Undef
8193   // mask values count as coming from any quadword, for better codegen.
8194   //
8195   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8196   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8197   unsigned LoQuad[] = { 0, 0, 0, 0 };
8198   unsigned HiQuad[] = { 0, 0, 0, 0 };
8199   // Indices of quads used.
8200   std::bitset<4> InputQuads;
8201   for (unsigned i = 0; i < 8; ++i) {
8202     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8203     int EltIdx = SVOp->getMaskElt(i);
8204     MaskVals.push_back(EltIdx);
8205     if (EltIdx < 0) {
8206       ++Quad[0];
8207       ++Quad[1];
8208       ++Quad[2];
8209       ++Quad[3];
8210       continue;
8211     }
8212     ++Quad[EltIdx / 4];
8213     InputQuads.set(EltIdx / 4);
8214   }
8215
8216   int BestLoQuad = -1;
8217   unsigned MaxQuad = 1;
8218   for (unsigned i = 0; i < 4; ++i) {
8219     if (LoQuad[i] > MaxQuad) {
8220       BestLoQuad = i;
8221       MaxQuad = LoQuad[i];
8222     }
8223   }
8224
8225   int BestHiQuad = -1;
8226   MaxQuad = 1;
8227   for (unsigned i = 0; i < 4; ++i) {
8228     if (HiQuad[i] > MaxQuad) {
8229       BestHiQuad = i;
8230       MaxQuad = HiQuad[i];
8231     }
8232   }
8233
8234   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8235   // of the two input vectors, shuffle them into one input vector so only a
8236   // single pshufb instruction is necessary. If there are more than 2 input
8237   // quads, disable the next transformation since it does not help SSSE3.
8238   bool V1Used = InputQuads[0] || InputQuads[1];
8239   bool V2Used = InputQuads[2] || InputQuads[3];
8240   if (Subtarget->hasSSSE3()) {
8241     if (InputQuads.count() == 2 && V1Used && V2Used) {
8242       BestLoQuad = InputQuads[0] ? 0 : 1;
8243       BestHiQuad = InputQuads[2] ? 2 : 3;
8244     }
8245     if (InputQuads.count() > 2) {
8246       BestLoQuad = -1;
8247       BestHiQuad = -1;
8248     }
8249   }
8250
8251   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8252   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8253   // words from all 4 input quadwords.
8254   SDValue NewV;
8255   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8256     int MaskV[] = {
8257       BestLoQuad < 0 ? 0 : BestLoQuad,
8258       BestHiQuad < 0 ? 1 : BestHiQuad
8259     };
8260     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8261                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8262                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8263     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8264
8265     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8266     // source words for the shuffle, to aid later transformations.
8267     bool AllWordsInNewV = true;
8268     bool InOrder[2] = { true, true };
8269     for (unsigned i = 0; i != 8; ++i) {
8270       int idx = MaskVals[i];
8271       if (idx != (int)i)
8272         InOrder[i/4] = false;
8273       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8274         continue;
8275       AllWordsInNewV = false;
8276       break;
8277     }
8278
8279     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8280     if (AllWordsInNewV) {
8281       for (int i = 0; i != 8; ++i) {
8282         int idx = MaskVals[i];
8283         if (idx < 0)
8284           continue;
8285         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8286         if ((idx != i) && idx < 4)
8287           pshufhw = false;
8288         if ((idx != i) && idx > 3)
8289           pshuflw = false;
8290       }
8291       V1 = NewV;
8292       V2Used = false;
8293       BestLoQuad = 0;
8294       BestHiQuad = 1;
8295     }
8296
8297     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8298     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8299     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8300       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8301       unsigned TargetMask = 0;
8302       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8303                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8304       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8305       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8306                              getShufflePSHUFLWImmediate(SVOp);
8307       V1 = NewV.getOperand(0);
8308       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8309     }
8310   }
8311
8312   // Promote splats to a larger type which usually leads to more efficient code.
8313   // FIXME: Is this true if pshufb is available?
8314   if (SVOp->isSplat())
8315     return PromoteSplat(SVOp, DAG);
8316
8317   // If we have SSSE3, and all words of the result are from 1 input vector,
8318   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8319   // is present, fall back to case 4.
8320   if (Subtarget->hasSSSE3()) {
8321     SmallVector<SDValue,16> pshufbMask;
8322
8323     // If we have elements from both input vectors, set the high bit of the
8324     // shuffle mask element to zero out elements that come from V2 in the V1
8325     // mask, and elements that come from V1 in the V2 mask, so that the two
8326     // results can be OR'd together.
8327     bool TwoInputs = V1Used && V2Used;
8328     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8329     if (!TwoInputs)
8330       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8331
8332     // Calculate the shuffle mask for the second input, shuffle it, and
8333     // OR it with the first shuffled input.
8334     CommuteVectorShuffleMask(MaskVals, 8);
8335     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8336     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8337     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8338   }
8339
8340   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8341   // and update MaskVals with new element order.
8342   std::bitset<8> InOrder;
8343   if (BestLoQuad >= 0) {
8344     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8345     for (int i = 0; i != 4; ++i) {
8346       int idx = MaskVals[i];
8347       if (idx < 0) {
8348         InOrder.set(i);
8349       } else if ((idx / 4) == BestLoQuad) {
8350         MaskV[i] = idx & 3;
8351         InOrder.set(i);
8352       }
8353     }
8354     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8355                                 &MaskV[0]);
8356
8357     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8358       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8359       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8360                                   NewV.getOperand(0),
8361                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8362     }
8363   }
8364
8365   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8366   // and update MaskVals with the new element order.
8367   if (BestHiQuad >= 0) {
8368     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8369     for (unsigned i = 4; i != 8; ++i) {
8370       int idx = MaskVals[i];
8371       if (idx < 0) {
8372         InOrder.set(i);
8373       } else if ((idx / 4) == BestHiQuad) {
8374         MaskV[i] = (idx & 3) + 4;
8375         InOrder.set(i);
8376       }
8377     }
8378     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8379                                 &MaskV[0]);
8380
8381     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8382       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8383       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8384                                   NewV.getOperand(0),
8385                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8386     }
8387   }
8388
8389   // In case BestHi & BestLo were both -1, which means each quadword has a word
8390   // from each of the four input quadwords, calculate the InOrder bitvector now
8391   // before falling through to the insert/extract cleanup.
8392   if (BestLoQuad == -1 && BestHiQuad == -1) {
8393     NewV = V1;
8394     for (int i = 0; i != 8; ++i)
8395       if (MaskVals[i] < 0 || MaskVals[i] == i)
8396         InOrder.set(i);
8397   }
8398
8399   // The other elements are put in the right place using pextrw and pinsrw.
8400   for (unsigned i = 0; i != 8; ++i) {
8401     if (InOrder[i])
8402       continue;
8403     int EltIdx = MaskVals[i];
8404     if (EltIdx < 0)
8405       continue;
8406     SDValue ExtOp = (EltIdx < 8) ?
8407       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8408                   DAG.getIntPtrConstant(EltIdx)) :
8409       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8410                   DAG.getIntPtrConstant(EltIdx - 8));
8411     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8412                        DAG.getIntPtrConstant(i));
8413   }
8414   return NewV;
8415 }
8416
8417 /// \brief v16i16 shuffles
8418 ///
8419 /// FIXME: We only support generation of a single pshufb currently.  We can
8420 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8421 /// well (e.g 2 x pshufb + 1 x por).
8422 static SDValue
8423 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8424   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8425   SDValue V1 = SVOp->getOperand(0);
8426   SDValue V2 = SVOp->getOperand(1);
8427   SDLoc dl(SVOp);
8428
8429   if (V2.getOpcode() != ISD::UNDEF)
8430     return SDValue();
8431
8432   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8433   return getPSHUFB(MaskVals, V1, dl, DAG);
8434 }
8435
8436 // v16i8 shuffles - Prefer shuffles in the following order:
8437 // 1. [ssse3] 1 x pshufb
8438 // 2. [ssse3] 2 x pshufb + 1 x por
8439 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8440 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8441                                         const X86Subtarget* Subtarget,
8442                                         SelectionDAG &DAG) {
8443   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8444   SDValue V1 = SVOp->getOperand(0);
8445   SDValue V2 = SVOp->getOperand(1);
8446   SDLoc dl(SVOp);
8447   ArrayRef<int> MaskVals = SVOp->getMask();
8448
8449   // Promote splats to a larger type which usually leads to more efficient code.
8450   // FIXME: Is this true if pshufb is available?
8451   if (SVOp->isSplat())
8452     return PromoteSplat(SVOp, DAG);
8453
8454   // If we have SSSE3, case 1 is generated when all result bytes come from
8455   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8456   // present, fall back to case 3.
8457
8458   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8459   if (Subtarget->hasSSSE3()) {
8460     SmallVector<SDValue,16> pshufbMask;
8461
8462     // If all result elements are from one input vector, then only translate
8463     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8464     //
8465     // Otherwise, we have elements from both input vectors, and must zero out
8466     // elements that come from V2 in the first mask, and V1 in the second mask
8467     // so that we can OR them together.
8468     for (unsigned i = 0; i != 16; ++i) {
8469       int EltIdx = MaskVals[i];
8470       if (EltIdx < 0 || EltIdx >= 16)
8471         EltIdx = 0x80;
8472       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8473     }
8474     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8475                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8476                                  MVT::v16i8, pshufbMask));
8477
8478     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8479     // the 2nd operand if it's undefined or zero.
8480     if (V2.getOpcode() == ISD::UNDEF ||
8481         ISD::isBuildVectorAllZeros(V2.getNode()))
8482       return V1;
8483
8484     // Calculate the shuffle mask for the second input, shuffle it, and
8485     // OR it with the first shuffled input.
8486     pshufbMask.clear();
8487     for (unsigned i = 0; i != 16; ++i) {
8488       int EltIdx = MaskVals[i];
8489       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8490       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8491     }
8492     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8493                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8494                                  MVT::v16i8, pshufbMask));
8495     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8496   }
8497
8498   // No SSSE3 - Calculate in place words and then fix all out of place words
8499   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8500   // the 16 different words that comprise the two doublequadword input vectors.
8501   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8502   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8503   SDValue NewV = V1;
8504   for (int i = 0; i != 8; ++i) {
8505     int Elt0 = MaskVals[i*2];
8506     int Elt1 = MaskVals[i*2+1];
8507
8508     // This word of the result is all undef, skip it.
8509     if (Elt0 < 0 && Elt1 < 0)
8510       continue;
8511
8512     // This word of the result is already in the correct place, skip it.
8513     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8514       continue;
8515
8516     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8517     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8518     SDValue InsElt;
8519
8520     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8521     // using a single extract together, load it and store it.
8522     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8523       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8524                            DAG.getIntPtrConstant(Elt1 / 2));
8525       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8526                         DAG.getIntPtrConstant(i));
8527       continue;
8528     }
8529
8530     // If Elt1 is defined, extract it from the appropriate source.  If the
8531     // source byte is not also odd, shift the extracted word left 8 bits
8532     // otherwise clear the bottom 8 bits if we need to do an or.
8533     if (Elt1 >= 0) {
8534       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8535                            DAG.getIntPtrConstant(Elt1 / 2));
8536       if ((Elt1 & 1) == 0)
8537         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8538                              DAG.getConstant(8,
8539                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8540       else if (Elt0 >= 0)
8541         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8542                              DAG.getConstant(0xFF00, MVT::i16));
8543     }
8544     // If Elt0 is defined, extract it from the appropriate source.  If the
8545     // source byte is not also even, shift the extracted word right 8 bits. If
8546     // Elt1 was also defined, OR the extracted values together before
8547     // inserting them in the result.
8548     if (Elt0 >= 0) {
8549       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8550                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8551       if ((Elt0 & 1) != 0)
8552         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8553                               DAG.getConstant(8,
8554                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8555       else if (Elt1 >= 0)
8556         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8557                              DAG.getConstant(0x00FF, MVT::i16));
8558       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8559                          : InsElt0;
8560     }
8561     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8562                        DAG.getIntPtrConstant(i));
8563   }
8564   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8565 }
8566
8567 // v32i8 shuffles - Translate to VPSHUFB if possible.
8568 static
8569 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8570                                  const X86Subtarget *Subtarget,
8571                                  SelectionDAG &DAG) {
8572   MVT VT = SVOp->getSimpleValueType(0);
8573   SDValue V1 = SVOp->getOperand(0);
8574   SDValue V2 = SVOp->getOperand(1);
8575   SDLoc dl(SVOp);
8576   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8577
8578   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8579   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8580   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8581
8582   // VPSHUFB may be generated if
8583   // (1) one of input vector is undefined or zeroinitializer.
8584   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8585   // And (2) the mask indexes don't cross the 128-bit lane.
8586   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8587       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8588     return SDValue();
8589
8590   if (V1IsAllZero && !V2IsAllZero) {
8591     CommuteVectorShuffleMask(MaskVals, 32);
8592     V1 = V2;
8593   }
8594   return getPSHUFB(MaskVals, V1, dl, DAG);
8595 }
8596
8597 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8598 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8599 /// done when every pair / quad of shuffle mask elements point to elements in
8600 /// the right sequence. e.g.
8601 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8602 static
8603 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8604                                  SelectionDAG &DAG) {
8605   MVT VT = SVOp->getSimpleValueType(0);
8606   SDLoc dl(SVOp);
8607   unsigned NumElems = VT.getVectorNumElements();
8608   MVT NewVT;
8609   unsigned Scale;
8610   switch (VT.SimpleTy) {
8611   default: llvm_unreachable("Unexpected!");
8612   case MVT::v2i64:
8613   case MVT::v2f64:
8614            return SDValue(SVOp, 0);
8615   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8616   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8617   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8618   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8619   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8620   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8621   }
8622
8623   SmallVector<int, 8> MaskVec;
8624   for (unsigned i = 0; i != NumElems; i += Scale) {
8625     int StartIdx = -1;
8626     for (unsigned j = 0; j != Scale; ++j) {
8627       int EltIdx = SVOp->getMaskElt(i+j);
8628       if (EltIdx < 0)
8629         continue;
8630       if (StartIdx < 0)
8631         StartIdx = (EltIdx / Scale);
8632       if (EltIdx != (int)(StartIdx*Scale + j))
8633         return SDValue();
8634     }
8635     MaskVec.push_back(StartIdx);
8636   }
8637
8638   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8639   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8640   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8641 }
8642
8643 /// getVZextMovL - Return a zero-extending vector move low node.
8644 ///
8645 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8646                             SDValue SrcOp, SelectionDAG &DAG,
8647                             const X86Subtarget *Subtarget, SDLoc dl) {
8648   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8649     LoadSDNode *LD = nullptr;
8650     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8651       LD = dyn_cast<LoadSDNode>(SrcOp);
8652     if (!LD) {
8653       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8654       // instead.
8655       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8656       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8657           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8658           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8659           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8660         // PR2108
8661         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8662         return DAG.getNode(ISD::BITCAST, dl, VT,
8663                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8664                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8665                                                    OpVT,
8666                                                    SrcOp.getOperand(0)
8667                                                           .getOperand(0))));
8668       }
8669     }
8670   }
8671
8672   return DAG.getNode(ISD::BITCAST, dl, VT,
8673                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8674                                  DAG.getNode(ISD::BITCAST, dl,
8675                                              OpVT, SrcOp)));
8676 }
8677
8678 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8679 /// which could not be matched by any known target speficic shuffle
8680 static SDValue
8681 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8682
8683   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8684   if (NewOp.getNode())
8685     return NewOp;
8686
8687   MVT VT = SVOp->getSimpleValueType(0);
8688
8689   unsigned NumElems = VT.getVectorNumElements();
8690   unsigned NumLaneElems = NumElems / 2;
8691
8692   SDLoc dl(SVOp);
8693   MVT EltVT = VT.getVectorElementType();
8694   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8695   SDValue Output[2];
8696
8697   SmallVector<int, 16> Mask;
8698   for (unsigned l = 0; l < 2; ++l) {
8699     // Build a shuffle mask for the output, discovering on the fly which
8700     // input vectors to use as shuffle operands (recorded in InputUsed).
8701     // If building a suitable shuffle vector proves too hard, then bail
8702     // out with UseBuildVector set.
8703     bool UseBuildVector = false;
8704     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8705     unsigned LaneStart = l * NumLaneElems;
8706     for (unsigned i = 0; i != NumLaneElems; ++i) {
8707       // The mask element.  This indexes into the input.
8708       int Idx = SVOp->getMaskElt(i+LaneStart);
8709       if (Idx < 0) {
8710         // the mask element does not index into any input vector.
8711         Mask.push_back(-1);
8712         continue;
8713       }
8714
8715       // The input vector this mask element indexes into.
8716       int Input = Idx / NumLaneElems;
8717
8718       // Turn the index into an offset from the start of the input vector.
8719       Idx -= Input * NumLaneElems;
8720
8721       // Find or create a shuffle vector operand to hold this input.
8722       unsigned OpNo;
8723       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8724         if (InputUsed[OpNo] == Input)
8725           // This input vector is already an operand.
8726           break;
8727         if (InputUsed[OpNo] < 0) {
8728           // Create a new operand for this input vector.
8729           InputUsed[OpNo] = Input;
8730           break;
8731         }
8732       }
8733
8734       if (OpNo >= array_lengthof(InputUsed)) {
8735         // More than two input vectors used!  Give up on trying to create a
8736         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8737         UseBuildVector = true;
8738         break;
8739       }
8740
8741       // Add the mask index for the new shuffle vector.
8742       Mask.push_back(Idx + OpNo * NumLaneElems);
8743     }
8744
8745     if (UseBuildVector) {
8746       SmallVector<SDValue, 16> SVOps;
8747       for (unsigned i = 0; i != NumLaneElems; ++i) {
8748         // The mask element.  This indexes into the input.
8749         int Idx = SVOp->getMaskElt(i+LaneStart);
8750         if (Idx < 0) {
8751           SVOps.push_back(DAG.getUNDEF(EltVT));
8752           continue;
8753         }
8754
8755         // The input vector this mask element indexes into.
8756         int Input = Idx / NumElems;
8757
8758         // Turn the index into an offset from the start of the input vector.
8759         Idx -= Input * NumElems;
8760
8761         // Extract the vector element by hand.
8762         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8763                                     SVOp->getOperand(Input),
8764                                     DAG.getIntPtrConstant(Idx)));
8765       }
8766
8767       // Construct the output using a BUILD_VECTOR.
8768       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8769     } else if (InputUsed[0] < 0) {
8770       // No input vectors were used! The result is undefined.
8771       Output[l] = DAG.getUNDEF(NVT);
8772     } else {
8773       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8774                                         (InputUsed[0] % 2) * NumLaneElems,
8775                                         DAG, dl);
8776       // If only one input was used, use an undefined vector for the other.
8777       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8778         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8779                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8780       // At least one input vector was used. Create a new shuffle vector.
8781       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8782     }
8783
8784     Mask.clear();
8785   }
8786
8787   // Concatenate the result back
8788   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8789 }
8790
8791 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8792 /// 4 elements, and match them with several different shuffle types.
8793 static SDValue
8794 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8795   SDValue V1 = SVOp->getOperand(0);
8796   SDValue V2 = SVOp->getOperand(1);
8797   SDLoc dl(SVOp);
8798   MVT VT = SVOp->getSimpleValueType(0);
8799
8800   assert(VT.is128BitVector() && "Unsupported vector size");
8801
8802   std::pair<int, int> Locs[4];
8803   int Mask1[] = { -1, -1, -1, -1 };
8804   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8805
8806   unsigned NumHi = 0;
8807   unsigned NumLo = 0;
8808   for (unsigned i = 0; i != 4; ++i) {
8809     int Idx = PermMask[i];
8810     if (Idx < 0) {
8811       Locs[i] = std::make_pair(-1, -1);
8812     } else {
8813       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8814       if (Idx < 4) {
8815         Locs[i] = std::make_pair(0, NumLo);
8816         Mask1[NumLo] = Idx;
8817         NumLo++;
8818       } else {
8819         Locs[i] = std::make_pair(1, NumHi);
8820         if (2+NumHi < 4)
8821           Mask1[2+NumHi] = Idx;
8822         NumHi++;
8823       }
8824     }
8825   }
8826
8827   if (NumLo <= 2 && NumHi <= 2) {
8828     // If no more than two elements come from either vector. This can be
8829     // implemented with two shuffles. First shuffle gather the elements.
8830     // The second shuffle, which takes the first shuffle as both of its
8831     // vector operands, put the elements into the right order.
8832     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8833
8834     int Mask2[] = { -1, -1, -1, -1 };
8835
8836     for (unsigned i = 0; i != 4; ++i)
8837       if (Locs[i].first != -1) {
8838         unsigned Idx = (i < 2) ? 0 : 4;
8839         Idx += Locs[i].first * 2 + Locs[i].second;
8840         Mask2[i] = Idx;
8841       }
8842
8843     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8844   }
8845
8846   if (NumLo == 3 || NumHi == 3) {
8847     // Otherwise, we must have three elements from one vector, call it X, and
8848     // one element from the other, call it Y.  First, use a shufps to build an
8849     // intermediate vector with the one element from Y and the element from X
8850     // that will be in the same half in the final destination (the indexes don't
8851     // matter). Then, use a shufps to build the final vector, taking the half
8852     // containing the element from Y from the intermediate, and the other half
8853     // from X.
8854     if (NumHi == 3) {
8855       // Normalize it so the 3 elements come from V1.
8856       CommuteVectorShuffleMask(PermMask, 4);
8857       std::swap(V1, V2);
8858     }
8859
8860     // Find the element from V2.
8861     unsigned HiIndex;
8862     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8863       int Val = PermMask[HiIndex];
8864       if (Val < 0)
8865         continue;
8866       if (Val >= 4)
8867         break;
8868     }
8869
8870     Mask1[0] = PermMask[HiIndex];
8871     Mask1[1] = -1;
8872     Mask1[2] = PermMask[HiIndex^1];
8873     Mask1[3] = -1;
8874     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8875
8876     if (HiIndex >= 2) {
8877       Mask1[0] = PermMask[0];
8878       Mask1[1] = PermMask[1];
8879       Mask1[2] = HiIndex & 1 ? 6 : 4;
8880       Mask1[3] = HiIndex & 1 ? 4 : 6;
8881       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8882     }
8883
8884     Mask1[0] = HiIndex & 1 ? 2 : 0;
8885     Mask1[1] = HiIndex & 1 ? 0 : 2;
8886     Mask1[2] = PermMask[2];
8887     Mask1[3] = PermMask[3];
8888     if (Mask1[2] >= 0)
8889       Mask1[2] += 4;
8890     if (Mask1[3] >= 0)
8891       Mask1[3] += 4;
8892     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8893   }
8894
8895   // Break it into (shuffle shuffle_hi, shuffle_lo).
8896   int LoMask[] = { -1, -1, -1, -1 };
8897   int HiMask[] = { -1, -1, -1, -1 };
8898
8899   int *MaskPtr = LoMask;
8900   unsigned MaskIdx = 0;
8901   unsigned LoIdx = 0;
8902   unsigned HiIdx = 2;
8903   for (unsigned i = 0; i != 4; ++i) {
8904     if (i == 2) {
8905       MaskPtr = HiMask;
8906       MaskIdx = 1;
8907       LoIdx = 0;
8908       HiIdx = 2;
8909     }
8910     int Idx = PermMask[i];
8911     if (Idx < 0) {
8912       Locs[i] = std::make_pair(-1, -1);
8913     } else if (Idx < 4) {
8914       Locs[i] = std::make_pair(MaskIdx, LoIdx);
8915       MaskPtr[LoIdx] = Idx;
8916       LoIdx++;
8917     } else {
8918       Locs[i] = std::make_pair(MaskIdx, HiIdx);
8919       MaskPtr[HiIdx] = Idx;
8920       HiIdx++;
8921     }
8922   }
8923
8924   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8925   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8926   int MaskOps[] = { -1, -1, -1, -1 };
8927   for (unsigned i = 0; i != 4; ++i)
8928     if (Locs[i].first != -1)
8929       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8930   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8931 }
8932
8933 static bool MayFoldVectorLoad(SDValue V) {
8934   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8935     V = V.getOperand(0);
8936
8937   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8938     V = V.getOperand(0);
8939   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8940       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8941     // BUILD_VECTOR (load), undef
8942     V = V.getOperand(0);
8943
8944   return MayFoldLoad(V);
8945 }
8946
8947 static
8948 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8949   MVT VT = Op.getSimpleValueType();
8950
8951   // Canonizalize to v2f64.
8952   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8953   return DAG.getNode(ISD::BITCAST, dl, VT,
8954                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8955                                           V1, DAG));
8956 }
8957
8958 static
8959 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8960                         bool HasSSE2) {
8961   SDValue V1 = Op.getOperand(0);
8962   SDValue V2 = Op.getOperand(1);
8963   MVT VT = Op.getSimpleValueType();
8964
8965   assert(VT != MVT::v2i64 && "unsupported shuffle type");
8966
8967   if (HasSSE2 && VT == MVT::v2f64)
8968     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8969
8970   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8971   return DAG.getNode(ISD::BITCAST, dl, VT,
8972                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8973                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8974                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8975 }
8976
8977 static
8978 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8979   SDValue V1 = Op.getOperand(0);
8980   SDValue V2 = Op.getOperand(1);
8981   MVT VT = Op.getSimpleValueType();
8982
8983   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8984          "unsupported shuffle type");
8985
8986   if (V2.getOpcode() == ISD::UNDEF)
8987     V2 = V1;
8988
8989   // v4i32 or v4f32
8990   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8991 }
8992
8993 static
8994 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8995   SDValue V1 = Op.getOperand(0);
8996   SDValue V2 = Op.getOperand(1);
8997   MVT VT = Op.getSimpleValueType();
8998   unsigned NumElems = VT.getVectorNumElements();
8999
9000   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9001   // operand of these instructions is only memory, so check if there's a
9002   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9003   // same masks.
9004   bool CanFoldLoad = false;
9005
9006   // Trivial case, when V2 comes from a load.
9007   if (MayFoldVectorLoad(V2))
9008     CanFoldLoad = true;
9009
9010   // When V1 is a load, it can be folded later into a store in isel, example:
9011   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9012   //    turns into:
9013   //  (MOVLPSmr addr:$src1, VR128:$src2)
9014   // So, recognize this potential and also use MOVLPS or MOVLPD
9015   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9016     CanFoldLoad = true;
9017
9018   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9019   if (CanFoldLoad) {
9020     if (HasSSE2 && NumElems == 2)
9021       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9022
9023     if (NumElems == 4)
9024       // If we don't care about the second element, proceed to use movss.
9025       if (SVOp->getMaskElt(1) != -1)
9026         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9027   }
9028
9029   // movl and movlp will both match v2i64, but v2i64 is never matched by
9030   // movl earlier because we make it strict to avoid messing with the movlp load
9031   // folding logic (see the code above getMOVLP call). Match it here then,
9032   // this is horrible, but will stay like this until we move all shuffle
9033   // matching to x86 specific nodes. Note that for the 1st condition all
9034   // types are matched with movsd.
9035   if (HasSSE2) {
9036     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9037     // as to remove this logic from here, as much as possible
9038     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9039       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9040     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9041   }
9042
9043   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9044
9045   // Invert the operand order and use SHUFPS to match it.
9046   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9047                               getShuffleSHUFImmediate(SVOp), DAG);
9048 }
9049
9050 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9051                                          SelectionDAG &DAG) {
9052   SDLoc dl(Load);
9053   MVT VT = Load->getSimpleValueType(0);
9054   MVT EVT = VT.getVectorElementType();
9055   SDValue Addr = Load->getOperand(1);
9056   SDValue NewAddr = DAG.getNode(
9057       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9058       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9059
9060   SDValue NewLoad =
9061       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9062                   DAG.getMachineFunction().getMachineMemOperand(
9063                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9064   return NewLoad;
9065 }
9066
9067 // It is only safe to call this function if isINSERTPSMask is true for
9068 // this shufflevector mask.
9069 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9070                            SelectionDAG &DAG) {
9071   // Generate an insertps instruction when inserting an f32 from memory onto a
9072   // v4f32 or when copying a member from one v4f32 to another.
9073   // We also use it for transferring i32 from one register to another,
9074   // since it simply copies the same bits.
9075   // If we're transferring an i32 from memory to a specific element in a
9076   // register, we output a generic DAG that will match the PINSRD
9077   // instruction.
9078   MVT VT = SVOp->getSimpleValueType(0);
9079   MVT EVT = VT.getVectorElementType();
9080   SDValue V1 = SVOp->getOperand(0);
9081   SDValue V2 = SVOp->getOperand(1);
9082   auto Mask = SVOp->getMask();
9083   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9084          "unsupported vector type for insertps/pinsrd");
9085
9086   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9087   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9088   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9089
9090   SDValue From;
9091   SDValue To;
9092   unsigned DestIndex;
9093   if (FromV1 == 1) {
9094     From = V1;
9095     To = V2;
9096     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9097                 Mask.begin();
9098
9099     // If we have 1 element from each vector, we have to check if we're
9100     // changing V1's element's place. If so, we're done. Otherwise, we
9101     // should assume we're changing V2's element's place and behave
9102     // accordingly.
9103     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9104     assert(DestIndex <= INT32_MAX && "truncated destination index");
9105     if (FromV1 == FromV2 &&
9106         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9107       From = V2;
9108       To = V1;
9109       DestIndex =
9110           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9111     }
9112   } else {
9113     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9114            "More than one element from V1 and from V2, or no elements from one "
9115            "of the vectors. This case should not have returned true from "
9116            "isINSERTPSMask");
9117     From = V2;
9118     To = V1;
9119     DestIndex =
9120         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9121   }
9122
9123   // Get an index into the source vector in the range [0,4) (the mask is
9124   // in the range [0,8) because it can address V1 and V2)
9125   unsigned SrcIndex = Mask[DestIndex] % 4;
9126   if (MayFoldLoad(From)) {
9127     // Trivial case, when From comes from a load and is only used by the
9128     // shuffle. Make it use insertps from the vector that we need from that
9129     // load.
9130     SDValue NewLoad =
9131         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9132     if (!NewLoad.getNode())
9133       return SDValue();
9134
9135     if (EVT == MVT::f32) {
9136       // Create this as a scalar to vector to match the instruction pattern.
9137       SDValue LoadScalarToVector =
9138           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9139       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9140       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9141                          InsertpsMask);
9142     } else { // EVT == MVT::i32
9143       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9144       // instruction, to match the PINSRD instruction, which loads an i32 to a
9145       // certain vector element.
9146       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9147                          DAG.getConstant(DestIndex, MVT::i32));
9148     }
9149   }
9150
9151   // Vector-element-to-vector
9152   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9153   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9154 }
9155
9156 // Reduce a vector shuffle to zext.
9157 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9158                                     SelectionDAG &DAG) {
9159   // PMOVZX is only available from SSE41.
9160   if (!Subtarget->hasSSE41())
9161     return SDValue();
9162
9163   MVT VT = Op.getSimpleValueType();
9164
9165   // Only AVX2 support 256-bit vector integer extending.
9166   if (!Subtarget->hasInt256() && VT.is256BitVector())
9167     return SDValue();
9168
9169   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9170   SDLoc DL(Op);
9171   SDValue V1 = Op.getOperand(0);
9172   SDValue V2 = Op.getOperand(1);
9173   unsigned NumElems = VT.getVectorNumElements();
9174
9175   // Extending is an unary operation and the element type of the source vector
9176   // won't be equal to or larger than i64.
9177   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9178       VT.getVectorElementType() == MVT::i64)
9179     return SDValue();
9180
9181   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9182   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9183   while ((1U << Shift) < NumElems) {
9184     if (SVOp->getMaskElt(1U << Shift) == 1)
9185       break;
9186     Shift += 1;
9187     // The maximal ratio is 8, i.e. from i8 to i64.
9188     if (Shift > 3)
9189       return SDValue();
9190   }
9191
9192   // Check the shuffle mask.
9193   unsigned Mask = (1U << Shift) - 1;
9194   for (unsigned i = 0; i != NumElems; ++i) {
9195     int EltIdx = SVOp->getMaskElt(i);
9196     if ((i & Mask) != 0 && EltIdx != -1)
9197       return SDValue();
9198     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9199       return SDValue();
9200   }
9201
9202   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9203   MVT NeVT = MVT::getIntegerVT(NBits);
9204   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9205
9206   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9207     return SDValue();
9208
9209   // Simplify the operand as it's prepared to be fed into shuffle.
9210   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9211   if (V1.getOpcode() == ISD::BITCAST &&
9212       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9213       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9214       V1.getOperand(0).getOperand(0)
9215         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9216     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9217     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9218     ConstantSDNode *CIdx =
9219       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9220     // If it's foldable, i.e. normal load with single use, we will let code
9221     // selection to fold it. Otherwise, we will short the conversion sequence.
9222     if (CIdx && CIdx->getZExtValue() == 0 &&
9223         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9224       MVT FullVT = V.getSimpleValueType();
9225       MVT V1VT = V1.getSimpleValueType();
9226       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9227         // The "ext_vec_elt" node is wider than the result node.
9228         // In this case we should extract subvector from V.
9229         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9230         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9231         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9232                                         FullVT.getVectorNumElements()/Ratio);
9233         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9234                         DAG.getIntPtrConstant(0));
9235       }
9236       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9237     }
9238   }
9239
9240   return DAG.getNode(ISD::BITCAST, DL, VT,
9241                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9242 }
9243
9244 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9245                                       SelectionDAG &DAG) {
9246   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9247   MVT VT = Op.getSimpleValueType();
9248   SDLoc dl(Op);
9249   SDValue V1 = Op.getOperand(0);
9250   SDValue V2 = Op.getOperand(1);
9251
9252   if (isZeroShuffle(SVOp))
9253     return getZeroVector(VT, Subtarget, DAG, dl);
9254
9255   // Handle splat operations
9256   if (SVOp->isSplat()) {
9257     // Use vbroadcast whenever the splat comes from a foldable load
9258     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9259     if (Broadcast.getNode())
9260       return Broadcast;
9261   }
9262
9263   // Check integer expanding shuffles.
9264   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9265   if (NewOp.getNode())
9266     return NewOp;
9267
9268   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9269   // do it!
9270   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9271       VT == MVT::v32i8) {
9272     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9273     if (NewOp.getNode())
9274       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9275   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9276     // FIXME: Figure out a cleaner way to do this.
9277     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9278       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9279       if (NewOp.getNode()) {
9280         MVT NewVT = NewOp.getSimpleValueType();
9281         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9282                                NewVT, true, false))
9283           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9284                               dl);
9285       }
9286     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9287       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9288       if (NewOp.getNode()) {
9289         MVT NewVT = NewOp.getSimpleValueType();
9290         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9291           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9292                               dl);
9293       }
9294     }
9295   }
9296   return SDValue();
9297 }
9298
9299 SDValue
9300 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9301   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9302   SDValue V1 = Op.getOperand(0);
9303   SDValue V2 = Op.getOperand(1);
9304   MVT VT = Op.getSimpleValueType();
9305   SDLoc dl(Op);
9306   unsigned NumElems = VT.getVectorNumElements();
9307   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9308   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9309   bool V1IsSplat = false;
9310   bool V2IsSplat = false;
9311   bool HasSSE2 = Subtarget->hasSSE2();
9312   bool HasFp256    = Subtarget->hasFp256();
9313   bool HasInt256   = Subtarget->hasInt256();
9314   MachineFunction &MF = DAG.getMachineFunction();
9315   bool OptForSize = MF.getFunction()->getAttributes().
9316     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9317
9318   // Check if we should use the experimental vector shuffle lowering. If so,
9319   // delegate completely to that code path.
9320   if (ExperimentalVectorShuffleLowering)
9321     return lowerVectorShuffle(Op, Subtarget, DAG);
9322
9323   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9324
9325   if (V1IsUndef && V2IsUndef)
9326     return DAG.getUNDEF(VT);
9327
9328   // When we create a shuffle node we put the UNDEF node to second operand,
9329   // but in some cases the first operand may be transformed to UNDEF.
9330   // In this case we should just commute the node.
9331   if (V1IsUndef)
9332     return DAG.getCommutedVectorShuffle(*SVOp);
9333
9334   // Vector shuffle lowering takes 3 steps:
9335   //
9336   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9337   //    narrowing and commutation of operands should be handled.
9338   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9339   //    shuffle nodes.
9340   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9341   //    so the shuffle can be broken into other shuffles and the legalizer can
9342   //    try the lowering again.
9343   //
9344   // The general idea is that no vector_shuffle operation should be left to
9345   // be matched during isel, all of them must be converted to a target specific
9346   // node here.
9347
9348   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9349   // narrowing and commutation of operands should be handled. The actual code
9350   // doesn't include all of those, work in progress...
9351   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9352   if (NewOp.getNode())
9353     return NewOp;
9354
9355   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9356
9357   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9358   // unpckh_undef). Only use pshufd if speed is more important than size.
9359   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9360     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9361   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9362     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9363
9364   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9365       V2IsUndef && MayFoldVectorLoad(V1))
9366     return getMOVDDup(Op, dl, V1, DAG);
9367
9368   if (isMOVHLPS_v_undef_Mask(M, VT))
9369     return getMOVHighToLow(Op, dl, DAG);
9370
9371   // Use to match splats
9372   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9373       (VT == MVT::v2f64 || VT == MVT::v2i64))
9374     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9375
9376   if (isPSHUFDMask(M, VT)) {
9377     // The actual implementation will match the mask in the if above and then
9378     // during isel it can match several different instructions, not only pshufd
9379     // as its name says, sad but true, emulate the behavior for now...
9380     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9381       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9382
9383     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9384
9385     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9386       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9387
9388     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9389       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9390                                   DAG);
9391
9392     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9393                                 TargetMask, DAG);
9394   }
9395
9396   if (isPALIGNRMask(M, VT, Subtarget))
9397     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9398                                 getShufflePALIGNRImmediate(SVOp),
9399                                 DAG);
9400
9401   // Check if this can be converted into a logical shift.
9402   bool isLeft = false;
9403   unsigned ShAmt = 0;
9404   SDValue ShVal;
9405   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9406   if (isShift && ShVal.hasOneUse()) {
9407     // If the shifted value has multiple uses, it may be cheaper to use
9408     // v_set0 + movlhps or movhlps, etc.
9409     MVT EltVT = VT.getVectorElementType();
9410     ShAmt *= EltVT.getSizeInBits();
9411     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9412   }
9413
9414   if (isMOVLMask(M, VT)) {
9415     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9416       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9417     if (!isMOVLPMask(M, VT)) {
9418       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9419         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9420
9421       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9422         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9423     }
9424   }
9425
9426   // FIXME: fold these into legal mask.
9427   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9428     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9429
9430   if (isMOVHLPSMask(M, VT))
9431     return getMOVHighToLow(Op, dl, DAG);
9432
9433   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9434     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9435
9436   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9437     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9438
9439   if (isMOVLPMask(M, VT))
9440     return getMOVLP(Op, dl, DAG, HasSSE2);
9441
9442   if (ShouldXformToMOVHLPS(M, VT) ||
9443       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9444     return DAG.getCommutedVectorShuffle(*SVOp);
9445
9446   if (isShift) {
9447     // No better options. Use a vshldq / vsrldq.
9448     MVT EltVT = VT.getVectorElementType();
9449     ShAmt *= EltVT.getSizeInBits();
9450     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9451   }
9452
9453   bool Commuted = false;
9454   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9455   // 1,1,1,1 -> v8i16 though.
9456   BitVector UndefElements;
9457   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9458     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9459       V1IsSplat = true;
9460   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9461     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9462       V2IsSplat = true;
9463
9464   // Canonicalize the splat or undef, if present, to be on the RHS.
9465   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9466     CommuteVectorShuffleMask(M, NumElems);
9467     std::swap(V1, V2);
9468     std::swap(V1IsSplat, V2IsSplat);
9469     Commuted = true;
9470   }
9471
9472   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9473     // Shuffling low element of v1 into undef, just return v1.
9474     if (V2IsUndef)
9475       return V1;
9476     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9477     // the instruction selector will not match, so get a canonical MOVL with
9478     // swapped operands to undo the commute.
9479     return getMOVL(DAG, dl, VT, V2, V1);
9480   }
9481
9482   if (isUNPCKLMask(M, VT, HasInt256))
9483     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9484
9485   if (isUNPCKHMask(M, VT, HasInt256))
9486     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9487
9488   if (V2IsSplat) {
9489     // Normalize mask so all entries that point to V2 points to its first
9490     // element then try to match unpck{h|l} again. If match, return a
9491     // new vector_shuffle with the corrected mask.p
9492     SmallVector<int, 8> NewMask(M.begin(), M.end());
9493     NormalizeMask(NewMask, NumElems);
9494     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9495       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9496     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9497       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9498   }
9499
9500   if (Commuted) {
9501     // Commute is back and try unpck* again.
9502     // FIXME: this seems wrong.
9503     CommuteVectorShuffleMask(M, NumElems);
9504     std::swap(V1, V2);
9505     std::swap(V1IsSplat, V2IsSplat);
9506
9507     if (isUNPCKLMask(M, VT, HasInt256))
9508       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9509
9510     if (isUNPCKHMask(M, VT, HasInt256))
9511       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9512   }
9513
9514   // Normalize the node to match x86 shuffle ops if needed
9515   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9516     return DAG.getCommutedVectorShuffle(*SVOp);
9517
9518   // The checks below are all present in isShuffleMaskLegal, but they are
9519   // inlined here right now to enable us to directly emit target specific
9520   // nodes, and remove one by one until they don't return Op anymore.
9521
9522   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9523       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9524     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9525       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9526   }
9527
9528   if (isPSHUFHWMask(M, VT, HasInt256))
9529     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9530                                 getShufflePSHUFHWImmediate(SVOp),
9531                                 DAG);
9532
9533   if (isPSHUFLWMask(M, VT, HasInt256))
9534     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9535                                 getShufflePSHUFLWImmediate(SVOp),
9536                                 DAG);
9537
9538   unsigned MaskValue;
9539   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9540                   &MaskValue))
9541     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9542
9543   if (isSHUFPMask(M, VT))
9544     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9545                                 getShuffleSHUFImmediate(SVOp), DAG);
9546
9547   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9548     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9549   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9550     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9551
9552   //===--------------------------------------------------------------------===//
9553   // Generate target specific nodes for 128 or 256-bit shuffles only
9554   // supported in the AVX instruction set.
9555   //
9556
9557   // Handle VMOVDDUPY permutations
9558   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9559     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9560
9561   // Handle VPERMILPS/D* permutations
9562   if (isVPERMILPMask(M, VT)) {
9563     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9564       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9565                                   getShuffleSHUFImmediate(SVOp), DAG);
9566     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9567                                 getShuffleSHUFImmediate(SVOp), DAG);
9568   }
9569
9570   unsigned Idx;
9571   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9572     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9573                               Idx*(NumElems/2), DAG, dl);
9574
9575   // Handle VPERM2F128/VPERM2I128 permutations
9576   if (isVPERM2X128Mask(M, VT, HasFp256))
9577     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9578                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9579
9580   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9581     return getINSERTPS(SVOp, dl, DAG);
9582
9583   unsigned Imm8;
9584   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9585     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9586
9587   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9588       VT.is512BitVector()) {
9589     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9590     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9591     SmallVector<SDValue, 16> permclMask;
9592     for (unsigned i = 0; i != NumElems; ++i) {
9593       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9594     }
9595
9596     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9597     if (V2IsUndef)
9598       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9599       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9600                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9601     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9602                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9603   }
9604
9605   //===--------------------------------------------------------------------===//
9606   // Since no target specific shuffle was selected for this generic one,
9607   // lower it into other known shuffles. FIXME: this isn't true yet, but
9608   // this is the plan.
9609   //
9610
9611   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9612   if (VT == MVT::v8i16) {
9613     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9614     if (NewOp.getNode())
9615       return NewOp;
9616   }
9617
9618   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9619     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9620     if (NewOp.getNode())
9621       return NewOp;
9622   }
9623
9624   if (VT == MVT::v16i8) {
9625     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9626     if (NewOp.getNode())
9627       return NewOp;
9628   }
9629
9630   if (VT == MVT::v32i8) {
9631     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9632     if (NewOp.getNode())
9633       return NewOp;
9634   }
9635
9636   // Handle all 128-bit wide vectors with 4 elements, and match them with
9637   // several different shuffle types.
9638   if (NumElems == 4 && VT.is128BitVector())
9639     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9640
9641   // Handle general 256-bit shuffles
9642   if (VT.is256BitVector())
9643     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9644
9645   return SDValue();
9646 }
9647
9648 // This function assumes its argument is a BUILD_VECTOR of constants or
9649 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9650 // true.
9651 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9652                                     unsigned &MaskValue) {
9653   MaskValue = 0;
9654   unsigned NumElems = BuildVector->getNumOperands();
9655   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9656   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9657   unsigned NumElemsInLane = NumElems / NumLanes;
9658
9659   // Blend for v16i16 should be symetric for the both lanes.
9660   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9661     SDValue EltCond = BuildVector->getOperand(i);
9662     SDValue SndLaneEltCond =
9663         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9664
9665     int Lane1Cond = -1, Lane2Cond = -1;
9666     if (isa<ConstantSDNode>(EltCond))
9667       Lane1Cond = !isZero(EltCond);
9668     if (isa<ConstantSDNode>(SndLaneEltCond))
9669       Lane2Cond = !isZero(SndLaneEltCond);
9670
9671     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9672       // Lane1Cond != 0, means we want the first argument.
9673       // Lane1Cond == 0, means we want the second argument.
9674       // The encoding of this argument is 0 for the first argument, 1
9675       // for the second. Therefore, invert the condition.
9676       MaskValue |= !Lane1Cond << i;
9677     else if (Lane1Cond < 0)
9678       MaskValue |= !Lane2Cond << i;
9679     else
9680       return false;
9681   }
9682   return true;
9683 }
9684
9685 // Try to lower a vselect node into a simple blend instruction.
9686 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9687                                    SelectionDAG &DAG) {
9688   SDValue Cond = Op.getOperand(0);
9689   SDValue LHS = Op.getOperand(1);
9690   SDValue RHS = Op.getOperand(2);
9691   SDLoc dl(Op);
9692   MVT VT = Op.getSimpleValueType();
9693   MVT EltVT = VT.getVectorElementType();
9694   unsigned NumElems = VT.getVectorNumElements();
9695
9696   // There is no blend with immediate in AVX-512.
9697   if (VT.is512BitVector())
9698     return SDValue();
9699
9700   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9701     return SDValue();
9702   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9703     return SDValue();
9704
9705   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9706     return SDValue();
9707
9708   // Check the mask for BLEND and build the value.
9709   unsigned MaskValue = 0;
9710   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9711     return SDValue();
9712
9713   // Convert i32 vectors to floating point if it is not AVX2.
9714   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9715   MVT BlendVT = VT;
9716   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9717     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9718                                NumElems);
9719     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9720     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9721   }
9722
9723   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9724                             DAG.getConstant(MaskValue, MVT::i32));
9725   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9726 }
9727
9728 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9729   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9730   if (BlendOp.getNode())
9731     return BlendOp;
9732
9733   // Some types for vselect were previously set to Expand, not Legal or
9734   // Custom. Return an empty SDValue so we fall-through to Expand, after
9735   // the Custom lowering phase.
9736   MVT VT = Op.getSimpleValueType();
9737   switch (VT.SimpleTy) {
9738   default:
9739     break;
9740   case MVT::v8i16:
9741   case MVT::v16i16:
9742     return SDValue();
9743   }
9744
9745   // We couldn't create a "Blend with immediate" node.
9746   // This node should still be legal, but we'll have to emit a blendv*
9747   // instruction.
9748   return Op;
9749 }
9750
9751 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9752   MVT VT = Op.getSimpleValueType();
9753   SDLoc dl(Op);
9754
9755   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9756     return SDValue();
9757
9758   if (VT.getSizeInBits() == 8) {
9759     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9760                                   Op.getOperand(0), Op.getOperand(1));
9761     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9762                                   DAG.getValueType(VT));
9763     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9764   }
9765
9766   if (VT.getSizeInBits() == 16) {
9767     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9768     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9769     if (Idx == 0)
9770       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9771                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9772                                      DAG.getNode(ISD::BITCAST, dl,
9773                                                  MVT::v4i32,
9774                                                  Op.getOperand(0)),
9775                                      Op.getOperand(1)));
9776     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9777                                   Op.getOperand(0), Op.getOperand(1));
9778     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9779                                   DAG.getValueType(VT));
9780     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9781   }
9782
9783   if (VT == MVT::f32) {
9784     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9785     // the result back to FR32 register. It's only worth matching if the
9786     // result has a single use which is a store or a bitcast to i32.  And in
9787     // the case of a store, it's not worth it if the index is a constant 0,
9788     // because a MOVSSmr can be used instead, which is smaller and faster.
9789     if (!Op.hasOneUse())
9790       return SDValue();
9791     SDNode *User = *Op.getNode()->use_begin();
9792     if ((User->getOpcode() != ISD::STORE ||
9793          (isa<ConstantSDNode>(Op.getOperand(1)) &&
9794           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9795         (User->getOpcode() != ISD::BITCAST ||
9796          User->getValueType(0) != MVT::i32))
9797       return SDValue();
9798     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9799                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9800                                               Op.getOperand(0)),
9801                                               Op.getOperand(1));
9802     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9803   }
9804
9805   if (VT == MVT::i32 || VT == MVT::i64) {
9806     // ExtractPS/pextrq works with constant index.
9807     if (isa<ConstantSDNode>(Op.getOperand(1)))
9808       return Op;
9809   }
9810   return SDValue();
9811 }
9812
9813 /// Extract one bit from mask vector, like v16i1 or v8i1.
9814 /// AVX-512 feature.
9815 SDValue
9816 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9817   SDValue Vec = Op.getOperand(0);
9818   SDLoc dl(Vec);
9819   MVT VecVT = Vec.getSimpleValueType();
9820   SDValue Idx = Op.getOperand(1);
9821   MVT EltVT = Op.getSimpleValueType();
9822
9823   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9824
9825   // variable index can't be handled in mask registers,
9826   // extend vector to VR512
9827   if (!isa<ConstantSDNode>(Idx)) {
9828     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9829     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9830     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9831                               ExtVT.getVectorElementType(), Ext, Idx);
9832     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9833   }
9834
9835   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9836   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9837   unsigned MaxSift = rc->getSize()*8 - 1;
9838   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9839                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9840   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9841                     DAG.getConstant(MaxSift, MVT::i8));
9842   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9843                        DAG.getIntPtrConstant(0));
9844 }
9845
9846 SDValue
9847 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9848                                            SelectionDAG &DAG) const {
9849   SDLoc dl(Op);
9850   SDValue Vec = Op.getOperand(0);
9851   MVT VecVT = Vec.getSimpleValueType();
9852   SDValue Idx = Op.getOperand(1);
9853
9854   if (Op.getSimpleValueType() == MVT::i1)
9855     return ExtractBitFromMaskVector(Op, DAG);
9856
9857   if (!isa<ConstantSDNode>(Idx)) {
9858     if (VecVT.is512BitVector() ||
9859         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9860          VecVT.getVectorElementType().getSizeInBits() == 32)) {
9861
9862       MVT MaskEltVT =
9863         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9864       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9865                                     MaskEltVT.getSizeInBits());
9866
9867       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9868       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9869                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
9870                                 Idx, DAG.getConstant(0, getPointerTy()));
9871       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9872       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9873                         Perm, DAG.getConstant(0, getPointerTy()));
9874     }
9875     return SDValue();
9876   }
9877
9878   // If this is a 256-bit vector result, first extract the 128-bit vector and
9879   // then extract the element from the 128-bit vector.
9880   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9881
9882     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9883     // Get the 128-bit vector.
9884     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9885     MVT EltVT = VecVT.getVectorElementType();
9886
9887     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9888
9889     //if (IdxVal >= NumElems/2)
9890     //  IdxVal -= NumElems/2;
9891     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9892     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9893                        DAG.getConstant(IdxVal, MVT::i32));
9894   }
9895
9896   assert(VecVT.is128BitVector() && "Unexpected vector length");
9897
9898   if (Subtarget->hasSSE41()) {
9899     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9900     if (Res.getNode())
9901       return Res;
9902   }
9903
9904   MVT VT = Op.getSimpleValueType();
9905   // TODO: handle v16i8.
9906   if (VT.getSizeInBits() == 16) {
9907     SDValue Vec = Op.getOperand(0);
9908     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9909     if (Idx == 0)
9910       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9911                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9912                                      DAG.getNode(ISD::BITCAST, dl,
9913                                                  MVT::v4i32, Vec),
9914                                      Op.getOperand(1)));
9915     // Transform it so it match pextrw which produces a 32-bit result.
9916     MVT EltVT = MVT::i32;
9917     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9918                                   Op.getOperand(0), Op.getOperand(1));
9919     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9920                                   DAG.getValueType(VT));
9921     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9922   }
9923
9924   if (VT.getSizeInBits() == 32) {
9925     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9926     if (Idx == 0)
9927       return Op;
9928
9929     // SHUFPS the element to the lowest double word, then movss.
9930     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9931     MVT VVT = Op.getOperand(0).getSimpleValueType();
9932     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9933                                        DAG.getUNDEF(VVT), Mask);
9934     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9935                        DAG.getIntPtrConstant(0));
9936   }
9937
9938   if (VT.getSizeInBits() == 64) {
9939     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9940     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9941     //        to match extract_elt for f64.
9942     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9943     if (Idx == 0)
9944       return Op;
9945
9946     // UNPCKHPD the element to the lowest double word, then movsd.
9947     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9948     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9949     int Mask[2] = { 1, -1 };
9950     MVT VVT = Op.getOperand(0).getSimpleValueType();
9951     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9952                                        DAG.getUNDEF(VVT), Mask);
9953     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9954                        DAG.getIntPtrConstant(0));
9955   }
9956
9957   return SDValue();
9958 }
9959
9960 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9961   MVT VT = Op.getSimpleValueType();
9962   MVT EltVT = VT.getVectorElementType();
9963   SDLoc dl(Op);
9964
9965   SDValue N0 = Op.getOperand(0);
9966   SDValue N1 = Op.getOperand(1);
9967   SDValue N2 = Op.getOperand(2);
9968
9969   if (!VT.is128BitVector())
9970     return SDValue();
9971
9972   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9973       isa<ConstantSDNode>(N2)) {
9974     unsigned Opc;
9975     if (VT == MVT::v8i16)
9976       Opc = X86ISD::PINSRW;
9977     else if (VT == MVT::v16i8)
9978       Opc = X86ISD::PINSRB;
9979     else
9980       Opc = X86ISD::PINSRB;
9981
9982     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9983     // argument.
9984     if (N1.getValueType() != MVT::i32)
9985       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9986     if (N2.getValueType() != MVT::i32)
9987       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9988     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9989   }
9990
9991   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9992     // Bits [7:6] of the constant are the source select.  This will always be
9993     //  zero here.  The DAG Combiner may combine an extract_elt index into these
9994     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
9995     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
9996     // Bits [5:4] of the constant are the destination select.  This is the
9997     //  value of the incoming immediate.
9998     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
9999     //   combine either bitwise AND or insert of float 0.0 to set these bits.
10000     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10001     // Create this as a scalar to vector..
10002     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10003     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10004   }
10005
10006   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10007     // PINSR* works with constant index.
10008     return Op;
10009   }
10010   return SDValue();
10011 }
10012
10013 /// Insert one bit to mask vector, like v16i1 or v8i1.
10014 /// AVX-512 feature.
10015 SDValue 
10016 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10017   SDLoc dl(Op);
10018   SDValue Vec = Op.getOperand(0);
10019   SDValue Elt = Op.getOperand(1);
10020   SDValue Idx = Op.getOperand(2);
10021   MVT VecVT = Vec.getSimpleValueType();
10022
10023   if (!isa<ConstantSDNode>(Idx)) {
10024     // Non constant index. Extend source and destination,
10025     // insert element and then truncate the result.
10026     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10027     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10028     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10029       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10030       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10031     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10032   }
10033
10034   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10035   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10036   if (Vec.getOpcode() == ISD::UNDEF)
10037     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10038                        DAG.getConstant(IdxVal, MVT::i8));
10039   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10040   unsigned MaxSift = rc->getSize()*8 - 1;
10041   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10042                     DAG.getConstant(MaxSift, MVT::i8));
10043   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10044                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10045   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10046 }
10047 SDValue
10048 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10049   MVT VT = Op.getSimpleValueType();
10050   MVT EltVT = VT.getVectorElementType();
10051   
10052   if (EltVT == MVT::i1)
10053     return InsertBitToMaskVector(Op, DAG);
10054
10055   SDLoc dl(Op);
10056   SDValue N0 = Op.getOperand(0);
10057   SDValue N1 = Op.getOperand(1);
10058   SDValue N2 = Op.getOperand(2);
10059
10060   // If this is a 256-bit vector result, first extract the 128-bit vector,
10061   // insert the element into the extracted half and then place it back.
10062   if (VT.is256BitVector() || VT.is512BitVector()) {
10063     if (!isa<ConstantSDNode>(N2))
10064       return SDValue();
10065
10066     // Get the desired 128-bit vector half.
10067     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10068     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10069
10070     // Insert the element into the desired half.
10071     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10072     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10073
10074     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10075                     DAG.getConstant(IdxIn128, MVT::i32));
10076
10077     // Insert the changed part back to the 256-bit vector
10078     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10079   }
10080
10081   if (Subtarget->hasSSE41())
10082     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10083
10084   if (EltVT == MVT::i8)
10085     return SDValue();
10086
10087   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10088     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10089     // as its second argument.
10090     if (N1.getValueType() != MVT::i32)
10091       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10092     if (N2.getValueType() != MVT::i32)
10093       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10094     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10095   }
10096   return SDValue();
10097 }
10098
10099 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10100   SDLoc dl(Op);
10101   MVT OpVT = Op.getSimpleValueType();
10102
10103   // If this is a 256-bit vector result, first insert into a 128-bit
10104   // vector and then insert into the 256-bit vector.
10105   if (!OpVT.is128BitVector()) {
10106     // Insert into a 128-bit vector.
10107     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10108     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10109                                  OpVT.getVectorNumElements() / SizeFactor);
10110
10111     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10112
10113     // Insert the 128-bit vector.
10114     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10115   }
10116
10117   if (OpVT == MVT::v1i64 &&
10118       Op.getOperand(0).getValueType() == MVT::i64)
10119     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10120
10121   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10122   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10123   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10124                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10125 }
10126
10127 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10128 // a simple subregister reference or explicit instructions to grab
10129 // upper bits of a vector.
10130 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10131                                       SelectionDAG &DAG) {
10132   SDLoc dl(Op);
10133   SDValue In =  Op.getOperand(0);
10134   SDValue Idx = Op.getOperand(1);
10135   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10136   MVT ResVT   = Op.getSimpleValueType();
10137   MVT InVT    = In.getSimpleValueType();
10138
10139   if (Subtarget->hasFp256()) {
10140     if (ResVT.is128BitVector() &&
10141         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10142         isa<ConstantSDNode>(Idx)) {
10143       return Extract128BitVector(In, IdxVal, DAG, dl);
10144     }
10145     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10146         isa<ConstantSDNode>(Idx)) {
10147       return Extract256BitVector(In, IdxVal, DAG, dl);
10148     }
10149   }
10150   return SDValue();
10151 }
10152
10153 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10154 // simple superregister reference or explicit instructions to insert
10155 // the upper bits of a vector.
10156 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10157                                      SelectionDAG &DAG) {
10158   if (Subtarget->hasFp256()) {
10159     SDLoc dl(Op.getNode());
10160     SDValue Vec = Op.getNode()->getOperand(0);
10161     SDValue SubVec = Op.getNode()->getOperand(1);
10162     SDValue Idx = Op.getNode()->getOperand(2);
10163
10164     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10165          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10166         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10167         isa<ConstantSDNode>(Idx)) {
10168       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10169       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10170     }
10171
10172     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10173         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10174         isa<ConstantSDNode>(Idx)) {
10175       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10176       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10177     }
10178   }
10179   return SDValue();
10180 }
10181
10182 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10183 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10184 // one of the above mentioned nodes. It has to be wrapped because otherwise
10185 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10186 // be used to form addressing mode. These wrapped nodes will be selected
10187 // into MOV32ri.
10188 SDValue
10189 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10190   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10191
10192   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10193   // global base reg.
10194   unsigned char OpFlag = 0;
10195   unsigned WrapperKind = X86ISD::Wrapper;
10196   CodeModel::Model M = DAG.getTarget().getCodeModel();
10197
10198   if (Subtarget->isPICStyleRIPRel() &&
10199       (M == CodeModel::Small || M == CodeModel::Kernel))
10200     WrapperKind = X86ISD::WrapperRIP;
10201   else if (Subtarget->isPICStyleGOT())
10202     OpFlag = X86II::MO_GOTOFF;
10203   else if (Subtarget->isPICStyleStubPIC())
10204     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10205
10206   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10207                                              CP->getAlignment(),
10208                                              CP->getOffset(), OpFlag);
10209   SDLoc DL(CP);
10210   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10211   // With PIC, the address is actually $g + Offset.
10212   if (OpFlag) {
10213     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10214                          DAG.getNode(X86ISD::GlobalBaseReg,
10215                                      SDLoc(), getPointerTy()),
10216                          Result);
10217   }
10218
10219   return Result;
10220 }
10221
10222 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10223   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10224
10225   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10226   // global base reg.
10227   unsigned char OpFlag = 0;
10228   unsigned WrapperKind = X86ISD::Wrapper;
10229   CodeModel::Model M = DAG.getTarget().getCodeModel();
10230
10231   if (Subtarget->isPICStyleRIPRel() &&
10232       (M == CodeModel::Small || M == CodeModel::Kernel))
10233     WrapperKind = X86ISD::WrapperRIP;
10234   else if (Subtarget->isPICStyleGOT())
10235     OpFlag = X86II::MO_GOTOFF;
10236   else if (Subtarget->isPICStyleStubPIC())
10237     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10238
10239   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10240                                           OpFlag);
10241   SDLoc DL(JT);
10242   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10243
10244   // With PIC, the address is actually $g + Offset.
10245   if (OpFlag)
10246     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10247                          DAG.getNode(X86ISD::GlobalBaseReg,
10248                                      SDLoc(), getPointerTy()),
10249                          Result);
10250
10251   return Result;
10252 }
10253
10254 SDValue
10255 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10256   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10257
10258   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10259   // global base reg.
10260   unsigned char OpFlag = 0;
10261   unsigned WrapperKind = X86ISD::Wrapper;
10262   CodeModel::Model M = DAG.getTarget().getCodeModel();
10263
10264   if (Subtarget->isPICStyleRIPRel() &&
10265       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10266     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10267       OpFlag = X86II::MO_GOTPCREL;
10268     WrapperKind = X86ISD::WrapperRIP;
10269   } else if (Subtarget->isPICStyleGOT()) {
10270     OpFlag = X86II::MO_GOT;
10271   } else if (Subtarget->isPICStyleStubPIC()) {
10272     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10273   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10274     OpFlag = X86II::MO_DARWIN_NONLAZY;
10275   }
10276
10277   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10278
10279   SDLoc DL(Op);
10280   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10281
10282   // With PIC, the address is actually $g + Offset.
10283   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10284       !Subtarget->is64Bit()) {
10285     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10286                          DAG.getNode(X86ISD::GlobalBaseReg,
10287                                      SDLoc(), getPointerTy()),
10288                          Result);
10289   }
10290
10291   // For symbols that require a load from a stub to get the address, emit the
10292   // load.
10293   if (isGlobalStubReference(OpFlag))
10294     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10295                          MachinePointerInfo::getGOT(), false, false, false, 0);
10296
10297   return Result;
10298 }
10299
10300 SDValue
10301 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10302   // Create the TargetBlockAddressAddress node.
10303   unsigned char OpFlags =
10304     Subtarget->ClassifyBlockAddressReference();
10305   CodeModel::Model M = DAG.getTarget().getCodeModel();
10306   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10307   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10308   SDLoc dl(Op);
10309   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10310                                              OpFlags);
10311
10312   if (Subtarget->isPICStyleRIPRel() &&
10313       (M == CodeModel::Small || M == CodeModel::Kernel))
10314     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10315   else
10316     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10317
10318   // With PIC, the address is actually $g + Offset.
10319   if (isGlobalRelativeToPICBase(OpFlags)) {
10320     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10321                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10322                          Result);
10323   }
10324
10325   return Result;
10326 }
10327
10328 SDValue
10329 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10330                                       int64_t Offset, SelectionDAG &DAG) const {
10331   // Create the TargetGlobalAddress node, folding in the constant
10332   // offset if it is legal.
10333   unsigned char OpFlags =
10334       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10335   CodeModel::Model M = DAG.getTarget().getCodeModel();
10336   SDValue Result;
10337   if (OpFlags == X86II::MO_NO_FLAG &&
10338       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10339     // A direct static reference to a global.
10340     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10341     Offset = 0;
10342   } else {
10343     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10344   }
10345
10346   if (Subtarget->isPICStyleRIPRel() &&
10347       (M == CodeModel::Small || M == CodeModel::Kernel))
10348     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10349   else
10350     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10351
10352   // With PIC, the address is actually $g + Offset.
10353   if (isGlobalRelativeToPICBase(OpFlags)) {
10354     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10355                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10356                          Result);
10357   }
10358
10359   // For globals that require a load from a stub to get the address, emit the
10360   // load.
10361   if (isGlobalStubReference(OpFlags))
10362     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10363                          MachinePointerInfo::getGOT(), false, false, false, 0);
10364
10365   // If there was a non-zero offset that we didn't fold, create an explicit
10366   // addition for it.
10367   if (Offset != 0)
10368     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10369                          DAG.getConstant(Offset, getPointerTy()));
10370
10371   return Result;
10372 }
10373
10374 SDValue
10375 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10376   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10377   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10378   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10379 }
10380
10381 static SDValue
10382 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10383            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10384            unsigned char OperandFlags, bool LocalDynamic = false) {
10385   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10386   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10387   SDLoc dl(GA);
10388   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10389                                            GA->getValueType(0),
10390                                            GA->getOffset(),
10391                                            OperandFlags);
10392
10393   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10394                                            : X86ISD::TLSADDR;
10395
10396   if (InFlag) {
10397     SDValue Ops[] = { Chain,  TGA, *InFlag };
10398     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10399   } else {
10400     SDValue Ops[]  = { Chain, TGA };
10401     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10402   }
10403
10404   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10405   MFI->setAdjustsStack(true);
10406
10407   SDValue Flag = Chain.getValue(1);
10408   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10409 }
10410
10411 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10412 static SDValue
10413 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10414                                 const EVT PtrVT) {
10415   SDValue InFlag;
10416   SDLoc dl(GA);  // ? function entry point might be better
10417   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10418                                    DAG.getNode(X86ISD::GlobalBaseReg,
10419                                                SDLoc(), PtrVT), InFlag);
10420   InFlag = Chain.getValue(1);
10421
10422   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10423 }
10424
10425 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10426 static SDValue
10427 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10428                                 const EVT PtrVT) {
10429   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10430                     X86::RAX, X86II::MO_TLSGD);
10431 }
10432
10433 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10434                                            SelectionDAG &DAG,
10435                                            const EVT PtrVT,
10436                                            bool is64Bit) {
10437   SDLoc dl(GA);
10438
10439   // Get the start address of the TLS block for this module.
10440   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10441       .getInfo<X86MachineFunctionInfo>();
10442   MFI->incNumLocalDynamicTLSAccesses();
10443
10444   SDValue Base;
10445   if (is64Bit) {
10446     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10447                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10448   } else {
10449     SDValue InFlag;
10450     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10451         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10452     InFlag = Chain.getValue(1);
10453     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10454                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10455   }
10456
10457   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10458   // of Base.
10459
10460   // Build x@dtpoff.
10461   unsigned char OperandFlags = X86II::MO_DTPOFF;
10462   unsigned WrapperKind = X86ISD::Wrapper;
10463   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10464                                            GA->getValueType(0),
10465                                            GA->getOffset(), OperandFlags);
10466   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10467
10468   // Add x@dtpoff with the base.
10469   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10470 }
10471
10472 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10473 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10474                                    const EVT PtrVT, TLSModel::Model model,
10475                                    bool is64Bit, bool isPIC) {
10476   SDLoc dl(GA);
10477
10478   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10479   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10480                                                          is64Bit ? 257 : 256));
10481
10482   SDValue ThreadPointer =
10483       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10484                   MachinePointerInfo(Ptr), false, false, false, 0);
10485
10486   unsigned char OperandFlags = 0;
10487   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10488   // initialexec.
10489   unsigned WrapperKind = X86ISD::Wrapper;
10490   if (model == TLSModel::LocalExec) {
10491     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10492   } else if (model == TLSModel::InitialExec) {
10493     if (is64Bit) {
10494       OperandFlags = X86II::MO_GOTTPOFF;
10495       WrapperKind = X86ISD::WrapperRIP;
10496     } else {
10497       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10498     }
10499   } else {
10500     llvm_unreachable("Unexpected model");
10501   }
10502
10503   // emit "addl x@ntpoff,%eax" (local exec)
10504   // or "addl x@indntpoff,%eax" (initial exec)
10505   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10506   SDValue TGA =
10507       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10508                                  GA->getOffset(), OperandFlags);
10509   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10510
10511   if (model == TLSModel::InitialExec) {
10512     if (isPIC && !is64Bit) {
10513       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10514                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10515                            Offset);
10516     }
10517
10518     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10519                          MachinePointerInfo::getGOT(), false, false, false, 0);
10520   }
10521
10522   // The address of the thread local variable is the add of the thread
10523   // pointer with the offset of the variable.
10524   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10525 }
10526
10527 SDValue
10528 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10529
10530   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10531   const GlobalValue *GV = GA->getGlobal();
10532
10533   if (Subtarget->isTargetELF()) {
10534     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10535
10536     switch (model) {
10537       case TLSModel::GeneralDynamic:
10538         if (Subtarget->is64Bit())
10539           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10540         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10541       case TLSModel::LocalDynamic:
10542         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10543                                            Subtarget->is64Bit());
10544       case TLSModel::InitialExec:
10545       case TLSModel::LocalExec:
10546         return LowerToTLSExecModel(
10547             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10548             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10549     }
10550     llvm_unreachable("Unknown TLS model.");
10551   }
10552
10553   if (Subtarget->isTargetDarwin()) {
10554     // Darwin only has one model of TLS.  Lower to that.
10555     unsigned char OpFlag = 0;
10556     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10557                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10558
10559     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10560     // global base reg.
10561     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10562                  !Subtarget->is64Bit();
10563     if (PIC32)
10564       OpFlag = X86II::MO_TLVP_PIC_BASE;
10565     else
10566       OpFlag = X86II::MO_TLVP;
10567     SDLoc DL(Op);
10568     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10569                                                 GA->getValueType(0),
10570                                                 GA->getOffset(), OpFlag);
10571     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10572
10573     // With PIC32, the address is actually $g + Offset.
10574     if (PIC32)
10575       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10576                            DAG.getNode(X86ISD::GlobalBaseReg,
10577                                        SDLoc(), getPointerTy()),
10578                            Offset);
10579
10580     // Lowering the machine isd will make sure everything is in the right
10581     // location.
10582     SDValue Chain = DAG.getEntryNode();
10583     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10584     SDValue Args[] = { Chain, Offset };
10585     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10586
10587     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10588     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10589     MFI->setAdjustsStack(true);
10590
10591     // And our return value (tls address) is in the standard call return value
10592     // location.
10593     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10594     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10595                               Chain.getValue(1));
10596   }
10597
10598   if (Subtarget->isTargetKnownWindowsMSVC() ||
10599       Subtarget->isTargetWindowsGNU()) {
10600     // Just use the implicit TLS architecture
10601     // Need to generate someting similar to:
10602     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10603     //                                  ; from TEB
10604     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10605     //   mov     rcx, qword [rdx+rcx*8]
10606     //   mov     eax, .tls$:tlsvar
10607     //   [rax+rcx] contains the address
10608     // Windows 64bit: gs:0x58
10609     // Windows 32bit: fs:__tls_array
10610
10611     SDLoc dl(GA);
10612     SDValue Chain = DAG.getEntryNode();
10613
10614     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10615     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10616     // use its literal value of 0x2C.
10617     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10618                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10619                                                              256)
10620                                         : Type::getInt32PtrTy(*DAG.getContext(),
10621                                                               257));
10622
10623     SDValue TlsArray =
10624         Subtarget->is64Bit()
10625             ? DAG.getIntPtrConstant(0x58)
10626             : (Subtarget->isTargetWindowsGNU()
10627                    ? DAG.getIntPtrConstant(0x2C)
10628                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10629
10630     SDValue ThreadPointer =
10631         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10632                     MachinePointerInfo(Ptr), false, false, false, 0);
10633
10634     // Load the _tls_index variable
10635     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10636     if (Subtarget->is64Bit())
10637       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10638                            IDX, MachinePointerInfo(), MVT::i32,
10639                            false, false, 0);
10640     else
10641       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10642                         false, false, false, 0);
10643
10644     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10645                                     getPointerTy());
10646     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10647
10648     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10649     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10650                       false, false, false, 0);
10651
10652     // Get the offset of start of .tls section
10653     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10654                                              GA->getValueType(0),
10655                                              GA->getOffset(), X86II::MO_SECREL);
10656     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10657
10658     // The address of the thread local variable is the add of the thread
10659     // pointer with the offset of the variable.
10660     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10661   }
10662
10663   llvm_unreachable("TLS not implemented for this target.");
10664 }
10665
10666 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10667 /// and take a 2 x i32 value to shift plus a shift amount.
10668 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10669   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10670   MVT VT = Op.getSimpleValueType();
10671   unsigned VTBits = VT.getSizeInBits();
10672   SDLoc dl(Op);
10673   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10674   SDValue ShOpLo = Op.getOperand(0);
10675   SDValue ShOpHi = Op.getOperand(1);
10676   SDValue ShAmt  = Op.getOperand(2);
10677   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10678   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10679   // during isel.
10680   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10681                                   DAG.getConstant(VTBits - 1, MVT::i8));
10682   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10683                                      DAG.getConstant(VTBits - 1, MVT::i8))
10684                        : DAG.getConstant(0, VT);
10685
10686   SDValue Tmp2, Tmp3;
10687   if (Op.getOpcode() == ISD::SHL_PARTS) {
10688     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10689     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10690   } else {
10691     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10692     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10693   }
10694
10695   // If the shift amount is larger or equal than the width of a part we can't
10696   // rely on the results of shld/shrd. Insert a test and select the appropriate
10697   // values for large shift amounts.
10698   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10699                                 DAG.getConstant(VTBits, MVT::i8));
10700   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10701                              AndNode, DAG.getConstant(0, MVT::i8));
10702
10703   SDValue Hi, Lo;
10704   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10705   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10706   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10707
10708   if (Op.getOpcode() == ISD::SHL_PARTS) {
10709     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10710     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10711   } else {
10712     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10713     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10714   }
10715
10716   SDValue Ops[2] = { Lo, Hi };
10717   return DAG.getMergeValues(Ops, dl);
10718 }
10719
10720 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10721                                            SelectionDAG &DAG) const {
10722   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10723
10724   if (SrcVT.isVector())
10725     return SDValue();
10726
10727   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10728          "Unknown SINT_TO_FP to lower!");
10729
10730   // These are really Legal; return the operand so the caller accepts it as
10731   // Legal.
10732   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10733     return Op;
10734   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10735       Subtarget->is64Bit()) {
10736     return Op;
10737   }
10738
10739   SDLoc dl(Op);
10740   unsigned Size = SrcVT.getSizeInBits()/8;
10741   MachineFunction &MF = DAG.getMachineFunction();
10742   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10743   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10744   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10745                                StackSlot,
10746                                MachinePointerInfo::getFixedStack(SSFI),
10747                                false, false, 0);
10748   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10749 }
10750
10751 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10752                                      SDValue StackSlot,
10753                                      SelectionDAG &DAG) const {
10754   // Build the FILD
10755   SDLoc DL(Op);
10756   SDVTList Tys;
10757   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10758   if (useSSE)
10759     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10760   else
10761     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10762
10763   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10764
10765   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10766   MachineMemOperand *MMO;
10767   if (FI) {
10768     int SSFI = FI->getIndex();
10769     MMO =
10770       DAG.getMachineFunction()
10771       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10772                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10773   } else {
10774     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10775     StackSlot = StackSlot.getOperand(1);
10776   }
10777   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10778   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10779                                            X86ISD::FILD, DL,
10780                                            Tys, Ops, SrcVT, MMO);
10781
10782   if (useSSE) {
10783     Chain = Result.getValue(1);
10784     SDValue InFlag = Result.getValue(2);
10785
10786     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10787     // shouldn't be necessary except that RFP cannot be live across
10788     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10789     MachineFunction &MF = DAG.getMachineFunction();
10790     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10791     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10792     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10793     Tys = DAG.getVTList(MVT::Other);
10794     SDValue Ops[] = {
10795       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10796     };
10797     MachineMemOperand *MMO =
10798       DAG.getMachineFunction()
10799       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10800                             MachineMemOperand::MOStore, SSFISize, SSFISize);
10801
10802     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10803                                     Ops, Op.getValueType(), MMO);
10804     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10805                          MachinePointerInfo::getFixedStack(SSFI),
10806                          false, false, false, 0);
10807   }
10808
10809   return Result;
10810 }
10811
10812 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10813 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10814                                                SelectionDAG &DAG) const {
10815   // This algorithm is not obvious. Here it is what we're trying to output:
10816   /*
10817      movq       %rax,  %xmm0
10818      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10819      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10820      #ifdef __SSE3__
10821        haddpd   %xmm0, %xmm0
10822      #else
10823        pshufd   $0x4e, %xmm0, %xmm1
10824        addpd    %xmm1, %xmm0
10825      #endif
10826   */
10827
10828   SDLoc dl(Op);
10829   LLVMContext *Context = DAG.getContext();
10830
10831   // Build some magic constants.
10832   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10833   Constant *C0 = ConstantDataVector::get(*Context, CV0);
10834   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10835
10836   SmallVector<Constant*,2> CV1;
10837   CV1.push_back(
10838     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10839                                       APInt(64, 0x4330000000000000ULL))));
10840   CV1.push_back(
10841     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10842                                       APInt(64, 0x4530000000000000ULL))));
10843   Constant *C1 = ConstantVector::get(CV1);
10844   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10845
10846   // Load the 64-bit value into an XMM register.
10847   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10848                             Op.getOperand(0));
10849   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10850                               MachinePointerInfo::getConstantPool(),
10851                               false, false, false, 16);
10852   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10853                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10854                               CLod0);
10855
10856   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10857                               MachinePointerInfo::getConstantPool(),
10858                               false, false, false, 16);
10859   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10860   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10861   SDValue Result;
10862
10863   if (Subtarget->hasSSE3()) {
10864     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10865     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10866   } else {
10867     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10868     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10869                                            S2F, 0x4E, DAG);
10870     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10871                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10872                          Sub);
10873   }
10874
10875   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10876                      DAG.getIntPtrConstant(0));
10877 }
10878
10879 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10880 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10881                                                SelectionDAG &DAG) const {
10882   SDLoc dl(Op);
10883   // FP constant to bias correct the final result.
10884   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10885                                    MVT::f64);
10886
10887   // Load the 32-bit value into an XMM register.
10888   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10889                              Op.getOperand(0));
10890
10891   // Zero out the upper parts of the register.
10892   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10893
10894   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10895                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10896                      DAG.getIntPtrConstant(0));
10897
10898   // Or the load with the bias.
10899   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10900                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10901                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10902                                                    MVT::v2f64, Load)),
10903                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10904                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10905                                                    MVT::v2f64, Bias)));
10906   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10907                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10908                    DAG.getIntPtrConstant(0));
10909
10910   // Subtract the bias.
10911   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10912
10913   // Handle final rounding.
10914   EVT DestVT = Op.getValueType();
10915
10916   if (DestVT.bitsLT(MVT::f64))
10917     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10918                        DAG.getIntPtrConstant(0));
10919   if (DestVT.bitsGT(MVT::f64))
10920     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10921
10922   // Handle final rounding.
10923   return Sub;
10924 }
10925
10926 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10927                                                SelectionDAG &DAG) const {
10928   SDValue N0 = Op.getOperand(0);
10929   MVT SVT = N0.getSimpleValueType();
10930   SDLoc dl(Op);
10931
10932   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10933           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10934          "Custom UINT_TO_FP is not supported!");
10935
10936   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10937   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10938                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10939 }
10940
10941 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10942                                            SelectionDAG &DAG) const {
10943   SDValue N0 = Op.getOperand(0);
10944   SDLoc dl(Op);
10945
10946   if (Op.getValueType().isVector())
10947     return lowerUINT_TO_FP_vec(Op, DAG);
10948
10949   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10950   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10951   // the optimization here.
10952   if (DAG.SignBitIsZero(N0))
10953     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10954
10955   MVT SrcVT = N0.getSimpleValueType();
10956   MVT DstVT = Op.getSimpleValueType();
10957   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10958     return LowerUINT_TO_FP_i64(Op, DAG);
10959   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10960     return LowerUINT_TO_FP_i32(Op, DAG);
10961   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10962     return SDValue();
10963
10964   // Make a 64-bit buffer, and use it to build an FILD.
10965   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10966   if (SrcVT == MVT::i32) {
10967     SDValue WordOff = DAG.getConstant(4, getPointerTy());
10968     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10969                                      getPointerTy(), StackSlot, WordOff);
10970     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10971                                   StackSlot, MachinePointerInfo(),
10972                                   false, false, 0);
10973     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10974                                   OffsetSlot, MachinePointerInfo(),
10975                                   false, false, 0);
10976     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10977     return Fild;
10978   }
10979
10980   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10981   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10982                                StackSlot, MachinePointerInfo(),
10983                                false, false, 0);
10984   // For i64 source, we need to add the appropriate power of 2 if the input
10985   // was negative.  This is the same as the optimization in
10986   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10987   // we must be careful to do the computation in x87 extended precision, not
10988   // in SSE. (The generic code can't know it's OK to do this, or how to.)
10989   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10990   MachineMemOperand *MMO =
10991     DAG.getMachineFunction()
10992     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10993                           MachineMemOperand::MOLoad, 8, 8);
10994
10995   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10996   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10997   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10998                                          MVT::i64, MMO);
10999
11000   APInt FF(32, 0x5F800000ULL);
11001
11002   // Check whether the sign bit is set.
11003   SDValue SignSet = DAG.getSetCC(dl,
11004                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11005                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11006                                  ISD::SETLT);
11007
11008   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11009   SDValue FudgePtr = DAG.getConstantPool(
11010                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11011                                          getPointerTy());
11012
11013   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11014   SDValue Zero = DAG.getIntPtrConstant(0);
11015   SDValue Four = DAG.getIntPtrConstant(4);
11016   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11017                                Zero, Four);
11018   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11019
11020   // Load the value out, extending it from f32 to f80.
11021   // FIXME: Avoid the extend by constructing the right constant pool?
11022   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11023                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11024                                  MVT::f32, false, false, 4);
11025   // Extend everything to 80 bits to force it to be done on x87.
11026   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11027   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11028 }
11029
11030 std::pair<SDValue,SDValue>
11031 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11032                                     bool IsSigned, bool IsReplace) const {
11033   SDLoc DL(Op);
11034
11035   EVT DstTy = Op.getValueType();
11036
11037   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11038     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11039     DstTy = MVT::i64;
11040   }
11041
11042   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11043          DstTy.getSimpleVT() >= MVT::i16 &&
11044          "Unknown FP_TO_INT to lower!");
11045
11046   // These are really Legal.
11047   if (DstTy == MVT::i32 &&
11048       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11049     return std::make_pair(SDValue(), SDValue());
11050   if (Subtarget->is64Bit() &&
11051       DstTy == MVT::i64 &&
11052       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11053     return std::make_pair(SDValue(), SDValue());
11054
11055   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11056   // stack slot, or into the FTOL runtime function.
11057   MachineFunction &MF = DAG.getMachineFunction();
11058   unsigned MemSize = DstTy.getSizeInBits()/8;
11059   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11060   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11061
11062   unsigned Opc;
11063   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11064     Opc = X86ISD::WIN_FTOL;
11065   else
11066     switch (DstTy.getSimpleVT().SimpleTy) {
11067     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11068     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11069     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11070     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11071     }
11072
11073   SDValue Chain = DAG.getEntryNode();
11074   SDValue Value = Op.getOperand(0);
11075   EVT TheVT = Op.getOperand(0).getValueType();
11076   // FIXME This causes a redundant load/store if the SSE-class value is already
11077   // in memory, such as if it is on the callstack.
11078   if (isScalarFPTypeInSSEReg(TheVT)) {
11079     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11080     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11081                          MachinePointerInfo::getFixedStack(SSFI),
11082                          false, false, 0);
11083     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11084     SDValue Ops[] = {
11085       Chain, StackSlot, DAG.getValueType(TheVT)
11086     };
11087
11088     MachineMemOperand *MMO =
11089       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11090                               MachineMemOperand::MOLoad, MemSize, MemSize);
11091     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11092     Chain = Value.getValue(1);
11093     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11094     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11095   }
11096
11097   MachineMemOperand *MMO =
11098     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11099                             MachineMemOperand::MOStore, MemSize, MemSize);
11100
11101   if (Opc != X86ISD::WIN_FTOL) {
11102     // Build the FP_TO_INT*_IN_MEM
11103     SDValue Ops[] = { Chain, Value, StackSlot };
11104     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11105                                            Ops, DstTy, MMO);
11106     return std::make_pair(FIST, StackSlot);
11107   } else {
11108     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11109       DAG.getVTList(MVT::Other, MVT::Glue),
11110       Chain, Value);
11111     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11112       MVT::i32, ftol.getValue(1));
11113     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11114       MVT::i32, eax.getValue(2));
11115     SDValue Ops[] = { eax, edx };
11116     SDValue pair = IsReplace
11117       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11118       : DAG.getMergeValues(Ops, DL);
11119     return std::make_pair(pair, SDValue());
11120   }
11121 }
11122
11123 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11124                               const X86Subtarget *Subtarget) {
11125   MVT VT = Op->getSimpleValueType(0);
11126   SDValue In = Op->getOperand(0);
11127   MVT InVT = In.getSimpleValueType();
11128   SDLoc dl(Op);
11129
11130   // Optimize vectors in AVX mode:
11131   //
11132   //   v8i16 -> v8i32
11133   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11134   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11135   //   Concat upper and lower parts.
11136   //
11137   //   v4i32 -> v4i64
11138   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11139   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11140   //   Concat upper and lower parts.
11141   //
11142
11143   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11144       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11145       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11146     return SDValue();
11147
11148   if (Subtarget->hasInt256())
11149     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11150
11151   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11152   SDValue Undef = DAG.getUNDEF(InVT);
11153   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11154   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11155   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11156
11157   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11158                              VT.getVectorNumElements()/2);
11159
11160   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11161   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11162
11163   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11164 }
11165
11166 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11167                                         SelectionDAG &DAG) {
11168   MVT VT = Op->getSimpleValueType(0);
11169   SDValue In = Op->getOperand(0);
11170   MVT InVT = In.getSimpleValueType();
11171   SDLoc DL(Op);
11172   unsigned int NumElts = VT.getVectorNumElements();
11173   if (NumElts != 8 && NumElts != 16)
11174     return SDValue();
11175
11176   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11177     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11178
11179   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11180   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11181   // Now we have only mask extension
11182   assert(InVT.getVectorElementType() == MVT::i1);
11183   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11184   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11185   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11186   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11187   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11188                            MachinePointerInfo::getConstantPool(),
11189                            false, false, false, Alignment);
11190
11191   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11192   if (VT.is512BitVector())
11193     return Brcst;
11194   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11195 }
11196
11197 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11198                                SelectionDAG &DAG) {
11199   if (Subtarget->hasFp256()) {
11200     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11201     if (Res.getNode())
11202       return Res;
11203   }
11204
11205   return SDValue();
11206 }
11207
11208 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11209                                 SelectionDAG &DAG) {
11210   SDLoc DL(Op);
11211   MVT VT = Op.getSimpleValueType();
11212   SDValue In = Op.getOperand(0);
11213   MVT SVT = In.getSimpleValueType();
11214
11215   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11216     return LowerZERO_EXTEND_AVX512(Op, DAG);
11217
11218   if (Subtarget->hasFp256()) {
11219     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11220     if (Res.getNode())
11221       return Res;
11222   }
11223
11224   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11225          VT.getVectorNumElements() != SVT.getVectorNumElements());
11226   return SDValue();
11227 }
11228
11229 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11230   SDLoc DL(Op);
11231   MVT VT = Op.getSimpleValueType();
11232   SDValue In = Op.getOperand(0);
11233   MVT InVT = In.getSimpleValueType();
11234
11235   if (VT == MVT::i1) {
11236     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11237            "Invalid scalar TRUNCATE operation");
11238     if (InVT == MVT::i32)
11239       return SDValue();
11240     if (InVT.getSizeInBits() == 64)
11241       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11242     else if (InVT.getSizeInBits() < 32)
11243       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11244     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11245   }
11246   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11247          "Invalid TRUNCATE operation");
11248
11249   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11250     if (VT.getVectorElementType().getSizeInBits() >=8)
11251       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11252
11253     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11254     unsigned NumElts = InVT.getVectorNumElements();
11255     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11256     if (InVT.getSizeInBits() < 512) {
11257       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11258       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11259       InVT = ExtVT;
11260     }
11261     
11262     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11263     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11264     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11265     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11266     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11267                            MachinePointerInfo::getConstantPool(),
11268                            false, false, false, Alignment);
11269     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11270     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11271     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11272   }
11273
11274   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11275     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11276     if (Subtarget->hasInt256()) {
11277       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11278       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11279       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11280                                 ShufMask);
11281       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11282                          DAG.getIntPtrConstant(0));
11283     }
11284
11285     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11286                                DAG.getIntPtrConstant(0));
11287     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11288                                DAG.getIntPtrConstant(2));
11289     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11290     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11291     static const int ShufMask[] = {0, 2, 4, 6};
11292     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11293   }
11294
11295   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11296     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11297     if (Subtarget->hasInt256()) {
11298       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11299
11300       SmallVector<SDValue,32> pshufbMask;
11301       for (unsigned i = 0; i < 2; ++i) {
11302         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11303         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11304         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11305         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11306         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11307         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11308         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11309         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11310         for (unsigned j = 0; j < 8; ++j)
11311           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11312       }
11313       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11314       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11315       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11316
11317       static const int ShufMask[] = {0,  2,  -1,  -1};
11318       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11319                                 &ShufMask[0]);
11320       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11321                        DAG.getIntPtrConstant(0));
11322       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11323     }
11324
11325     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11326                                DAG.getIntPtrConstant(0));
11327
11328     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11329                                DAG.getIntPtrConstant(4));
11330
11331     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11332     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11333
11334     // The PSHUFB mask:
11335     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11336                                    -1, -1, -1, -1, -1, -1, -1, -1};
11337
11338     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11339     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11340     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11341
11342     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11343     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11344
11345     // The MOVLHPS Mask:
11346     static const int ShufMask2[] = {0, 1, 4, 5};
11347     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11348     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11349   }
11350
11351   // Handle truncation of V256 to V128 using shuffles.
11352   if (!VT.is128BitVector() || !InVT.is256BitVector())
11353     return SDValue();
11354
11355   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11356
11357   unsigned NumElems = VT.getVectorNumElements();
11358   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11359
11360   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11361   // Prepare truncation shuffle mask
11362   for (unsigned i = 0; i != NumElems; ++i)
11363     MaskVec[i] = i * 2;
11364   SDValue V = DAG.getVectorShuffle(NVT, DL,
11365                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11366                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11367   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11368                      DAG.getIntPtrConstant(0));
11369 }
11370
11371 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11372                                            SelectionDAG &DAG) const {
11373   assert(!Op.getSimpleValueType().isVector());
11374
11375   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11376     /*IsSigned=*/ true, /*IsReplace=*/ false);
11377   SDValue FIST = Vals.first, StackSlot = Vals.second;
11378   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11379   if (!FIST.getNode()) return Op;
11380
11381   if (StackSlot.getNode())
11382     // Load the result.
11383     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11384                        FIST, StackSlot, MachinePointerInfo(),
11385                        false, false, false, 0);
11386
11387   // The node is the result.
11388   return FIST;
11389 }
11390
11391 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11392                                            SelectionDAG &DAG) const {
11393   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11394     /*IsSigned=*/ false, /*IsReplace=*/ false);
11395   SDValue FIST = Vals.first, StackSlot = Vals.second;
11396   assert(FIST.getNode() && "Unexpected failure");
11397
11398   if (StackSlot.getNode())
11399     // Load the result.
11400     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11401                        FIST, StackSlot, MachinePointerInfo(),
11402                        false, false, false, 0);
11403
11404   // The node is the result.
11405   return FIST;
11406 }
11407
11408 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11409   SDLoc DL(Op);
11410   MVT VT = Op.getSimpleValueType();
11411   SDValue In = Op.getOperand(0);
11412   MVT SVT = In.getSimpleValueType();
11413
11414   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11415
11416   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11417                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11418                                  In, DAG.getUNDEF(SVT)));
11419 }
11420
11421 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11422   LLVMContext *Context = DAG.getContext();
11423   SDLoc dl(Op);
11424   MVT VT = Op.getSimpleValueType();
11425   MVT EltVT = VT;
11426   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11427   if (VT.isVector()) {
11428     EltVT = VT.getVectorElementType();
11429     NumElts = VT.getVectorNumElements();
11430   }
11431   Constant *C;
11432   if (EltVT == MVT::f64)
11433     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11434                                           APInt(64, ~(1ULL << 63))));
11435   else
11436     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11437                                           APInt(32, ~(1U << 31))));
11438   C = ConstantVector::getSplat(NumElts, C);
11439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11440   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11441   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11442   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11443                              MachinePointerInfo::getConstantPool(),
11444                              false, false, false, Alignment);
11445   if (VT.isVector()) {
11446     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11447     return DAG.getNode(ISD::BITCAST, dl, VT,
11448                        DAG.getNode(ISD::AND, dl, ANDVT,
11449                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11450                                                Op.getOperand(0)),
11451                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11452   }
11453   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11454 }
11455
11456 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11457   LLVMContext *Context = DAG.getContext();
11458   SDLoc dl(Op);
11459   MVT VT = Op.getSimpleValueType();
11460   MVT EltVT = VT;
11461   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11462   if (VT.isVector()) {
11463     EltVT = VT.getVectorElementType();
11464     NumElts = VT.getVectorNumElements();
11465   }
11466   Constant *C;
11467   if (EltVT == MVT::f64)
11468     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11469                                           APInt(64, 1ULL << 63)));
11470   else
11471     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11472                                           APInt(32, 1U << 31)));
11473   C = ConstantVector::getSplat(NumElts, C);
11474   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11475   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11476   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11477   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11478                              MachinePointerInfo::getConstantPool(),
11479                              false, false, false, Alignment);
11480   if (VT.isVector()) {
11481     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11482     return DAG.getNode(ISD::BITCAST, dl, VT,
11483                        DAG.getNode(ISD::XOR, dl, XORVT,
11484                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11485                                                Op.getOperand(0)),
11486                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11487   }
11488
11489   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11490 }
11491
11492 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11493   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11494   LLVMContext *Context = DAG.getContext();
11495   SDValue Op0 = Op.getOperand(0);
11496   SDValue Op1 = Op.getOperand(1);
11497   SDLoc dl(Op);
11498   MVT VT = Op.getSimpleValueType();
11499   MVT SrcVT = Op1.getSimpleValueType();
11500
11501   // If second operand is smaller, extend it first.
11502   if (SrcVT.bitsLT(VT)) {
11503     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11504     SrcVT = VT;
11505   }
11506   // And if it is bigger, shrink it first.
11507   if (SrcVT.bitsGT(VT)) {
11508     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11509     SrcVT = VT;
11510   }
11511
11512   // At this point the operands and the result should have the same
11513   // type, and that won't be f80 since that is not custom lowered.
11514
11515   // First get the sign bit of second operand.
11516   SmallVector<Constant*,4> CV;
11517   if (SrcVT == MVT::f64) {
11518     const fltSemantics &Sem = APFloat::IEEEdouble;
11519     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11520     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11521   } else {
11522     const fltSemantics &Sem = APFloat::IEEEsingle;
11523     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11524     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11525     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11526     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11527   }
11528   Constant *C = ConstantVector::get(CV);
11529   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11530   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11531                               MachinePointerInfo::getConstantPool(),
11532                               false, false, false, 16);
11533   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11534
11535   // Shift sign bit right or left if the two operands have different types.
11536   if (SrcVT.bitsGT(VT)) {
11537     // Op0 is MVT::f32, Op1 is MVT::f64.
11538     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11539     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11540                           DAG.getConstant(32, MVT::i32));
11541     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11542     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11543                           DAG.getIntPtrConstant(0));
11544   }
11545
11546   // Clear first operand sign bit.
11547   CV.clear();
11548   if (VT == MVT::f64) {
11549     const fltSemantics &Sem = APFloat::IEEEdouble;
11550     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11551                                                    APInt(64, ~(1ULL << 63)))));
11552     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11553   } else {
11554     const fltSemantics &Sem = APFloat::IEEEsingle;
11555     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11556                                                    APInt(32, ~(1U << 31)))));
11557     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11558     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11559     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11560   }
11561   C = ConstantVector::get(CV);
11562   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11563   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11564                               MachinePointerInfo::getConstantPool(),
11565                               false, false, false, 16);
11566   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11567
11568   // Or the value with the sign bit.
11569   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11570 }
11571
11572 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11573   SDValue N0 = Op.getOperand(0);
11574   SDLoc dl(Op);
11575   MVT VT = Op.getSimpleValueType();
11576
11577   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11578   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11579                                   DAG.getConstant(1, VT));
11580   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11581 }
11582
11583 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11584 //
11585 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11586                                       SelectionDAG &DAG) {
11587   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11588
11589   if (!Subtarget->hasSSE41())
11590     return SDValue();
11591
11592   if (!Op->hasOneUse())
11593     return SDValue();
11594
11595   SDNode *N = Op.getNode();
11596   SDLoc DL(N);
11597
11598   SmallVector<SDValue, 8> Opnds;
11599   DenseMap<SDValue, unsigned> VecInMap;
11600   SmallVector<SDValue, 8> VecIns;
11601   EVT VT = MVT::Other;
11602
11603   // Recognize a special case where a vector is casted into wide integer to
11604   // test all 0s.
11605   Opnds.push_back(N->getOperand(0));
11606   Opnds.push_back(N->getOperand(1));
11607
11608   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11609     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11610     // BFS traverse all OR'd operands.
11611     if (I->getOpcode() == ISD::OR) {
11612       Opnds.push_back(I->getOperand(0));
11613       Opnds.push_back(I->getOperand(1));
11614       // Re-evaluate the number of nodes to be traversed.
11615       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11616       continue;
11617     }
11618
11619     // Quit if a non-EXTRACT_VECTOR_ELT
11620     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11621       return SDValue();
11622
11623     // Quit if without a constant index.
11624     SDValue Idx = I->getOperand(1);
11625     if (!isa<ConstantSDNode>(Idx))
11626       return SDValue();
11627
11628     SDValue ExtractedFromVec = I->getOperand(0);
11629     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11630     if (M == VecInMap.end()) {
11631       VT = ExtractedFromVec.getValueType();
11632       // Quit if not 128/256-bit vector.
11633       if (!VT.is128BitVector() && !VT.is256BitVector())
11634         return SDValue();
11635       // Quit if not the same type.
11636       if (VecInMap.begin() != VecInMap.end() &&
11637           VT != VecInMap.begin()->first.getValueType())
11638         return SDValue();
11639       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11640       VecIns.push_back(ExtractedFromVec);
11641     }
11642     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11643   }
11644
11645   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11646          "Not extracted from 128-/256-bit vector.");
11647
11648   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11649
11650   for (DenseMap<SDValue, unsigned>::const_iterator
11651         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11652     // Quit if not all elements are used.
11653     if (I->second != FullMask)
11654       return SDValue();
11655   }
11656
11657   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11658
11659   // Cast all vectors into TestVT for PTEST.
11660   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11661     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11662
11663   // If more than one full vectors are evaluated, OR them first before PTEST.
11664   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11665     // Each iteration will OR 2 nodes and append the result until there is only
11666     // 1 node left, i.e. the final OR'd value of all vectors.
11667     SDValue LHS = VecIns[Slot];
11668     SDValue RHS = VecIns[Slot + 1];
11669     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11670   }
11671
11672   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11673                      VecIns.back(), VecIns.back());
11674 }
11675
11676 /// \brief return true if \c Op has a use that doesn't just read flags.
11677 static bool hasNonFlagsUse(SDValue Op) {
11678   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11679        ++UI) {
11680     SDNode *User = *UI;
11681     unsigned UOpNo = UI.getOperandNo();
11682     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11683       // Look pass truncate.
11684       UOpNo = User->use_begin().getOperandNo();
11685       User = *User->use_begin();
11686     }
11687
11688     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11689         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11690       return true;
11691   }
11692   return false;
11693 }
11694
11695 /// Emit nodes that will be selected as "test Op0,Op0", or something
11696 /// equivalent.
11697 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11698                                     SelectionDAG &DAG) const {
11699   if (Op.getValueType() == MVT::i1)
11700     // KORTEST instruction should be selected
11701     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11702                        DAG.getConstant(0, Op.getValueType()));
11703
11704   // CF and OF aren't always set the way we want. Determine which
11705   // of these we need.
11706   bool NeedCF = false;
11707   bool NeedOF = false;
11708   switch (X86CC) {
11709   default: break;
11710   case X86::COND_A: case X86::COND_AE:
11711   case X86::COND_B: case X86::COND_BE:
11712     NeedCF = true;
11713     break;
11714   case X86::COND_G: case X86::COND_GE:
11715   case X86::COND_L: case X86::COND_LE:
11716   case X86::COND_O: case X86::COND_NO: {
11717     // Check if we really need to set the
11718     // Overflow flag. If NoSignedWrap is present
11719     // that is not actually needed.
11720     switch (Op->getOpcode()) {
11721     case ISD::ADD:
11722     case ISD::SUB:
11723     case ISD::MUL:
11724     case ISD::SHL: {
11725       const BinaryWithFlagsSDNode *BinNode =
11726           cast<BinaryWithFlagsSDNode>(Op.getNode());
11727       if (BinNode->hasNoSignedWrap())
11728         break;
11729     }
11730     default:
11731       NeedOF = true;
11732       break;
11733     }
11734     break;
11735   }
11736   }
11737   // See if we can use the EFLAGS value from the operand instead of
11738   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11739   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11740   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11741     // Emit a CMP with 0, which is the TEST pattern.
11742     //if (Op.getValueType() == MVT::i1)
11743     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11744     //                     DAG.getConstant(0, MVT::i1));
11745     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11746                        DAG.getConstant(0, Op.getValueType()));
11747   }
11748   unsigned Opcode = 0;
11749   unsigned NumOperands = 0;
11750
11751   // Truncate operations may prevent the merge of the SETCC instruction
11752   // and the arithmetic instruction before it. Attempt to truncate the operands
11753   // of the arithmetic instruction and use a reduced bit-width instruction.
11754   bool NeedTruncation = false;
11755   SDValue ArithOp = Op;
11756   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11757     SDValue Arith = Op->getOperand(0);
11758     // Both the trunc and the arithmetic op need to have one user each.
11759     if (Arith->hasOneUse())
11760       switch (Arith.getOpcode()) {
11761         default: break;
11762         case ISD::ADD:
11763         case ISD::SUB:
11764         case ISD::AND:
11765         case ISD::OR:
11766         case ISD::XOR: {
11767           NeedTruncation = true;
11768           ArithOp = Arith;
11769         }
11770       }
11771   }
11772
11773   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11774   // which may be the result of a CAST.  We use the variable 'Op', which is the
11775   // non-casted variable when we check for possible users.
11776   switch (ArithOp.getOpcode()) {
11777   case ISD::ADD:
11778     // Due to an isel shortcoming, be conservative if this add is likely to be
11779     // selected as part of a load-modify-store instruction. When the root node
11780     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11781     // uses of other nodes in the match, such as the ADD in this case. This
11782     // leads to the ADD being left around and reselected, with the result being
11783     // two adds in the output.  Alas, even if none our users are stores, that
11784     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11785     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11786     // climbing the DAG back to the root, and it doesn't seem to be worth the
11787     // effort.
11788     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11789          UE = Op.getNode()->use_end(); UI != UE; ++UI)
11790       if (UI->getOpcode() != ISD::CopyToReg &&
11791           UI->getOpcode() != ISD::SETCC &&
11792           UI->getOpcode() != ISD::STORE)
11793         goto default_case;
11794
11795     if (ConstantSDNode *C =
11796         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11797       // An add of one will be selected as an INC.
11798       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11799         Opcode = X86ISD::INC;
11800         NumOperands = 1;
11801         break;
11802       }
11803
11804       // An add of negative one (subtract of one) will be selected as a DEC.
11805       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11806         Opcode = X86ISD::DEC;
11807         NumOperands = 1;
11808         break;
11809       }
11810     }
11811
11812     // Otherwise use a regular EFLAGS-setting add.
11813     Opcode = X86ISD::ADD;
11814     NumOperands = 2;
11815     break;
11816   case ISD::SHL:
11817   case ISD::SRL:
11818     // If we have a constant logical shift that's only used in a comparison
11819     // against zero turn it into an equivalent AND. This allows turning it into
11820     // a TEST instruction later.
11821     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11822         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11823       EVT VT = Op.getValueType();
11824       unsigned BitWidth = VT.getSizeInBits();
11825       unsigned ShAmt = Op->getConstantOperandVal(1);
11826       if (ShAmt >= BitWidth) // Avoid undefined shifts.
11827         break;
11828       APInt Mask = ArithOp.getOpcode() == ISD::SRL
11829                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11830                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11831       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11832         break;
11833       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11834                                 DAG.getConstant(Mask, VT));
11835       DAG.ReplaceAllUsesWith(Op, New);
11836       Op = New;
11837     }
11838     break;
11839
11840   case ISD::AND:
11841     // If the primary and result isn't used, don't bother using X86ISD::AND,
11842     // because a TEST instruction will be better.
11843     if (!hasNonFlagsUse(Op))
11844       break;
11845     // FALL THROUGH
11846   case ISD::SUB:
11847   case ISD::OR:
11848   case ISD::XOR:
11849     // Due to the ISEL shortcoming noted above, be conservative if this op is
11850     // likely to be selected as part of a load-modify-store instruction.
11851     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11852            UE = Op.getNode()->use_end(); UI != UE; ++UI)
11853       if (UI->getOpcode() == ISD::STORE)
11854         goto default_case;
11855
11856     // Otherwise use a regular EFLAGS-setting instruction.
11857     switch (ArithOp.getOpcode()) {
11858     default: llvm_unreachable("unexpected operator!");
11859     case ISD::SUB: Opcode = X86ISD::SUB; break;
11860     case ISD::XOR: Opcode = X86ISD::XOR; break;
11861     case ISD::AND: Opcode = X86ISD::AND; break;
11862     case ISD::OR: {
11863       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11864         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11865         if (EFLAGS.getNode())
11866           return EFLAGS;
11867       }
11868       Opcode = X86ISD::OR;
11869       break;
11870     }
11871     }
11872
11873     NumOperands = 2;
11874     break;
11875   case X86ISD::ADD:
11876   case X86ISD::SUB:
11877   case X86ISD::INC:
11878   case X86ISD::DEC:
11879   case X86ISD::OR:
11880   case X86ISD::XOR:
11881   case X86ISD::AND:
11882     return SDValue(Op.getNode(), 1);
11883   default:
11884   default_case:
11885     break;
11886   }
11887
11888   // If we found that truncation is beneficial, perform the truncation and
11889   // update 'Op'.
11890   if (NeedTruncation) {
11891     EVT VT = Op.getValueType();
11892     SDValue WideVal = Op->getOperand(0);
11893     EVT WideVT = WideVal.getValueType();
11894     unsigned ConvertedOp = 0;
11895     // Use a target machine opcode to prevent further DAGCombine
11896     // optimizations that may separate the arithmetic operations
11897     // from the setcc node.
11898     switch (WideVal.getOpcode()) {
11899       default: break;
11900       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11901       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11902       case ISD::AND: ConvertedOp = X86ISD::AND; break;
11903       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
11904       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11905     }
11906
11907     if (ConvertedOp) {
11908       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11909       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11910         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11911         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11912         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11913       }
11914     }
11915   }
11916
11917   if (Opcode == 0)
11918     // Emit a CMP with 0, which is the TEST pattern.
11919     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11920                        DAG.getConstant(0, Op.getValueType()));
11921
11922   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11923   SmallVector<SDValue, 4> Ops;
11924   for (unsigned i = 0; i != NumOperands; ++i)
11925     Ops.push_back(Op.getOperand(i));
11926
11927   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11928   DAG.ReplaceAllUsesWith(Op, New);
11929   return SDValue(New.getNode(), 1);
11930 }
11931
11932 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11933 /// equivalent.
11934 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11935                                    SDLoc dl, SelectionDAG &DAG) const {
11936   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11937     if (C->getAPIntValue() == 0)
11938       return EmitTest(Op0, X86CC, dl, DAG);
11939
11940      if (Op0.getValueType() == MVT::i1)
11941        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11942   }
11943  
11944   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11945        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11946     // Do the comparison at i32 if it's smaller, besides the Atom case. 
11947     // This avoids subregister aliasing issues. Keep the smaller reference 
11948     // if we're optimizing for size, however, as that'll allow better folding 
11949     // of memory operations.
11950     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11951         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11952              AttributeSet::FunctionIndex, Attribute::MinSize) &&
11953         !Subtarget->isAtom()) {
11954       unsigned ExtendOp =
11955           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11956       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11957       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11958     }
11959     // Use SUB instead of CMP to enable CSE between SUB and CMP.
11960     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11961     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11962                               Op0, Op1);
11963     return SDValue(Sub.getNode(), 1);
11964   }
11965   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11966 }
11967
11968 /// Convert a comparison if required by the subtarget.
11969 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11970                                                  SelectionDAG &DAG) const {
11971   // If the subtarget does not support the FUCOMI instruction, floating-point
11972   // comparisons have to be converted.
11973   if (Subtarget->hasCMov() ||
11974       Cmp.getOpcode() != X86ISD::CMP ||
11975       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11976       !Cmp.getOperand(1).getValueType().isFloatingPoint())
11977     return Cmp;
11978
11979   // The instruction selector will select an FUCOM instruction instead of
11980   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11981   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11982   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11983   SDLoc dl(Cmp);
11984   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11985   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11986   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11987                             DAG.getConstant(8, MVT::i8));
11988   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11989   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11990 }
11991
11992 static bool isAllOnes(SDValue V) {
11993   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11994   return C && C->isAllOnesValue();
11995 }
11996
11997 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11998 /// if it's possible.
11999 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12000                                      SDLoc dl, SelectionDAG &DAG) const {
12001   SDValue Op0 = And.getOperand(0);
12002   SDValue Op1 = And.getOperand(1);
12003   if (Op0.getOpcode() == ISD::TRUNCATE)
12004     Op0 = Op0.getOperand(0);
12005   if (Op1.getOpcode() == ISD::TRUNCATE)
12006     Op1 = Op1.getOperand(0);
12007
12008   SDValue LHS, RHS;
12009   if (Op1.getOpcode() == ISD::SHL)
12010     std::swap(Op0, Op1);
12011   if (Op0.getOpcode() == ISD::SHL) {
12012     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12013       if (And00C->getZExtValue() == 1) {
12014         // If we looked past a truncate, check that it's only truncating away
12015         // known zeros.
12016         unsigned BitWidth = Op0.getValueSizeInBits();
12017         unsigned AndBitWidth = And.getValueSizeInBits();
12018         if (BitWidth > AndBitWidth) {
12019           APInt Zeros, Ones;
12020           DAG.computeKnownBits(Op0, Zeros, Ones);
12021           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12022             return SDValue();
12023         }
12024         LHS = Op1;
12025         RHS = Op0.getOperand(1);
12026       }
12027   } else if (Op1.getOpcode() == ISD::Constant) {
12028     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12029     uint64_t AndRHSVal = AndRHS->getZExtValue();
12030     SDValue AndLHS = Op0;
12031
12032     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12033       LHS = AndLHS.getOperand(0);
12034       RHS = AndLHS.getOperand(1);
12035     }
12036
12037     // Use BT if the immediate can't be encoded in a TEST instruction.
12038     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12039       LHS = AndLHS;
12040       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12041     }
12042   }
12043
12044   if (LHS.getNode()) {
12045     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12046     // instruction.  Since the shift amount is in-range-or-undefined, we know
12047     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12048     // the encoding for the i16 version is larger than the i32 version.
12049     // Also promote i16 to i32 for performance / code size reason.
12050     if (LHS.getValueType() == MVT::i8 ||
12051         LHS.getValueType() == MVT::i16)
12052       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12053
12054     // If the operand types disagree, extend the shift amount to match.  Since
12055     // BT ignores high bits (like shifts) we can use anyextend.
12056     if (LHS.getValueType() != RHS.getValueType())
12057       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12058
12059     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12060     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12061     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12062                        DAG.getConstant(Cond, MVT::i8), BT);
12063   }
12064
12065   return SDValue();
12066 }
12067
12068 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12069 /// mask CMPs.
12070 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12071                               SDValue &Op1) {
12072   unsigned SSECC;
12073   bool Swap = false;
12074
12075   // SSE Condition code mapping:
12076   //  0 - EQ
12077   //  1 - LT
12078   //  2 - LE
12079   //  3 - UNORD
12080   //  4 - NEQ
12081   //  5 - NLT
12082   //  6 - NLE
12083   //  7 - ORD
12084   switch (SetCCOpcode) {
12085   default: llvm_unreachable("Unexpected SETCC condition");
12086   case ISD::SETOEQ:
12087   case ISD::SETEQ:  SSECC = 0; break;
12088   case ISD::SETOGT:
12089   case ISD::SETGT:  Swap = true; // Fallthrough
12090   case ISD::SETLT:
12091   case ISD::SETOLT: SSECC = 1; break;
12092   case ISD::SETOGE:
12093   case ISD::SETGE:  Swap = true; // Fallthrough
12094   case ISD::SETLE:
12095   case ISD::SETOLE: SSECC = 2; break;
12096   case ISD::SETUO:  SSECC = 3; break;
12097   case ISD::SETUNE:
12098   case ISD::SETNE:  SSECC = 4; break;
12099   case ISD::SETULE: Swap = true; // Fallthrough
12100   case ISD::SETUGE: SSECC = 5; break;
12101   case ISD::SETULT: Swap = true; // Fallthrough
12102   case ISD::SETUGT: SSECC = 6; break;
12103   case ISD::SETO:   SSECC = 7; break;
12104   case ISD::SETUEQ:
12105   case ISD::SETONE: SSECC = 8; break;
12106   }
12107   if (Swap)
12108     std::swap(Op0, Op1);
12109
12110   return SSECC;
12111 }
12112
12113 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12114 // ones, and then concatenate the result back.
12115 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12116   MVT VT = Op.getSimpleValueType();
12117
12118   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12119          "Unsupported value type for operation");
12120
12121   unsigned NumElems = VT.getVectorNumElements();
12122   SDLoc dl(Op);
12123   SDValue CC = Op.getOperand(2);
12124
12125   // Extract the LHS vectors
12126   SDValue LHS = Op.getOperand(0);
12127   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12128   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12129
12130   // Extract the RHS vectors
12131   SDValue RHS = Op.getOperand(1);
12132   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12133   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12134
12135   // Issue the operation on the smaller types and concatenate the result back
12136   MVT EltVT = VT.getVectorElementType();
12137   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12138   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12139                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12140                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12141 }
12142
12143 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12144                                      const X86Subtarget *Subtarget) {
12145   SDValue Op0 = Op.getOperand(0);
12146   SDValue Op1 = Op.getOperand(1);
12147   SDValue CC = Op.getOperand(2);
12148   MVT VT = Op.getSimpleValueType();
12149   SDLoc dl(Op);
12150
12151   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12152          Op.getValueType().getScalarType() == MVT::i1 &&
12153          "Cannot set masked compare for this operation");
12154
12155   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12156   unsigned  Opc = 0;
12157   bool Unsigned = false;
12158   bool Swap = false;
12159   unsigned SSECC;
12160   switch (SetCCOpcode) {
12161   default: llvm_unreachable("Unexpected SETCC condition");
12162   case ISD::SETNE:  SSECC = 4; break;
12163   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12164   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12165   case ISD::SETLT:  Swap = true; //fall-through
12166   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12167   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12168   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12169   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12170   case ISD::SETULE: Unsigned = true; //fall-through
12171   case ISD::SETLE:  SSECC = 2; break;
12172   }
12173
12174   if (Swap)
12175     std::swap(Op0, Op1);
12176   if (Opc)
12177     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12178   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12179   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12180                      DAG.getConstant(SSECC, MVT::i8));
12181 }
12182
12183 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12184 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12185 /// return an empty value.
12186 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12187 {
12188   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12189   if (!BV)
12190     return SDValue();
12191
12192   MVT VT = Op1.getSimpleValueType();
12193   MVT EVT = VT.getVectorElementType();
12194   unsigned n = VT.getVectorNumElements();
12195   SmallVector<SDValue, 8> ULTOp1;
12196
12197   for (unsigned i = 0; i < n; ++i) {
12198     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12199     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12200       return SDValue();
12201
12202     // Avoid underflow.
12203     APInt Val = Elt->getAPIntValue();
12204     if (Val == 0)
12205       return SDValue();
12206
12207     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12208   }
12209
12210   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12211 }
12212
12213 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12214                            SelectionDAG &DAG) {
12215   SDValue Op0 = Op.getOperand(0);
12216   SDValue Op1 = Op.getOperand(1);
12217   SDValue CC = Op.getOperand(2);
12218   MVT VT = Op.getSimpleValueType();
12219   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12220   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12221   SDLoc dl(Op);
12222
12223   if (isFP) {
12224 #ifndef NDEBUG
12225     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12226     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12227 #endif
12228
12229     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12230     unsigned Opc = X86ISD::CMPP;
12231     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12232       assert(VT.getVectorNumElements() <= 16);
12233       Opc = X86ISD::CMPM;
12234     }
12235     // In the two special cases we can't handle, emit two comparisons.
12236     if (SSECC == 8) {
12237       unsigned CC0, CC1;
12238       unsigned CombineOpc;
12239       if (SetCCOpcode == ISD::SETUEQ) {
12240         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12241       } else {
12242         assert(SetCCOpcode == ISD::SETONE);
12243         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12244       }
12245
12246       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12247                                  DAG.getConstant(CC0, MVT::i8));
12248       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12249                                  DAG.getConstant(CC1, MVT::i8));
12250       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12251     }
12252     // Handle all other FP comparisons here.
12253     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12254                        DAG.getConstant(SSECC, MVT::i8));
12255   }
12256
12257   // Break 256-bit integer vector compare into smaller ones.
12258   if (VT.is256BitVector() && !Subtarget->hasInt256())
12259     return Lower256IntVSETCC(Op, DAG);
12260
12261   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12262   EVT OpVT = Op1.getValueType();
12263   if (Subtarget->hasAVX512()) {
12264     if (Op1.getValueType().is512BitVector() ||
12265         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12266       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12267
12268     // In AVX-512 architecture setcc returns mask with i1 elements,
12269     // But there is no compare instruction for i8 and i16 elements.
12270     // We are not talking about 512-bit operands in this case, these
12271     // types are illegal.
12272     if (MaskResult &&
12273         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12274          OpVT.getVectorElementType().getSizeInBits() >= 8))
12275       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12276                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12277   }
12278
12279   // We are handling one of the integer comparisons here.  Since SSE only has
12280   // GT and EQ comparisons for integer, swapping operands and multiple
12281   // operations may be required for some comparisons.
12282   unsigned Opc;
12283   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12284   bool Subus = false;
12285
12286   switch (SetCCOpcode) {
12287   default: llvm_unreachable("Unexpected SETCC condition");
12288   case ISD::SETNE:  Invert = true;
12289   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12290   case ISD::SETLT:  Swap = true;
12291   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12292   case ISD::SETGE:  Swap = true;
12293   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12294                     Invert = true; break;
12295   case ISD::SETULT: Swap = true;
12296   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12297                     FlipSigns = true; break;
12298   case ISD::SETUGE: Swap = true;
12299   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12300                     FlipSigns = true; Invert = true; break;
12301   }
12302
12303   // Special case: Use min/max operations for SETULE/SETUGE
12304   MVT VET = VT.getVectorElementType();
12305   bool hasMinMax =
12306        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12307     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12308
12309   if (hasMinMax) {
12310     switch (SetCCOpcode) {
12311     default: break;
12312     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12313     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12314     }
12315
12316     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12317   }
12318
12319   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12320   if (!MinMax && hasSubus) {
12321     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12322     // Op0 u<= Op1:
12323     //   t = psubus Op0, Op1
12324     //   pcmpeq t, <0..0>
12325     switch (SetCCOpcode) {
12326     default: break;
12327     case ISD::SETULT: {
12328       // If the comparison is against a constant we can turn this into a
12329       // setule.  With psubus, setule does not require a swap.  This is
12330       // beneficial because the constant in the register is no longer
12331       // destructed as the destination so it can be hoisted out of a loop.
12332       // Only do this pre-AVX since vpcmp* is no longer destructive.
12333       if (Subtarget->hasAVX())
12334         break;
12335       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12336       if (ULEOp1.getNode()) {
12337         Op1 = ULEOp1;
12338         Subus = true; Invert = false; Swap = false;
12339       }
12340       break;
12341     }
12342     // Psubus is better than flip-sign because it requires no inversion.
12343     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12344     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12345     }
12346
12347     if (Subus) {
12348       Opc = X86ISD::SUBUS;
12349       FlipSigns = false;
12350     }
12351   }
12352
12353   if (Swap)
12354     std::swap(Op0, Op1);
12355
12356   // Check that the operation in question is available (most are plain SSE2,
12357   // but PCMPGTQ and PCMPEQQ have different requirements).
12358   if (VT == MVT::v2i64) {
12359     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12360       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12361
12362       // First cast everything to the right type.
12363       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12364       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12365
12366       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12367       // bits of the inputs before performing those operations. The lower
12368       // compare is always unsigned.
12369       SDValue SB;
12370       if (FlipSigns) {
12371         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12372       } else {
12373         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12374         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12375         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12376                          Sign, Zero, Sign, Zero);
12377       }
12378       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12379       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12380
12381       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12382       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12383       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12384
12385       // Create masks for only the low parts/high parts of the 64 bit integers.
12386       static const int MaskHi[] = { 1, 1, 3, 3 };
12387       static const int MaskLo[] = { 0, 0, 2, 2 };
12388       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12389       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12390       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12391
12392       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12393       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12394
12395       if (Invert)
12396         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12397
12398       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12399     }
12400
12401     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12402       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12403       // pcmpeqd + pshufd + pand.
12404       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12405
12406       // First cast everything to the right type.
12407       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12408       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12409
12410       // Do the compare.
12411       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12412
12413       // Make sure the lower and upper halves are both all-ones.
12414       static const int Mask[] = { 1, 0, 3, 2 };
12415       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12416       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12417
12418       if (Invert)
12419         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12420
12421       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12422     }
12423   }
12424
12425   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12426   // bits of the inputs before performing those operations.
12427   if (FlipSigns) {
12428     EVT EltVT = VT.getVectorElementType();
12429     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12430     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12431     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12432   }
12433
12434   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12435
12436   // If the logical-not of the result is required, perform that now.
12437   if (Invert)
12438     Result = DAG.getNOT(dl, Result, VT);
12439
12440   if (MinMax)
12441     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12442
12443   if (Subus)
12444     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12445                          getZeroVector(VT, Subtarget, DAG, dl));
12446
12447   return Result;
12448 }
12449
12450 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12451
12452   MVT VT = Op.getSimpleValueType();
12453
12454   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12455
12456   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12457          && "SetCC type must be 8-bit or 1-bit integer");
12458   SDValue Op0 = Op.getOperand(0);
12459   SDValue Op1 = Op.getOperand(1);
12460   SDLoc dl(Op);
12461   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12462
12463   // Optimize to BT if possible.
12464   // Lower (X & (1 << N)) == 0 to BT(X, N).
12465   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12466   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12467   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12468       Op1.getOpcode() == ISD::Constant &&
12469       cast<ConstantSDNode>(Op1)->isNullValue() &&
12470       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12471     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12472     if (NewSetCC.getNode())
12473       return NewSetCC;
12474   }
12475
12476   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12477   // these.
12478   if (Op1.getOpcode() == ISD::Constant &&
12479       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12480        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12481       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12482
12483     // If the input is a setcc, then reuse the input setcc or use a new one with
12484     // the inverted condition.
12485     if (Op0.getOpcode() == X86ISD::SETCC) {
12486       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12487       bool Invert = (CC == ISD::SETNE) ^
12488         cast<ConstantSDNode>(Op1)->isNullValue();
12489       if (!Invert)
12490         return Op0;
12491
12492       CCode = X86::GetOppositeBranchCondition(CCode);
12493       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12494                                   DAG.getConstant(CCode, MVT::i8),
12495                                   Op0.getOperand(1));
12496       if (VT == MVT::i1)
12497         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12498       return SetCC;
12499     }
12500   }
12501   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12502       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12503       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12504
12505     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12506     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12507   }
12508
12509   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12510   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12511   if (X86CC == X86::COND_INVALID)
12512     return SDValue();
12513
12514   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12515   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12516   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12517                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12518   if (VT == MVT::i1)
12519     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12520   return SetCC;
12521 }
12522
12523 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12524 static bool isX86LogicalCmp(SDValue Op) {
12525   unsigned Opc = Op.getNode()->getOpcode();
12526   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12527       Opc == X86ISD::SAHF)
12528     return true;
12529   if (Op.getResNo() == 1 &&
12530       (Opc == X86ISD::ADD ||
12531        Opc == X86ISD::SUB ||
12532        Opc == X86ISD::ADC ||
12533        Opc == X86ISD::SBB ||
12534        Opc == X86ISD::SMUL ||
12535        Opc == X86ISD::UMUL ||
12536        Opc == X86ISD::INC ||
12537        Opc == X86ISD::DEC ||
12538        Opc == X86ISD::OR ||
12539        Opc == X86ISD::XOR ||
12540        Opc == X86ISD::AND))
12541     return true;
12542
12543   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12544     return true;
12545
12546   return false;
12547 }
12548
12549 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12550   if (V.getOpcode() != ISD::TRUNCATE)
12551     return false;
12552
12553   SDValue VOp0 = V.getOperand(0);
12554   unsigned InBits = VOp0.getValueSizeInBits();
12555   unsigned Bits = V.getValueSizeInBits();
12556   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12557 }
12558
12559 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12560   bool addTest = true;
12561   SDValue Cond  = Op.getOperand(0);
12562   SDValue Op1 = Op.getOperand(1);
12563   SDValue Op2 = Op.getOperand(2);
12564   SDLoc DL(Op);
12565   EVT VT = Op1.getValueType();
12566   SDValue CC;
12567
12568   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12569   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12570   // sequence later on.
12571   if (Cond.getOpcode() == ISD::SETCC &&
12572       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12573        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12574       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12575     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12576     int SSECC = translateX86FSETCC(
12577         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12578
12579     if (SSECC != 8) {
12580       if (Subtarget->hasAVX512()) {
12581         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12582                                   DAG.getConstant(SSECC, MVT::i8));
12583         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12584       }
12585       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12586                                 DAG.getConstant(SSECC, MVT::i8));
12587       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12588       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12589       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12590     }
12591   }
12592
12593   if (Cond.getOpcode() == ISD::SETCC) {
12594     SDValue NewCond = LowerSETCC(Cond, DAG);
12595     if (NewCond.getNode())
12596       Cond = NewCond;
12597   }
12598
12599   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12600   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12601   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12602   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12603   if (Cond.getOpcode() == X86ISD::SETCC &&
12604       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12605       isZero(Cond.getOperand(1).getOperand(1))) {
12606     SDValue Cmp = Cond.getOperand(1);
12607
12608     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12609
12610     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12611         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12612       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12613
12614       SDValue CmpOp0 = Cmp.getOperand(0);
12615       // Apply further optimizations for special cases
12616       // (select (x != 0), -1, 0) -> neg & sbb
12617       // (select (x == 0), 0, -1) -> neg & sbb
12618       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12619         if (YC->isNullValue() &&
12620             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12621           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12622           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12623                                     DAG.getConstant(0, CmpOp0.getValueType()),
12624                                     CmpOp0);
12625           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12626                                     DAG.getConstant(X86::COND_B, MVT::i8),
12627                                     SDValue(Neg.getNode(), 1));
12628           return Res;
12629         }
12630
12631       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12632                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12633       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12634
12635       SDValue Res =   // Res = 0 or -1.
12636         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12637                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12638
12639       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12640         Res = DAG.getNOT(DL, Res, Res.getValueType());
12641
12642       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12643       if (!N2C || !N2C->isNullValue())
12644         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12645       return Res;
12646     }
12647   }
12648
12649   // Look past (and (setcc_carry (cmp ...)), 1).
12650   if (Cond.getOpcode() == ISD::AND &&
12651       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12652     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12653     if (C && C->getAPIntValue() == 1)
12654       Cond = Cond.getOperand(0);
12655   }
12656
12657   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12658   // setting operand in place of the X86ISD::SETCC.
12659   unsigned CondOpcode = Cond.getOpcode();
12660   if (CondOpcode == X86ISD::SETCC ||
12661       CondOpcode == X86ISD::SETCC_CARRY) {
12662     CC = Cond.getOperand(0);
12663
12664     SDValue Cmp = Cond.getOperand(1);
12665     unsigned Opc = Cmp.getOpcode();
12666     MVT VT = Op.getSimpleValueType();
12667
12668     bool IllegalFPCMov = false;
12669     if (VT.isFloatingPoint() && !VT.isVector() &&
12670         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12671       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12672
12673     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12674         Opc == X86ISD::BT) { // FIXME
12675       Cond = Cmp;
12676       addTest = false;
12677     }
12678   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12679              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12680              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12681               Cond.getOperand(0).getValueType() != MVT::i8)) {
12682     SDValue LHS = Cond.getOperand(0);
12683     SDValue RHS = Cond.getOperand(1);
12684     unsigned X86Opcode;
12685     unsigned X86Cond;
12686     SDVTList VTs;
12687     switch (CondOpcode) {
12688     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12689     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12690     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12691     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12692     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12693     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12694     default: llvm_unreachable("unexpected overflowing operator");
12695     }
12696     if (CondOpcode == ISD::UMULO)
12697       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12698                           MVT::i32);
12699     else
12700       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12701
12702     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12703
12704     if (CondOpcode == ISD::UMULO)
12705       Cond = X86Op.getValue(2);
12706     else
12707       Cond = X86Op.getValue(1);
12708
12709     CC = DAG.getConstant(X86Cond, MVT::i8);
12710     addTest = false;
12711   }
12712
12713   if (addTest) {
12714     // Look pass the truncate if the high bits are known zero.
12715     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12716         Cond = Cond.getOperand(0);
12717
12718     // We know the result of AND is compared against zero. Try to match
12719     // it to BT.
12720     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12721       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12722       if (NewSetCC.getNode()) {
12723         CC = NewSetCC.getOperand(0);
12724         Cond = NewSetCC.getOperand(1);
12725         addTest = false;
12726       }
12727     }
12728   }
12729
12730   if (addTest) {
12731     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12732     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12733   }
12734
12735   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12736   // a <  b ?  0 : -1 -> RES = setcc_carry
12737   // a >= b ? -1 :  0 -> RES = setcc_carry
12738   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12739   if (Cond.getOpcode() == X86ISD::SUB) {
12740     Cond = ConvertCmpIfNecessary(Cond, DAG);
12741     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12742
12743     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12744         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12745       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12746                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12747       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12748         return DAG.getNOT(DL, Res, Res.getValueType());
12749       return Res;
12750     }
12751   }
12752
12753   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12754   // widen the cmov and push the truncate through. This avoids introducing a new
12755   // branch during isel and doesn't add any extensions.
12756   if (Op.getValueType() == MVT::i8 &&
12757       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12758     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12759     if (T1.getValueType() == T2.getValueType() &&
12760         // Blacklist CopyFromReg to avoid partial register stalls.
12761         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12762       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12763       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12764       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12765     }
12766   }
12767
12768   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12769   // condition is true.
12770   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12771   SDValue Ops[] = { Op2, Op1, CC, Cond };
12772   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12773 }
12774
12775 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12776   MVT VT = Op->getSimpleValueType(0);
12777   SDValue In = Op->getOperand(0);
12778   MVT InVT = In.getSimpleValueType();
12779   SDLoc dl(Op);
12780
12781   unsigned int NumElts = VT.getVectorNumElements();
12782   if (NumElts != 8 && NumElts != 16)
12783     return SDValue();
12784
12785   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12786     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12787
12788   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12789   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12790
12791   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12792   Constant *C = ConstantInt::get(*DAG.getContext(),
12793     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12794
12795   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12796   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12797   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12798                           MachinePointerInfo::getConstantPool(),
12799                           false, false, false, Alignment);
12800   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12801   if (VT.is512BitVector())
12802     return Brcst;
12803   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12804 }
12805
12806 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12807                                 SelectionDAG &DAG) {
12808   MVT VT = Op->getSimpleValueType(0);
12809   SDValue In = Op->getOperand(0);
12810   MVT InVT = In.getSimpleValueType();
12811   SDLoc dl(Op);
12812
12813   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12814     return LowerSIGN_EXTEND_AVX512(Op, DAG);
12815
12816   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12817       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12818       (VT != MVT::v16i16 || InVT != MVT::v16i8))
12819     return SDValue();
12820
12821   if (Subtarget->hasInt256())
12822     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12823
12824   // Optimize vectors in AVX mode
12825   // Sign extend  v8i16 to v8i32 and
12826   //              v4i32 to v4i64
12827   //
12828   // Divide input vector into two parts
12829   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12830   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12831   // concat the vectors to original VT
12832
12833   unsigned NumElems = InVT.getVectorNumElements();
12834   SDValue Undef = DAG.getUNDEF(InVT);
12835
12836   SmallVector<int,8> ShufMask1(NumElems, -1);
12837   for (unsigned i = 0; i != NumElems/2; ++i)
12838     ShufMask1[i] = i;
12839
12840   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12841
12842   SmallVector<int,8> ShufMask2(NumElems, -1);
12843   for (unsigned i = 0; i != NumElems/2; ++i)
12844     ShufMask2[i] = i + NumElems/2;
12845
12846   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12847
12848   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12849                                 VT.getVectorNumElements()/2);
12850
12851   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12852   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12853
12854   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12855 }
12856
12857 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
12858 // may emit an illegal shuffle but the expansion is still better than scalar
12859 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
12860 // we'll emit a shuffle and a arithmetic shift.
12861 // TODO: It is possible to support ZExt by zeroing the undef values during
12862 // the shuffle phase or after the shuffle.
12863 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
12864                                  SelectionDAG &DAG) {
12865   MVT RegVT = Op.getSimpleValueType();
12866   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
12867   assert(RegVT.isInteger() &&
12868          "We only custom lower integer vector sext loads.");
12869
12870   // Nothing useful we can do without SSE2 shuffles.
12871   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
12872
12873   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
12874   SDLoc dl(Ld);
12875   EVT MemVT = Ld->getMemoryVT();
12876   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12877   unsigned RegSz = RegVT.getSizeInBits();
12878
12879   ISD::LoadExtType Ext = Ld->getExtensionType();
12880
12881   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
12882          && "Only anyext and sext are currently implemented.");
12883   assert(MemVT != RegVT && "Cannot extend to the same type");
12884   assert(MemVT.isVector() && "Must load a vector from memory");
12885
12886   unsigned NumElems = RegVT.getVectorNumElements();
12887   unsigned MemSz = MemVT.getSizeInBits();
12888   assert(RegSz > MemSz && "Register size must be greater than the mem size");
12889
12890   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
12891     // The only way in which we have a legal 256-bit vector result but not the
12892     // integer 256-bit operations needed to directly lower a sextload is if we
12893     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
12894     // a 128-bit vector and a normal sign_extend to 256-bits that should get
12895     // correctly legalized. We do this late to allow the canonical form of
12896     // sextload to persist throughout the rest of the DAG combiner -- it wants
12897     // to fold together any extensions it can, and so will fuse a sign_extend
12898     // of an sextload into an sextload targeting a wider value.
12899     SDValue Load;
12900     if (MemSz == 128) {
12901       // Just switch this to a normal load.
12902       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
12903                                        "it must be a legal 128-bit vector "
12904                                        "type!");
12905       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
12906                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
12907                   Ld->isInvariant(), Ld->getAlignment());
12908     } else {
12909       assert(MemSz < 128 &&
12910              "Can't extend a type wider than 128 bits to a 256 bit vector!");
12911       // Do an sext load to a 128-bit vector type. We want to use the same
12912       // number of elements, but elements half as wide. This will end up being
12913       // recursively lowered by this routine, but will succeed as we definitely
12914       // have all the necessary features if we're using AVX1.
12915       EVT HalfEltVT =
12916           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
12917       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
12918       Load =
12919           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
12920                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
12921                          Ld->isNonTemporal(), Ld->getAlignment());
12922     }
12923
12924     // Replace chain users with the new chain.
12925     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
12926     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
12927
12928     // Finally, do a normal sign-extend to the desired register.
12929     return DAG.getSExtOrTrunc(Load, dl, RegVT);
12930   }
12931
12932   // All sizes must be a power of two.
12933   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
12934          "Non-power-of-two elements are not custom lowered!");
12935
12936   // Attempt to load the original value using scalar loads.
12937   // Find the largest scalar type that divides the total loaded size.
12938   MVT SclrLoadTy = MVT::i8;
12939   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
12940        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
12941     MVT Tp = (MVT::SimpleValueType)tp;
12942     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
12943       SclrLoadTy = Tp;
12944     }
12945   }
12946
12947   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
12948   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
12949       (64 <= MemSz))
12950     SclrLoadTy = MVT::f64;
12951
12952   // Calculate the number of scalar loads that we need to perform
12953   // in order to load our vector from memory.
12954   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
12955
12956   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
12957          "Can only lower sext loads with a single scalar load!");
12958
12959   unsigned loadRegZize = RegSz;
12960   if (Ext == ISD::SEXTLOAD && RegSz == 256)
12961     loadRegZize /= 2;
12962
12963   // Represent our vector as a sequence of elements which are the
12964   // largest scalar that we can load.
12965   EVT LoadUnitVecVT = EVT::getVectorVT(
12966       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
12967
12968   // Represent the data using the same element type that is stored in
12969   // memory. In practice, we ''widen'' MemVT.
12970   EVT WideVecVT =
12971       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
12972                        loadRegZize / MemVT.getScalarType().getSizeInBits());
12973
12974   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
12975          "Invalid vector type");
12976
12977   // We can't shuffle using an illegal type.
12978   assert(TLI.isTypeLegal(WideVecVT) &&
12979          "We only lower types that form legal widened vector types");
12980
12981   SmallVector<SDValue, 8> Chains;
12982   SDValue Ptr = Ld->getBasePtr();
12983   SDValue Increment =
12984       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
12985   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
12986
12987   for (unsigned i = 0; i < NumLoads; ++i) {
12988     // Perform a single load.
12989     SDValue ScalarLoad =
12990         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
12991                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
12992                     Ld->getAlignment());
12993     Chains.push_back(ScalarLoad.getValue(1));
12994     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
12995     // another round of DAGCombining.
12996     if (i == 0)
12997       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
12998     else
12999       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13000                         ScalarLoad, DAG.getIntPtrConstant(i));
13001
13002     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13003   }
13004
13005   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13006
13007   // Bitcast the loaded value to a vector of the original element type, in
13008   // the size of the target vector type.
13009   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13010   unsigned SizeRatio = RegSz / MemSz;
13011
13012   if (Ext == ISD::SEXTLOAD) {
13013     // If we have SSE4.1 we can directly emit a VSEXT node.
13014     if (Subtarget->hasSSE41()) {
13015       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13016       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13017       return Sext;
13018     }
13019
13020     // Otherwise we'll shuffle the small elements in the high bits of the
13021     // larger type and perform an arithmetic shift. If the shift is not legal
13022     // it's better to scalarize.
13023     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13024            "We can't implement an sext load without a arithmetic right shift!");
13025
13026     // Redistribute the loaded elements into the different locations.
13027     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13028     for (unsigned i = 0; i != NumElems; ++i)
13029       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13030
13031     SDValue Shuff = DAG.getVectorShuffle(
13032         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13033
13034     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13035
13036     // Build the arithmetic shift.
13037     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13038                    MemVT.getVectorElementType().getSizeInBits();
13039     Shuff =
13040         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13041
13042     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13043     return Shuff;
13044   }
13045
13046   // Redistribute the loaded elements into the different locations.
13047   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13048   for (unsigned i = 0; i != NumElems; ++i)
13049     ShuffleVec[i * SizeRatio] = i;
13050
13051   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13052                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13053
13054   // Bitcast to the requested type.
13055   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13056   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13057   return Shuff;
13058 }
13059
13060 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13061 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13062 // from the AND / OR.
13063 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13064   Opc = Op.getOpcode();
13065   if (Opc != ISD::OR && Opc != ISD::AND)
13066     return false;
13067   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13068           Op.getOperand(0).hasOneUse() &&
13069           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13070           Op.getOperand(1).hasOneUse());
13071 }
13072
13073 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13074 // 1 and that the SETCC node has a single use.
13075 static bool isXor1OfSetCC(SDValue Op) {
13076   if (Op.getOpcode() != ISD::XOR)
13077     return false;
13078   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13079   if (N1C && N1C->getAPIntValue() == 1) {
13080     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13081       Op.getOperand(0).hasOneUse();
13082   }
13083   return false;
13084 }
13085
13086 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13087   bool addTest = true;
13088   SDValue Chain = Op.getOperand(0);
13089   SDValue Cond  = Op.getOperand(1);
13090   SDValue Dest  = Op.getOperand(2);
13091   SDLoc dl(Op);
13092   SDValue CC;
13093   bool Inverted = false;
13094
13095   if (Cond.getOpcode() == ISD::SETCC) {
13096     // Check for setcc([su]{add,sub,mul}o == 0).
13097     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13098         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13099         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13100         Cond.getOperand(0).getResNo() == 1 &&
13101         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13102          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13103          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13104          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13105          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13106          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13107       Inverted = true;
13108       Cond = Cond.getOperand(0);
13109     } else {
13110       SDValue NewCond = LowerSETCC(Cond, DAG);
13111       if (NewCond.getNode())
13112         Cond = NewCond;
13113     }
13114   }
13115 #if 0
13116   // FIXME: LowerXALUO doesn't handle these!!
13117   else if (Cond.getOpcode() == X86ISD::ADD  ||
13118            Cond.getOpcode() == X86ISD::SUB  ||
13119            Cond.getOpcode() == X86ISD::SMUL ||
13120            Cond.getOpcode() == X86ISD::UMUL)
13121     Cond = LowerXALUO(Cond, DAG);
13122 #endif
13123
13124   // Look pass (and (setcc_carry (cmp ...)), 1).
13125   if (Cond.getOpcode() == ISD::AND &&
13126       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13127     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13128     if (C && C->getAPIntValue() == 1)
13129       Cond = Cond.getOperand(0);
13130   }
13131
13132   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13133   // setting operand in place of the X86ISD::SETCC.
13134   unsigned CondOpcode = Cond.getOpcode();
13135   if (CondOpcode == X86ISD::SETCC ||
13136       CondOpcode == X86ISD::SETCC_CARRY) {
13137     CC = Cond.getOperand(0);
13138
13139     SDValue Cmp = Cond.getOperand(1);
13140     unsigned Opc = Cmp.getOpcode();
13141     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13142     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13143       Cond = Cmp;
13144       addTest = false;
13145     } else {
13146       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13147       default: break;
13148       case X86::COND_O:
13149       case X86::COND_B:
13150         // These can only come from an arithmetic instruction with overflow,
13151         // e.g. SADDO, UADDO.
13152         Cond = Cond.getNode()->getOperand(1);
13153         addTest = false;
13154         break;
13155       }
13156     }
13157   }
13158   CondOpcode = Cond.getOpcode();
13159   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13160       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13161       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13162        Cond.getOperand(0).getValueType() != MVT::i8)) {
13163     SDValue LHS = Cond.getOperand(0);
13164     SDValue RHS = Cond.getOperand(1);
13165     unsigned X86Opcode;
13166     unsigned X86Cond;
13167     SDVTList VTs;
13168     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13169     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13170     // X86ISD::INC).
13171     switch (CondOpcode) {
13172     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13173     case ISD::SADDO:
13174       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13175         if (C->isOne()) {
13176           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13177           break;
13178         }
13179       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13180     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13181     case ISD::SSUBO:
13182       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13183         if (C->isOne()) {
13184           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13185           break;
13186         }
13187       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13188     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13189     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13190     default: llvm_unreachable("unexpected overflowing operator");
13191     }
13192     if (Inverted)
13193       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13194     if (CondOpcode == ISD::UMULO)
13195       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13196                           MVT::i32);
13197     else
13198       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13199
13200     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13201
13202     if (CondOpcode == ISD::UMULO)
13203       Cond = X86Op.getValue(2);
13204     else
13205       Cond = X86Op.getValue(1);
13206
13207     CC = DAG.getConstant(X86Cond, MVT::i8);
13208     addTest = false;
13209   } else {
13210     unsigned CondOpc;
13211     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13212       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13213       if (CondOpc == ISD::OR) {
13214         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13215         // two branches instead of an explicit OR instruction with a
13216         // separate test.
13217         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13218             isX86LogicalCmp(Cmp)) {
13219           CC = Cond.getOperand(0).getOperand(0);
13220           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13221                               Chain, Dest, CC, Cmp);
13222           CC = Cond.getOperand(1).getOperand(0);
13223           Cond = Cmp;
13224           addTest = false;
13225         }
13226       } else { // ISD::AND
13227         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13228         // two branches instead of an explicit AND instruction with a
13229         // separate test. However, we only do this if this block doesn't
13230         // have a fall-through edge, because this requires an explicit
13231         // jmp when the condition is false.
13232         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13233             isX86LogicalCmp(Cmp) &&
13234             Op.getNode()->hasOneUse()) {
13235           X86::CondCode CCode =
13236             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13237           CCode = X86::GetOppositeBranchCondition(CCode);
13238           CC = DAG.getConstant(CCode, MVT::i8);
13239           SDNode *User = *Op.getNode()->use_begin();
13240           // Look for an unconditional branch following this conditional branch.
13241           // We need this because we need to reverse the successors in order
13242           // to implement FCMP_OEQ.
13243           if (User->getOpcode() == ISD::BR) {
13244             SDValue FalseBB = User->getOperand(1);
13245             SDNode *NewBR =
13246               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13247             assert(NewBR == User);
13248             (void)NewBR;
13249             Dest = FalseBB;
13250
13251             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13252                                 Chain, Dest, CC, Cmp);
13253             X86::CondCode CCode =
13254               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13255             CCode = X86::GetOppositeBranchCondition(CCode);
13256             CC = DAG.getConstant(CCode, MVT::i8);
13257             Cond = Cmp;
13258             addTest = false;
13259           }
13260         }
13261       }
13262     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13263       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13264       // It should be transformed during dag combiner except when the condition
13265       // is set by a arithmetics with overflow node.
13266       X86::CondCode CCode =
13267         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13268       CCode = X86::GetOppositeBranchCondition(CCode);
13269       CC = DAG.getConstant(CCode, MVT::i8);
13270       Cond = Cond.getOperand(0).getOperand(1);
13271       addTest = false;
13272     } else if (Cond.getOpcode() == ISD::SETCC &&
13273                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13274       // For FCMP_OEQ, we can emit
13275       // two branches instead of an explicit AND instruction with a
13276       // separate test. However, we only do this if this block doesn't
13277       // have a fall-through edge, because this requires an explicit
13278       // jmp when the condition is false.
13279       if (Op.getNode()->hasOneUse()) {
13280         SDNode *User = *Op.getNode()->use_begin();
13281         // Look for an unconditional branch following this conditional branch.
13282         // We need this because we need to reverse the successors in order
13283         // to implement FCMP_OEQ.
13284         if (User->getOpcode() == ISD::BR) {
13285           SDValue FalseBB = User->getOperand(1);
13286           SDNode *NewBR =
13287             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13288           assert(NewBR == User);
13289           (void)NewBR;
13290           Dest = FalseBB;
13291
13292           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13293                                     Cond.getOperand(0), Cond.getOperand(1));
13294           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13295           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13296           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13297                               Chain, Dest, CC, Cmp);
13298           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13299           Cond = Cmp;
13300           addTest = false;
13301         }
13302       }
13303     } else if (Cond.getOpcode() == ISD::SETCC &&
13304                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13305       // For FCMP_UNE, we can emit
13306       // two branches instead of an explicit AND instruction with a
13307       // separate test. However, we only do this if this block doesn't
13308       // have a fall-through edge, because this requires an explicit
13309       // jmp when the condition is false.
13310       if (Op.getNode()->hasOneUse()) {
13311         SDNode *User = *Op.getNode()->use_begin();
13312         // Look for an unconditional branch following this conditional branch.
13313         // We need this because we need to reverse the successors in order
13314         // to implement FCMP_UNE.
13315         if (User->getOpcode() == ISD::BR) {
13316           SDValue FalseBB = User->getOperand(1);
13317           SDNode *NewBR =
13318             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13319           assert(NewBR == User);
13320           (void)NewBR;
13321
13322           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13323                                     Cond.getOperand(0), Cond.getOperand(1));
13324           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13325           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13326           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13327                               Chain, Dest, CC, Cmp);
13328           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13329           Cond = Cmp;
13330           addTest = false;
13331           Dest = FalseBB;
13332         }
13333       }
13334     }
13335   }
13336
13337   if (addTest) {
13338     // Look pass the truncate if the high bits are known zero.
13339     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13340         Cond = Cond.getOperand(0);
13341
13342     // We know the result of AND is compared against zero. Try to match
13343     // it to BT.
13344     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13345       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13346       if (NewSetCC.getNode()) {
13347         CC = NewSetCC.getOperand(0);
13348         Cond = NewSetCC.getOperand(1);
13349         addTest = false;
13350       }
13351     }
13352   }
13353
13354   if (addTest) {
13355     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13356     CC = DAG.getConstant(X86Cond, MVT::i8);
13357     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13358   }
13359   Cond = ConvertCmpIfNecessary(Cond, DAG);
13360   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13361                      Chain, Dest, CC, Cond);
13362 }
13363
13364 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13365 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13366 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13367 // that the guard pages used by the OS virtual memory manager are allocated in
13368 // correct sequence.
13369 SDValue
13370 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13371                                            SelectionDAG &DAG) const {
13372   MachineFunction &MF = DAG.getMachineFunction();
13373   bool SplitStack = MF.shouldSplitStack();
13374   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13375                SplitStack;
13376   SDLoc dl(Op);
13377
13378   if (!Lower) {
13379     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13380     SDNode* Node = Op.getNode();
13381
13382     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13383     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13384         " not tell us which reg is the stack pointer!");
13385     EVT VT = Node->getValueType(0);
13386     SDValue Tmp1 = SDValue(Node, 0);
13387     SDValue Tmp2 = SDValue(Node, 1);
13388     SDValue Tmp3 = Node->getOperand(2);
13389     SDValue Chain = Tmp1.getOperand(0);
13390
13391     // Chain the dynamic stack allocation so that it doesn't modify the stack
13392     // pointer when other instructions are using the stack.
13393     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13394         SDLoc(Node));
13395
13396     SDValue Size = Tmp2.getOperand(1);
13397     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13398     Chain = SP.getValue(1);
13399     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13400     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13401     unsigned StackAlign = TFI.getStackAlignment();
13402     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13403     if (Align > StackAlign)
13404       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13405           DAG.getConstant(-(uint64_t)Align, VT));
13406     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13407
13408     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13409         DAG.getIntPtrConstant(0, true), SDValue(),
13410         SDLoc(Node));
13411
13412     SDValue Ops[2] = { Tmp1, Tmp2 };
13413     return DAG.getMergeValues(Ops, dl);
13414   }
13415
13416   // Get the inputs.
13417   SDValue Chain = Op.getOperand(0);
13418   SDValue Size  = Op.getOperand(1);
13419   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13420   EVT VT = Op.getNode()->getValueType(0);
13421
13422   bool Is64Bit = Subtarget->is64Bit();
13423   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13424
13425   if (SplitStack) {
13426     MachineRegisterInfo &MRI = MF.getRegInfo();
13427
13428     if (Is64Bit) {
13429       // The 64 bit implementation of segmented stacks needs to clobber both r10
13430       // r11. This makes it impossible to use it along with nested parameters.
13431       const Function *F = MF.getFunction();
13432
13433       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13434            I != E; ++I)
13435         if (I->hasNestAttr())
13436           report_fatal_error("Cannot use segmented stacks with functions that "
13437                              "have nested arguments.");
13438     }
13439
13440     const TargetRegisterClass *AddrRegClass =
13441       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13442     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13443     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13444     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13445                                 DAG.getRegister(Vreg, SPTy));
13446     SDValue Ops1[2] = { Value, Chain };
13447     return DAG.getMergeValues(Ops1, dl);
13448   } else {
13449     SDValue Flag;
13450     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13451
13452     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13453     Flag = Chain.getValue(1);
13454     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13455
13456     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13457
13458     const X86RegisterInfo *RegInfo =
13459       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13460     unsigned SPReg = RegInfo->getStackRegister();
13461     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13462     Chain = SP.getValue(1);
13463
13464     if (Align) {
13465       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13466                        DAG.getConstant(-(uint64_t)Align, VT));
13467       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13468     }
13469
13470     SDValue Ops1[2] = { SP, Chain };
13471     return DAG.getMergeValues(Ops1, dl);
13472   }
13473 }
13474
13475 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13476   MachineFunction &MF = DAG.getMachineFunction();
13477   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13478
13479   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13480   SDLoc DL(Op);
13481
13482   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13483     // vastart just stores the address of the VarArgsFrameIndex slot into the
13484     // memory location argument.
13485     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13486                                    getPointerTy());
13487     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13488                         MachinePointerInfo(SV), false, false, 0);
13489   }
13490
13491   // __va_list_tag:
13492   //   gp_offset         (0 - 6 * 8)
13493   //   fp_offset         (48 - 48 + 8 * 16)
13494   //   overflow_arg_area (point to parameters coming in memory).
13495   //   reg_save_area
13496   SmallVector<SDValue, 8> MemOps;
13497   SDValue FIN = Op.getOperand(1);
13498   // Store gp_offset
13499   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13500                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13501                                                MVT::i32),
13502                                FIN, MachinePointerInfo(SV), false, false, 0);
13503   MemOps.push_back(Store);
13504
13505   // Store fp_offset
13506   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13507                     FIN, DAG.getIntPtrConstant(4));
13508   Store = DAG.getStore(Op.getOperand(0), DL,
13509                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13510                                        MVT::i32),
13511                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13512   MemOps.push_back(Store);
13513
13514   // Store ptr to overflow_arg_area
13515   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13516                     FIN, DAG.getIntPtrConstant(4));
13517   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13518                                     getPointerTy());
13519   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13520                        MachinePointerInfo(SV, 8),
13521                        false, false, 0);
13522   MemOps.push_back(Store);
13523
13524   // Store ptr to reg_save_area.
13525   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13526                     FIN, DAG.getIntPtrConstant(8));
13527   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13528                                     getPointerTy());
13529   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13530                        MachinePointerInfo(SV, 16), false, false, 0);
13531   MemOps.push_back(Store);
13532   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13533 }
13534
13535 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13536   assert(Subtarget->is64Bit() &&
13537          "LowerVAARG only handles 64-bit va_arg!");
13538   assert((Subtarget->isTargetLinux() ||
13539           Subtarget->isTargetDarwin()) &&
13540           "Unhandled target in LowerVAARG");
13541   assert(Op.getNode()->getNumOperands() == 4);
13542   SDValue Chain = Op.getOperand(0);
13543   SDValue SrcPtr = Op.getOperand(1);
13544   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13545   unsigned Align = Op.getConstantOperandVal(3);
13546   SDLoc dl(Op);
13547
13548   EVT ArgVT = Op.getNode()->getValueType(0);
13549   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13550   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13551   uint8_t ArgMode;
13552
13553   // Decide which area this value should be read from.
13554   // TODO: Implement the AMD64 ABI in its entirety. This simple
13555   // selection mechanism works only for the basic types.
13556   if (ArgVT == MVT::f80) {
13557     llvm_unreachable("va_arg for f80 not yet implemented");
13558   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13559     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13560   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13561     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13562   } else {
13563     llvm_unreachable("Unhandled argument type in LowerVAARG");
13564   }
13565
13566   if (ArgMode == 2) {
13567     // Sanity Check: Make sure using fp_offset makes sense.
13568     assert(!DAG.getTarget().Options.UseSoftFloat &&
13569            !(DAG.getMachineFunction()
13570                 .getFunction()->getAttributes()
13571                 .hasAttribute(AttributeSet::FunctionIndex,
13572                               Attribute::NoImplicitFloat)) &&
13573            Subtarget->hasSSE1());
13574   }
13575
13576   // Insert VAARG_64 node into the DAG
13577   // VAARG_64 returns two values: Variable Argument Address, Chain
13578   SmallVector<SDValue, 11> InstOps;
13579   InstOps.push_back(Chain);
13580   InstOps.push_back(SrcPtr);
13581   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13582   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13583   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13584   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13585   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13586                                           VTs, InstOps, MVT::i64,
13587                                           MachinePointerInfo(SV),
13588                                           /*Align=*/0,
13589                                           /*Volatile=*/false,
13590                                           /*ReadMem=*/true,
13591                                           /*WriteMem=*/true);
13592   Chain = VAARG.getValue(1);
13593
13594   // Load the next argument and return it
13595   return DAG.getLoad(ArgVT, dl,
13596                      Chain,
13597                      VAARG,
13598                      MachinePointerInfo(),
13599                      false, false, false, 0);
13600 }
13601
13602 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13603                            SelectionDAG &DAG) {
13604   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13605   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13606   SDValue Chain = Op.getOperand(0);
13607   SDValue DstPtr = Op.getOperand(1);
13608   SDValue SrcPtr = Op.getOperand(2);
13609   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13610   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13611   SDLoc DL(Op);
13612
13613   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13614                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13615                        false,
13616                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13617 }
13618
13619 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13620 // amount is a constant. Takes immediate version of shift as input.
13621 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13622                                           SDValue SrcOp, uint64_t ShiftAmt,
13623                                           SelectionDAG &DAG) {
13624   MVT ElementType = VT.getVectorElementType();
13625
13626   // Fold this packed shift into its first operand if ShiftAmt is 0.
13627   if (ShiftAmt == 0)
13628     return SrcOp;
13629
13630   // Check for ShiftAmt >= element width
13631   if (ShiftAmt >= ElementType.getSizeInBits()) {
13632     if (Opc == X86ISD::VSRAI)
13633       ShiftAmt = ElementType.getSizeInBits() - 1;
13634     else
13635       return DAG.getConstant(0, VT);
13636   }
13637
13638   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13639          && "Unknown target vector shift-by-constant node");
13640
13641   // Fold this packed vector shift into a build vector if SrcOp is a
13642   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13643   if (VT == SrcOp.getSimpleValueType() &&
13644       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13645     SmallVector<SDValue, 8> Elts;
13646     unsigned NumElts = SrcOp->getNumOperands();
13647     ConstantSDNode *ND;
13648
13649     switch(Opc) {
13650     default: llvm_unreachable(nullptr);
13651     case X86ISD::VSHLI:
13652       for (unsigned i=0; i!=NumElts; ++i) {
13653         SDValue CurrentOp = SrcOp->getOperand(i);
13654         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13655           Elts.push_back(CurrentOp);
13656           continue;
13657         }
13658         ND = cast<ConstantSDNode>(CurrentOp);
13659         const APInt &C = ND->getAPIntValue();
13660         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13661       }
13662       break;
13663     case X86ISD::VSRLI:
13664       for (unsigned i=0; i!=NumElts; ++i) {
13665         SDValue CurrentOp = SrcOp->getOperand(i);
13666         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13667           Elts.push_back(CurrentOp);
13668           continue;
13669         }
13670         ND = cast<ConstantSDNode>(CurrentOp);
13671         const APInt &C = ND->getAPIntValue();
13672         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13673       }
13674       break;
13675     case X86ISD::VSRAI:
13676       for (unsigned i=0; i!=NumElts; ++i) {
13677         SDValue CurrentOp = SrcOp->getOperand(i);
13678         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13679           Elts.push_back(CurrentOp);
13680           continue;
13681         }
13682         ND = cast<ConstantSDNode>(CurrentOp);
13683         const APInt &C = ND->getAPIntValue();
13684         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13685       }
13686       break;
13687     }
13688
13689     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13690   }
13691
13692   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13693 }
13694
13695 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13696 // may or may not be a constant. Takes immediate version of shift as input.
13697 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13698                                    SDValue SrcOp, SDValue ShAmt,
13699                                    SelectionDAG &DAG) {
13700   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13701
13702   // Catch shift-by-constant.
13703   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13704     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13705                                       CShAmt->getZExtValue(), DAG);
13706
13707   // Change opcode to non-immediate version
13708   switch (Opc) {
13709     default: llvm_unreachable("Unknown target vector shift node");
13710     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13711     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13712     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13713   }
13714
13715   // Need to build a vector containing shift amount
13716   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13717   SDValue ShOps[4];
13718   ShOps[0] = ShAmt;
13719   ShOps[1] = DAG.getConstant(0, MVT::i32);
13720   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13721   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13722
13723   // The return type has to be a 128-bit type with the same element
13724   // type as the input type.
13725   MVT EltVT = VT.getVectorElementType();
13726   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13727
13728   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13729   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13730 }
13731
13732 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13733   SDLoc dl(Op);
13734   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13735   switch (IntNo) {
13736   default: return SDValue();    // Don't custom lower most intrinsics.
13737   // Comparison intrinsics.
13738   case Intrinsic::x86_sse_comieq_ss:
13739   case Intrinsic::x86_sse_comilt_ss:
13740   case Intrinsic::x86_sse_comile_ss:
13741   case Intrinsic::x86_sse_comigt_ss:
13742   case Intrinsic::x86_sse_comige_ss:
13743   case Intrinsic::x86_sse_comineq_ss:
13744   case Intrinsic::x86_sse_ucomieq_ss:
13745   case Intrinsic::x86_sse_ucomilt_ss:
13746   case Intrinsic::x86_sse_ucomile_ss:
13747   case Intrinsic::x86_sse_ucomigt_ss:
13748   case Intrinsic::x86_sse_ucomige_ss:
13749   case Intrinsic::x86_sse_ucomineq_ss:
13750   case Intrinsic::x86_sse2_comieq_sd:
13751   case Intrinsic::x86_sse2_comilt_sd:
13752   case Intrinsic::x86_sse2_comile_sd:
13753   case Intrinsic::x86_sse2_comigt_sd:
13754   case Intrinsic::x86_sse2_comige_sd:
13755   case Intrinsic::x86_sse2_comineq_sd:
13756   case Intrinsic::x86_sse2_ucomieq_sd:
13757   case Intrinsic::x86_sse2_ucomilt_sd:
13758   case Intrinsic::x86_sse2_ucomile_sd:
13759   case Intrinsic::x86_sse2_ucomigt_sd:
13760   case Intrinsic::x86_sse2_ucomige_sd:
13761   case Intrinsic::x86_sse2_ucomineq_sd: {
13762     unsigned Opc;
13763     ISD::CondCode CC;
13764     switch (IntNo) {
13765     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13766     case Intrinsic::x86_sse_comieq_ss:
13767     case Intrinsic::x86_sse2_comieq_sd:
13768       Opc = X86ISD::COMI;
13769       CC = ISD::SETEQ;
13770       break;
13771     case Intrinsic::x86_sse_comilt_ss:
13772     case Intrinsic::x86_sse2_comilt_sd:
13773       Opc = X86ISD::COMI;
13774       CC = ISD::SETLT;
13775       break;
13776     case Intrinsic::x86_sse_comile_ss:
13777     case Intrinsic::x86_sse2_comile_sd:
13778       Opc = X86ISD::COMI;
13779       CC = ISD::SETLE;
13780       break;
13781     case Intrinsic::x86_sse_comigt_ss:
13782     case Intrinsic::x86_sse2_comigt_sd:
13783       Opc = X86ISD::COMI;
13784       CC = ISD::SETGT;
13785       break;
13786     case Intrinsic::x86_sse_comige_ss:
13787     case Intrinsic::x86_sse2_comige_sd:
13788       Opc = X86ISD::COMI;
13789       CC = ISD::SETGE;
13790       break;
13791     case Intrinsic::x86_sse_comineq_ss:
13792     case Intrinsic::x86_sse2_comineq_sd:
13793       Opc = X86ISD::COMI;
13794       CC = ISD::SETNE;
13795       break;
13796     case Intrinsic::x86_sse_ucomieq_ss:
13797     case Intrinsic::x86_sse2_ucomieq_sd:
13798       Opc = X86ISD::UCOMI;
13799       CC = ISD::SETEQ;
13800       break;
13801     case Intrinsic::x86_sse_ucomilt_ss:
13802     case Intrinsic::x86_sse2_ucomilt_sd:
13803       Opc = X86ISD::UCOMI;
13804       CC = ISD::SETLT;
13805       break;
13806     case Intrinsic::x86_sse_ucomile_ss:
13807     case Intrinsic::x86_sse2_ucomile_sd:
13808       Opc = X86ISD::UCOMI;
13809       CC = ISD::SETLE;
13810       break;
13811     case Intrinsic::x86_sse_ucomigt_ss:
13812     case Intrinsic::x86_sse2_ucomigt_sd:
13813       Opc = X86ISD::UCOMI;
13814       CC = ISD::SETGT;
13815       break;
13816     case Intrinsic::x86_sse_ucomige_ss:
13817     case Intrinsic::x86_sse2_ucomige_sd:
13818       Opc = X86ISD::UCOMI;
13819       CC = ISD::SETGE;
13820       break;
13821     case Intrinsic::x86_sse_ucomineq_ss:
13822     case Intrinsic::x86_sse2_ucomineq_sd:
13823       Opc = X86ISD::UCOMI;
13824       CC = ISD::SETNE;
13825       break;
13826     }
13827
13828     SDValue LHS = Op.getOperand(1);
13829     SDValue RHS = Op.getOperand(2);
13830     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13831     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13832     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13833     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13834                                 DAG.getConstant(X86CC, MVT::i8), Cond);
13835     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13836   }
13837
13838   // Arithmetic intrinsics.
13839   case Intrinsic::x86_sse2_pmulu_dq:
13840   case Intrinsic::x86_avx2_pmulu_dq:
13841     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13842                        Op.getOperand(1), Op.getOperand(2));
13843
13844   case Intrinsic::x86_sse41_pmuldq:
13845   case Intrinsic::x86_avx2_pmul_dq:
13846     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13847                        Op.getOperand(1), Op.getOperand(2));
13848
13849   case Intrinsic::x86_sse2_pmulhu_w:
13850   case Intrinsic::x86_avx2_pmulhu_w:
13851     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13852                        Op.getOperand(1), Op.getOperand(2));
13853
13854   case Intrinsic::x86_sse2_pmulh_w:
13855   case Intrinsic::x86_avx2_pmulh_w:
13856     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13857                        Op.getOperand(1), Op.getOperand(2));
13858
13859   // SSE2/AVX2 sub with unsigned saturation intrinsics
13860   case Intrinsic::x86_sse2_psubus_b:
13861   case Intrinsic::x86_sse2_psubus_w:
13862   case Intrinsic::x86_avx2_psubus_b:
13863   case Intrinsic::x86_avx2_psubus_w:
13864     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13865                        Op.getOperand(1), Op.getOperand(2));
13866
13867   // SSE3/AVX horizontal add/sub intrinsics
13868   case Intrinsic::x86_sse3_hadd_ps:
13869   case Intrinsic::x86_sse3_hadd_pd:
13870   case Intrinsic::x86_avx_hadd_ps_256:
13871   case Intrinsic::x86_avx_hadd_pd_256:
13872   case Intrinsic::x86_sse3_hsub_ps:
13873   case Intrinsic::x86_sse3_hsub_pd:
13874   case Intrinsic::x86_avx_hsub_ps_256:
13875   case Intrinsic::x86_avx_hsub_pd_256:
13876   case Intrinsic::x86_ssse3_phadd_w_128:
13877   case Intrinsic::x86_ssse3_phadd_d_128:
13878   case Intrinsic::x86_avx2_phadd_w:
13879   case Intrinsic::x86_avx2_phadd_d:
13880   case Intrinsic::x86_ssse3_phsub_w_128:
13881   case Intrinsic::x86_ssse3_phsub_d_128:
13882   case Intrinsic::x86_avx2_phsub_w:
13883   case Intrinsic::x86_avx2_phsub_d: {
13884     unsigned Opcode;
13885     switch (IntNo) {
13886     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13887     case Intrinsic::x86_sse3_hadd_ps:
13888     case Intrinsic::x86_sse3_hadd_pd:
13889     case Intrinsic::x86_avx_hadd_ps_256:
13890     case Intrinsic::x86_avx_hadd_pd_256:
13891       Opcode = X86ISD::FHADD;
13892       break;
13893     case Intrinsic::x86_sse3_hsub_ps:
13894     case Intrinsic::x86_sse3_hsub_pd:
13895     case Intrinsic::x86_avx_hsub_ps_256:
13896     case Intrinsic::x86_avx_hsub_pd_256:
13897       Opcode = X86ISD::FHSUB;
13898       break;
13899     case Intrinsic::x86_ssse3_phadd_w_128:
13900     case Intrinsic::x86_ssse3_phadd_d_128:
13901     case Intrinsic::x86_avx2_phadd_w:
13902     case Intrinsic::x86_avx2_phadd_d:
13903       Opcode = X86ISD::HADD;
13904       break;
13905     case Intrinsic::x86_ssse3_phsub_w_128:
13906     case Intrinsic::x86_ssse3_phsub_d_128:
13907     case Intrinsic::x86_avx2_phsub_w:
13908     case Intrinsic::x86_avx2_phsub_d:
13909       Opcode = X86ISD::HSUB;
13910       break;
13911     }
13912     return DAG.getNode(Opcode, dl, Op.getValueType(),
13913                        Op.getOperand(1), Op.getOperand(2));
13914   }
13915
13916   // SSE2/SSE41/AVX2 integer max/min intrinsics.
13917   case Intrinsic::x86_sse2_pmaxu_b:
13918   case Intrinsic::x86_sse41_pmaxuw:
13919   case Intrinsic::x86_sse41_pmaxud:
13920   case Intrinsic::x86_avx2_pmaxu_b:
13921   case Intrinsic::x86_avx2_pmaxu_w:
13922   case Intrinsic::x86_avx2_pmaxu_d:
13923   case Intrinsic::x86_sse2_pminu_b:
13924   case Intrinsic::x86_sse41_pminuw:
13925   case Intrinsic::x86_sse41_pminud:
13926   case Intrinsic::x86_avx2_pminu_b:
13927   case Intrinsic::x86_avx2_pminu_w:
13928   case Intrinsic::x86_avx2_pminu_d:
13929   case Intrinsic::x86_sse41_pmaxsb:
13930   case Intrinsic::x86_sse2_pmaxs_w:
13931   case Intrinsic::x86_sse41_pmaxsd:
13932   case Intrinsic::x86_avx2_pmaxs_b:
13933   case Intrinsic::x86_avx2_pmaxs_w:
13934   case Intrinsic::x86_avx2_pmaxs_d:
13935   case Intrinsic::x86_sse41_pminsb:
13936   case Intrinsic::x86_sse2_pmins_w:
13937   case Intrinsic::x86_sse41_pminsd:
13938   case Intrinsic::x86_avx2_pmins_b:
13939   case Intrinsic::x86_avx2_pmins_w:
13940   case Intrinsic::x86_avx2_pmins_d: {
13941     unsigned Opcode;
13942     switch (IntNo) {
13943     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13944     case Intrinsic::x86_sse2_pmaxu_b:
13945     case Intrinsic::x86_sse41_pmaxuw:
13946     case Intrinsic::x86_sse41_pmaxud:
13947     case Intrinsic::x86_avx2_pmaxu_b:
13948     case Intrinsic::x86_avx2_pmaxu_w:
13949     case Intrinsic::x86_avx2_pmaxu_d:
13950       Opcode = X86ISD::UMAX;
13951       break;
13952     case Intrinsic::x86_sse2_pminu_b:
13953     case Intrinsic::x86_sse41_pminuw:
13954     case Intrinsic::x86_sse41_pminud:
13955     case Intrinsic::x86_avx2_pminu_b:
13956     case Intrinsic::x86_avx2_pminu_w:
13957     case Intrinsic::x86_avx2_pminu_d:
13958       Opcode = X86ISD::UMIN;
13959       break;
13960     case Intrinsic::x86_sse41_pmaxsb:
13961     case Intrinsic::x86_sse2_pmaxs_w:
13962     case Intrinsic::x86_sse41_pmaxsd:
13963     case Intrinsic::x86_avx2_pmaxs_b:
13964     case Intrinsic::x86_avx2_pmaxs_w:
13965     case Intrinsic::x86_avx2_pmaxs_d:
13966       Opcode = X86ISD::SMAX;
13967       break;
13968     case Intrinsic::x86_sse41_pminsb:
13969     case Intrinsic::x86_sse2_pmins_w:
13970     case Intrinsic::x86_sse41_pminsd:
13971     case Intrinsic::x86_avx2_pmins_b:
13972     case Intrinsic::x86_avx2_pmins_w:
13973     case Intrinsic::x86_avx2_pmins_d:
13974       Opcode = X86ISD::SMIN;
13975       break;
13976     }
13977     return DAG.getNode(Opcode, dl, Op.getValueType(),
13978                        Op.getOperand(1), Op.getOperand(2));
13979   }
13980
13981   // SSE/SSE2/AVX floating point max/min intrinsics.
13982   case Intrinsic::x86_sse_max_ps:
13983   case Intrinsic::x86_sse2_max_pd:
13984   case Intrinsic::x86_avx_max_ps_256:
13985   case Intrinsic::x86_avx_max_pd_256:
13986   case Intrinsic::x86_sse_min_ps:
13987   case Intrinsic::x86_sse2_min_pd:
13988   case Intrinsic::x86_avx_min_ps_256:
13989   case Intrinsic::x86_avx_min_pd_256: {
13990     unsigned Opcode;
13991     switch (IntNo) {
13992     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13993     case Intrinsic::x86_sse_max_ps:
13994     case Intrinsic::x86_sse2_max_pd:
13995     case Intrinsic::x86_avx_max_ps_256:
13996     case Intrinsic::x86_avx_max_pd_256:
13997       Opcode = X86ISD::FMAX;
13998       break;
13999     case Intrinsic::x86_sse_min_ps:
14000     case Intrinsic::x86_sse2_min_pd:
14001     case Intrinsic::x86_avx_min_ps_256:
14002     case Intrinsic::x86_avx_min_pd_256:
14003       Opcode = X86ISD::FMIN;
14004       break;
14005     }
14006     return DAG.getNode(Opcode, dl, Op.getValueType(),
14007                        Op.getOperand(1), Op.getOperand(2));
14008   }
14009
14010   // AVX2 variable shift intrinsics
14011   case Intrinsic::x86_avx2_psllv_d:
14012   case Intrinsic::x86_avx2_psllv_q:
14013   case Intrinsic::x86_avx2_psllv_d_256:
14014   case Intrinsic::x86_avx2_psllv_q_256:
14015   case Intrinsic::x86_avx2_psrlv_d:
14016   case Intrinsic::x86_avx2_psrlv_q:
14017   case Intrinsic::x86_avx2_psrlv_d_256:
14018   case Intrinsic::x86_avx2_psrlv_q_256:
14019   case Intrinsic::x86_avx2_psrav_d:
14020   case Intrinsic::x86_avx2_psrav_d_256: {
14021     unsigned Opcode;
14022     switch (IntNo) {
14023     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14024     case Intrinsic::x86_avx2_psllv_d:
14025     case Intrinsic::x86_avx2_psllv_q:
14026     case Intrinsic::x86_avx2_psllv_d_256:
14027     case Intrinsic::x86_avx2_psllv_q_256:
14028       Opcode = ISD::SHL;
14029       break;
14030     case Intrinsic::x86_avx2_psrlv_d:
14031     case Intrinsic::x86_avx2_psrlv_q:
14032     case Intrinsic::x86_avx2_psrlv_d_256:
14033     case Intrinsic::x86_avx2_psrlv_q_256:
14034       Opcode = ISD::SRL;
14035       break;
14036     case Intrinsic::x86_avx2_psrav_d:
14037     case Intrinsic::x86_avx2_psrav_d_256:
14038       Opcode = ISD::SRA;
14039       break;
14040     }
14041     return DAG.getNode(Opcode, dl, Op.getValueType(),
14042                        Op.getOperand(1), Op.getOperand(2));
14043   }
14044
14045   case Intrinsic::x86_sse2_packssdw_128:
14046   case Intrinsic::x86_sse2_packsswb_128:
14047   case Intrinsic::x86_avx2_packssdw:
14048   case Intrinsic::x86_avx2_packsswb:
14049     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14050                        Op.getOperand(1), Op.getOperand(2));
14051
14052   case Intrinsic::x86_sse2_packuswb_128:
14053   case Intrinsic::x86_sse41_packusdw:
14054   case Intrinsic::x86_avx2_packuswb:
14055   case Intrinsic::x86_avx2_packusdw:
14056     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14057                        Op.getOperand(1), Op.getOperand(2));
14058
14059   case Intrinsic::x86_ssse3_pshuf_b_128:
14060   case Intrinsic::x86_avx2_pshuf_b:
14061     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14062                        Op.getOperand(1), Op.getOperand(2));
14063
14064   case Intrinsic::x86_sse2_pshuf_d:
14065     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14066                        Op.getOperand(1), Op.getOperand(2));
14067
14068   case Intrinsic::x86_sse2_pshufl_w:
14069     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14070                        Op.getOperand(1), Op.getOperand(2));
14071
14072   case Intrinsic::x86_sse2_pshufh_w:
14073     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14074                        Op.getOperand(1), Op.getOperand(2));
14075
14076   case Intrinsic::x86_ssse3_psign_b_128:
14077   case Intrinsic::x86_ssse3_psign_w_128:
14078   case Intrinsic::x86_ssse3_psign_d_128:
14079   case Intrinsic::x86_avx2_psign_b:
14080   case Intrinsic::x86_avx2_psign_w:
14081   case Intrinsic::x86_avx2_psign_d:
14082     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14083                        Op.getOperand(1), Op.getOperand(2));
14084
14085   case Intrinsic::x86_sse41_insertps:
14086     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14087                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14088
14089   case Intrinsic::x86_avx_vperm2f128_ps_256:
14090   case Intrinsic::x86_avx_vperm2f128_pd_256:
14091   case Intrinsic::x86_avx_vperm2f128_si_256:
14092   case Intrinsic::x86_avx2_vperm2i128:
14093     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14094                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14095
14096   case Intrinsic::x86_avx2_permd:
14097   case Intrinsic::x86_avx2_permps:
14098     // Operands intentionally swapped. Mask is last operand to intrinsic,
14099     // but second operand for node/instruction.
14100     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14101                        Op.getOperand(2), Op.getOperand(1));
14102
14103   case Intrinsic::x86_sse_sqrt_ps:
14104   case Intrinsic::x86_sse2_sqrt_pd:
14105   case Intrinsic::x86_avx_sqrt_ps_256:
14106   case Intrinsic::x86_avx_sqrt_pd_256:
14107     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14108
14109   // ptest and testp intrinsics. The intrinsic these come from are designed to
14110   // return an integer value, not just an instruction so lower it to the ptest
14111   // or testp pattern and a setcc for the result.
14112   case Intrinsic::x86_sse41_ptestz:
14113   case Intrinsic::x86_sse41_ptestc:
14114   case Intrinsic::x86_sse41_ptestnzc:
14115   case Intrinsic::x86_avx_ptestz_256:
14116   case Intrinsic::x86_avx_ptestc_256:
14117   case Intrinsic::x86_avx_ptestnzc_256:
14118   case Intrinsic::x86_avx_vtestz_ps:
14119   case Intrinsic::x86_avx_vtestc_ps:
14120   case Intrinsic::x86_avx_vtestnzc_ps:
14121   case Intrinsic::x86_avx_vtestz_pd:
14122   case Intrinsic::x86_avx_vtestc_pd:
14123   case Intrinsic::x86_avx_vtestnzc_pd:
14124   case Intrinsic::x86_avx_vtestz_ps_256:
14125   case Intrinsic::x86_avx_vtestc_ps_256:
14126   case Intrinsic::x86_avx_vtestnzc_ps_256:
14127   case Intrinsic::x86_avx_vtestz_pd_256:
14128   case Intrinsic::x86_avx_vtestc_pd_256:
14129   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14130     bool IsTestPacked = false;
14131     unsigned X86CC;
14132     switch (IntNo) {
14133     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14134     case Intrinsic::x86_avx_vtestz_ps:
14135     case Intrinsic::x86_avx_vtestz_pd:
14136     case Intrinsic::x86_avx_vtestz_ps_256:
14137     case Intrinsic::x86_avx_vtestz_pd_256:
14138       IsTestPacked = true; // Fallthrough
14139     case Intrinsic::x86_sse41_ptestz:
14140     case Intrinsic::x86_avx_ptestz_256:
14141       // ZF = 1
14142       X86CC = X86::COND_E;
14143       break;
14144     case Intrinsic::x86_avx_vtestc_ps:
14145     case Intrinsic::x86_avx_vtestc_pd:
14146     case Intrinsic::x86_avx_vtestc_ps_256:
14147     case Intrinsic::x86_avx_vtestc_pd_256:
14148       IsTestPacked = true; // Fallthrough
14149     case Intrinsic::x86_sse41_ptestc:
14150     case Intrinsic::x86_avx_ptestc_256:
14151       // CF = 1
14152       X86CC = X86::COND_B;
14153       break;
14154     case Intrinsic::x86_avx_vtestnzc_ps:
14155     case Intrinsic::x86_avx_vtestnzc_pd:
14156     case Intrinsic::x86_avx_vtestnzc_ps_256:
14157     case Intrinsic::x86_avx_vtestnzc_pd_256:
14158       IsTestPacked = true; // Fallthrough
14159     case Intrinsic::x86_sse41_ptestnzc:
14160     case Intrinsic::x86_avx_ptestnzc_256:
14161       // ZF and CF = 0
14162       X86CC = X86::COND_A;
14163       break;
14164     }
14165
14166     SDValue LHS = Op.getOperand(1);
14167     SDValue RHS = Op.getOperand(2);
14168     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14169     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14170     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14171     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14172     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14173   }
14174   case Intrinsic::x86_avx512_kortestz_w:
14175   case Intrinsic::x86_avx512_kortestc_w: {
14176     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14177     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14178     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14179     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14180     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14181     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14182     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14183   }
14184
14185   // SSE/AVX shift intrinsics
14186   case Intrinsic::x86_sse2_psll_w:
14187   case Intrinsic::x86_sse2_psll_d:
14188   case Intrinsic::x86_sse2_psll_q:
14189   case Intrinsic::x86_avx2_psll_w:
14190   case Intrinsic::x86_avx2_psll_d:
14191   case Intrinsic::x86_avx2_psll_q:
14192   case Intrinsic::x86_sse2_psrl_w:
14193   case Intrinsic::x86_sse2_psrl_d:
14194   case Intrinsic::x86_sse2_psrl_q:
14195   case Intrinsic::x86_avx2_psrl_w:
14196   case Intrinsic::x86_avx2_psrl_d:
14197   case Intrinsic::x86_avx2_psrl_q:
14198   case Intrinsic::x86_sse2_psra_w:
14199   case Intrinsic::x86_sse2_psra_d:
14200   case Intrinsic::x86_avx2_psra_w:
14201   case Intrinsic::x86_avx2_psra_d: {
14202     unsigned Opcode;
14203     switch (IntNo) {
14204     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14205     case Intrinsic::x86_sse2_psll_w:
14206     case Intrinsic::x86_sse2_psll_d:
14207     case Intrinsic::x86_sse2_psll_q:
14208     case Intrinsic::x86_avx2_psll_w:
14209     case Intrinsic::x86_avx2_psll_d:
14210     case Intrinsic::x86_avx2_psll_q:
14211       Opcode = X86ISD::VSHL;
14212       break;
14213     case Intrinsic::x86_sse2_psrl_w:
14214     case Intrinsic::x86_sse2_psrl_d:
14215     case Intrinsic::x86_sse2_psrl_q:
14216     case Intrinsic::x86_avx2_psrl_w:
14217     case Intrinsic::x86_avx2_psrl_d:
14218     case Intrinsic::x86_avx2_psrl_q:
14219       Opcode = X86ISD::VSRL;
14220       break;
14221     case Intrinsic::x86_sse2_psra_w:
14222     case Intrinsic::x86_sse2_psra_d:
14223     case Intrinsic::x86_avx2_psra_w:
14224     case Intrinsic::x86_avx2_psra_d:
14225       Opcode = X86ISD::VSRA;
14226       break;
14227     }
14228     return DAG.getNode(Opcode, dl, Op.getValueType(),
14229                        Op.getOperand(1), Op.getOperand(2));
14230   }
14231
14232   // SSE/AVX immediate shift intrinsics
14233   case Intrinsic::x86_sse2_pslli_w:
14234   case Intrinsic::x86_sse2_pslli_d:
14235   case Intrinsic::x86_sse2_pslli_q:
14236   case Intrinsic::x86_avx2_pslli_w:
14237   case Intrinsic::x86_avx2_pslli_d:
14238   case Intrinsic::x86_avx2_pslli_q:
14239   case Intrinsic::x86_sse2_psrli_w:
14240   case Intrinsic::x86_sse2_psrli_d:
14241   case Intrinsic::x86_sse2_psrli_q:
14242   case Intrinsic::x86_avx2_psrli_w:
14243   case Intrinsic::x86_avx2_psrli_d:
14244   case Intrinsic::x86_avx2_psrli_q:
14245   case Intrinsic::x86_sse2_psrai_w:
14246   case Intrinsic::x86_sse2_psrai_d:
14247   case Intrinsic::x86_avx2_psrai_w:
14248   case Intrinsic::x86_avx2_psrai_d: {
14249     unsigned Opcode;
14250     switch (IntNo) {
14251     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14252     case Intrinsic::x86_sse2_pslli_w:
14253     case Intrinsic::x86_sse2_pslli_d:
14254     case Intrinsic::x86_sse2_pslli_q:
14255     case Intrinsic::x86_avx2_pslli_w:
14256     case Intrinsic::x86_avx2_pslli_d:
14257     case Intrinsic::x86_avx2_pslli_q:
14258       Opcode = X86ISD::VSHLI;
14259       break;
14260     case Intrinsic::x86_sse2_psrli_w:
14261     case Intrinsic::x86_sse2_psrli_d:
14262     case Intrinsic::x86_sse2_psrli_q:
14263     case Intrinsic::x86_avx2_psrli_w:
14264     case Intrinsic::x86_avx2_psrli_d:
14265     case Intrinsic::x86_avx2_psrli_q:
14266       Opcode = X86ISD::VSRLI;
14267       break;
14268     case Intrinsic::x86_sse2_psrai_w:
14269     case Intrinsic::x86_sse2_psrai_d:
14270     case Intrinsic::x86_avx2_psrai_w:
14271     case Intrinsic::x86_avx2_psrai_d:
14272       Opcode = X86ISD::VSRAI;
14273       break;
14274     }
14275     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14276                                Op.getOperand(1), Op.getOperand(2), DAG);
14277   }
14278
14279   case Intrinsic::x86_sse42_pcmpistria128:
14280   case Intrinsic::x86_sse42_pcmpestria128:
14281   case Intrinsic::x86_sse42_pcmpistric128:
14282   case Intrinsic::x86_sse42_pcmpestric128:
14283   case Intrinsic::x86_sse42_pcmpistrio128:
14284   case Intrinsic::x86_sse42_pcmpestrio128:
14285   case Intrinsic::x86_sse42_pcmpistris128:
14286   case Intrinsic::x86_sse42_pcmpestris128:
14287   case Intrinsic::x86_sse42_pcmpistriz128:
14288   case Intrinsic::x86_sse42_pcmpestriz128: {
14289     unsigned Opcode;
14290     unsigned X86CC;
14291     switch (IntNo) {
14292     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14293     case Intrinsic::x86_sse42_pcmpistria128:
14294       Opcode = X86ISD::PCMPISTRI;
14295       X86CC = X86::COND_A;
14296       break;
14297     case Intrinsic::x86_sse42_pcmpestria128:
14298       Opcode = X86ISD::PCMPESTRI;
14299       X86CC = X86::COND_A;
14300       break;
14301     case Intrinsic::x86_sse42_pcmpistric128:
14302       Opcode = X86ISD::PCMPISTRI;
14303       X86CC = X86::COND_B;
14304       break;
14305     case Intrinsic::x86_sse42_pcmpestric128:
14306       Opcode = X86ISD::PCMPESTRI;
14307       X86CC = X86::COND_B;
14308       break;
14309     case Intrinsic::x86_sse42_pcmpistrio128:
14310       Opcode = X86ISD::PCMPISTRI;
14311       X86CC = X86::COND_O;
14312       break;
14313     case Intrinsic::x86_sse42_pcmpestrio128:
14314       Opcode = X86ISD::PCMPESTRI;
14315       X86CC = X86::COND_O;
14316       break;
14317     case Intrinsic::x86_sse42_pcmpistris128:
14318       Opcode = X86ISD::PCMPISTRI;
14319       X86CC = X86::COND_S;
14320       break;
14321     case Intrinsic::x86_sse42_pcmpestris128:
14322       Opcode = X86ISD::PCMPESTRI;
14323       X86CC = X86::COND_S;
14324       break;
14325     case Intrinsic::x86_sse42_pcmpistriz128:
14326       Opcode = X86ISD::PCMPISTRI;
14327       X86CC = X86::COND_E;
14328       break;
14329     case Intrinsic::x86_sse42_pcmpestriz128:
14330       Opcode = X86ISD::PCMPESTRI;
14331       X86CC = X86::COND_E;
14332       break;
14333     }
14334     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14335     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14336     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14337     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14338                                 DAG.getConstant(X86CC, MVT::i8),
14339                                 SDValue(PCMP.getNode(), 1));
14340     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14341   }
14342
14343   case Intrinsic::x86_sse42_pcmpistri128:
14344   case Intrinsic::x86_sse42_pcmpestri128: {
14345     unsigned Opcode;
14346     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14347       Opcode = X86ISD::PCMPISTRI;
14348     else
14349       Opcode = X86ISD::PCMPESTRI;
14350
14351     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14352     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14353     return DAG.getNode(Opcode, dl, VTs, NewOps);
14354   }
14355   case Intrinsic::x86_fma_vfmadd_ps:
14356   case Intrinsic::x86_fma_vfmadd_pd:
14357   case Intrinsic::x86_fma_vfmsub_ps:
14358   case Intrinsic::x86_fma_vfmsub_pd:
14359   case Intrinsic::x86_fma_vfnmadd_ps:
14360   case Intrinsic::x86_fma_vfnmadd_pd:
14361   case Intrinsic::x86_fma_vfnmsub_ps:
14362   case Intrinsic::x86_fma_vfnmsub_pd:
14363   case Intrinsic::x86_fma_vfmaddsub_ps:
14364   case Intrinsic::x86_fma_vfmaddsub_pd:
14365   case Intrinsic::x86_fma_vfmsubadd_ps:
14366   case Intrinsic::x86_fma_vfmsubadd_pd:
14367   case Intrinsic::x86_fma_vfmadd_ps_256:
14368   case Intrinsic::x86_fma_vfmadd_pd_256:
14369   case Intrinsic::x86_fma_vfmsub_ps_256:
14370   case Intrinsic::x86_fma_vfmsub_pd_256:
14371   case Intrinsic::x86_fma_vfnmadd_ps_256:
14372   case Intrinsic::x86_fma_vfnmadd_pd_256:
14373   case Intrinsic::x86_fma_vfnmsub_ps_256:
14374   case Intrinsic::x86_fma_vfnmsub_pd_256:
14375   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14376   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14377   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14378   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14379   case Intrinsic::x86_fma_vfmadd_ps_512:
14380   case Intrinsic::x86_fma_vfmadd_pd_512:
14381   case Intrinsic::x86_fma_vfmsub_ps_512:
14382   case Intrinsic::x86_fma_vfmsub_pd_512:
14383   case Intrinsic::x86_fma_vfnmadd_ps_512:
14384   case Intrinsic::x86_fma_vfnmadd_pd_512:
14385   case Intrinsic::x86_fma_vfnmsub_ps_512:
14386   case Intrinsic::x86_fma_vfnmsub_pd_512:
14387   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14388   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14389   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14390   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14391     unsigned Opc;
14392     switch (IntNo) {
14393     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14394     case Intrinsic::x86_fma_vfmadd_ps:
14395     case Intrinsic::x86_fma_vfmadd_pd:
14396     case Intrinsic::x86_fma_vfmadd_ps_256:
14397     case Intrinsic::x86_fma_vfmadd_pd_256:
14398     case Intrinsic::x86_fma_vfmadd_ps_512:
14399     case Intrinsic::x86_fma_vfmadd_pd_512:
14400       Opc = X86ISD::FMADD;
14401       break;
14402     case Intrinsic::x86_fma_vfmsub_ps:
14403     case Intrinsic::x86_fma_vfmsub_pd:
14404     case Intrinsic::x86_fma_vfmsub_ps_256:
14405     case Intrinsic::x86_fma_vfmsub_pd_256:
14406     case Intrinsic::x86_fma_vfmsub_ps_512:
14407     case Intrinsic::x86_fma_vfmsub_pd_512:
14408       Opc = X86ISD::FMSUB;
14409       break;
14410     case Intrinsic::x86_fma_vfnmadd_ps:
14411     case Intrinsic::x86_fma_vfnmadd_pd:
14412     case Intrinsic::x86_fma_vfnmadd_ps_256:
14413     case Intrinsic::x86_fma_vfnmadd_pd_256:
14414     case Intrinsic::x86_fma_vfnmadd_ps_512:
14415     case Intrinsic::x86_fma_vfnmadd_pd_512:
14416       Opc = X86ISD::FNMADD;
14417       break;
14418     case Intrinsic::x86_fma_vfnmsub_ps:
14419     case Intrinsic::x86_fma_vfnmsub_pd:
14420     case Intrinsic::x86_fma_vfnmsub_ps_256:
14421     case Intrinsic::x86_fma_vfnmsub_pd_256:
14422     case Intrinsic::x86_fma_vfnmsub_ps_512:
14423     case Intrinsic::x86_fma_vfnmsub_pd_512:
14424       Opc = X86ISD::FNMSUB;
14425       break;
14426     case Intrinsic::x86_fma_vfmaddsub_ps:
14427     case Intrinsic::x86_fma_vfmaddsub_pd:
14428     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14429     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14430     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14431     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14432       Opc = X86ISD::FMADDSUB;
14433       break;
14434     case Intrinsic::x86_fma_vfmsubadd_ps:
14435     case Intrinsic::x86_fma_vfmsubadd_pd:
14436     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14437     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14438     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14439     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14440       Opc = X86ISD::FMSUBADD;
14441       break;
14442     }
14443
14444     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14445                        Op.getOperand(2), Op.getOperand(3));
14446   }
14447   }
14448 }
14449
14450 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14451                               SDValue Src, SDValue Mask, SDValue Base,
14452                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14453                               const X86Subtarget * Subtarget) {
14454   SDLoc dl(Op);
14455   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14456   assert(C && "Invalid scale type");
14457   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14458   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14459                              Index.getSimpleValueType().getVectorNumElements());
14460   SDValue MaskInReg;
14461   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14462   if (MaskC)
14463     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14464   else
14465     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14466   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14467   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14468   SDValue Segment = DAG.getRegister(0, MVT::i32);
14469   if (Src.getOpcode() == ISD::UNDEF)
14470     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14471   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14472   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14473   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14474   return DAG.getMergeValues(RetOps, dl);
14475 }
14476
14477 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14478                                SDValue Src, SDValue Mask, SDValue Base,
14479                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14480   SDLoc dl(Op);
14481   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14482   assert(C && "Invalid scale type");
14483   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14484   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14485   SDValue Segment = DAG.getRegister(0, MVT::i32);
14486   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14487                              Index.getSimpleValueType().getVectorNumElements());
14488   SDValue MaskInReg;
14489   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14490   if (MaskC)
14491     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14492   else
14493     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14494   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14495   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14496   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14497   return SDValue(Res, 1);
14498 }
14499
14500 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14501                                SDValue Mask, SDValue Base, SDValue Index,
14502                                SDValue ScaleOp, SDValue Chain) {
14503   SDLoc dl(Op);
14504   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14505   assert(C && "Invalid scale type");
14506   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14507   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14508   SDValue Segment = DAG.getRegister(0, MVT::i32);
14509   EVT MaskVT =
14510     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14511   SDValue MaskInReg;
14512   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14513   if (MaskC)
14514     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14515   else
14516     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14517   //SDVTList VTs = DAG.getVTList(MVT::Other);
14518   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14519   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14520   return SDValue(Res, 0);
14521 }
14522
14523 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14524 // read performance monitor counters (x86_rdpmc).
14525 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14526                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14527                               SmallVectorImpl<SDValue> &Results) {
14528   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14529   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14530   SDValue LO, HI;
14531
14532   // The ECX register is used to select the index of the performance counter
14533   // to read.
14534   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14535                                    N->getOperand(2));
14536   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14537
14538   // Reads the content of a 64-bit performance counter and returns it in the
14539   // registers EDX:EAX.
14540   if (Subtarget->is64Bit()) {
14541     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14542     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14543                             LO.getValue(2));
14544   } else {
14545     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14546     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14547                             LO.getValue(2));
14548   }
14549   Chain = HI.getValue(1);
14550
14551   if (Subtarget->is64Bit()) {
14552     // The EAX register is loaded with the low-order 32 bits. The EDX register
14553     // is loaded with the supported high-order bits of the counter.
14554     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14555                               DAG.getConstant(32, MVT::i8));
14556     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14557     Results.push_back(Chain);
14558     return;
14559   }
14560
14561   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14562   SDValue Ops[] = { LO, HI };
14563   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14564   Results.push_back(Pair);
14565   Results.push_back(Chain);
14566 }
14567
14568 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14569 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14570 // also used to custom lower READCYCLECOUNTER nodes.
14571 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14572                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14573                               SmallVectorImpl<SDValue> &Results) {
14574   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14575   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14576   SDValue LO, HI;
14577
14578   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14579   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14580   // and the EAX register is loaded with the low-order 32 bits.
14581   if (Subtarget->is64Bit()) {
14582     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14583     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14584                             LO.getValue(2));
14585   } else {
14586     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14587     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14588                             LO.getValue(2));
14589   }
14590   SDValue Chain = HI.getValue(1);
14591
14592   if (Opcode == X86ISD::RDTSCP_DAG) {
14593     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14594
14595     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14596     // the ECX register. Add 'ecx' explicitly to the chain.
14597     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14598                                      HI.getValue(2));
14599     // Explicitly store the content of ECX at the location passed in input
14600     // to the 'rdtscp' intrinsic.
14601     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14602                          MachinePointerInfo(), false, false, 0);
14603   }
14604
14605   if (Subtarget->is64Bit()) {
14606     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14607     // the EAX register is loaded with the low-order 32 bits.
14608     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14609                               DAG.getConstant(32, MVT::i8));
14610     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14611     Results.push_back(Chain);
14612     return;
14613   }
14614
14615   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14616   SDValue Ops[] = { LO, HI };
14617   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14618   Results.push_back(Pair);
14619   Results.push_back(Chain);
14620 }
14621
14622 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14623                                      SelectionDAG &DAG) {
14624   SmallVector<SDValue, 2> Results;
14625   SDLoc DL(Op);
14626   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14627                           Results);
14628   return DAG.getMergeValues(Results, DL);
14629 }
14630
14631 enum IntrinsicType {
14632   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14633 };
14634
14635 struct IntrinsicData {
14636   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14637     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14638   IntrinsicType Type;
14639   unsigned      Opc0;
14640   unsigned      Opc1;
14641 };
14642
14643 std::map < unsigned, IntrinsicData> IntrMap;
14644 static void InitIntinsicsMap() {
14645   static bool Initialized = false;
14646   if (Initialized) 
14647     return;
14648   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14649                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14650   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14651                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14652   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14653                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14654   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14655                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14656   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14657                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14658   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14659                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14660   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14661                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14662   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14663                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14664   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14665                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14666
14667   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14668                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14669   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14670                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14671   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14672                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14673   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14674                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14675   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14676                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14677   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14678                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14679   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14680                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14681   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14682                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14683    
14684   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14685                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14686                                                         X86::VGATHERPF1QPSm)));
14687   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14688                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14689                                                         X86::VGATHERPF1QPDm)));
14690   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14691                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14692                                                         X86::VGATHERPF1DPDm)));
14693   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14694                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14695                                                         X86::VGATHERPF1DPSm)));
14696   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14697                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14698                                                         X86::VSCATTERPF1QPSm)));
14699   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14700                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14701                                                         X86::VSCATTERPF1QPDm)));
14702   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14703                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14704                                                         X86::VSCATTERPF1DPDm)));
14705   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14706                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14707                                                         X86::VSCATTERPF1DPSm)));
14708   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14709                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14710   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14711                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14712   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14713                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14714   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14715                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14716   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14717                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14718   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14719                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14720   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14721                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14722   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14723                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14724   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14725                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14726   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14727                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
14728   Initialized = true;
14729 }
14730
14731 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14732                                       SelectionDAG &DAG) {
14733   InitIntinsicsMap();
14734   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14735   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14736   if (itr == IntrMap.end())
14737     return SDValue();
14738
14739   SDLoc dl(Op);
14740   IntrinsicData Intr = itr->second;
14741   switch(Intr.Type) {
14742   case RDSEED:
14743   case RDRAND: {
14744     // Emit the node with the right value type.
14745     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14746     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14747
14748     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14749     // Otherwise return the value from Rand, which is always 0, casted to i32.
14750     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14751                       DAG.getConstant(1, Op->getValueType(1)),
14752                       DAG.getConstant(X86::COND_B, MVT::i32),
14753                       SDValue(Result.getNode(), 1) };
14754     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14755                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14756                                   Ops);
14757
14758     // Return { result, isValid, chain }.
14759     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14760                        SDValue(Result.getNode(), 2));
14761   }
14762   case GATHER: {
14763   //gather(v1, mask, index, base, scale);
14764     SDValue Chain = Op.getOperand(0);
14765     SDValue Src   = Op.getOperand(2);
14766     SDValue Base  = Op.getOperand(3);
14767     SDValue Index = Op.getOperand(4);
14768     SDValue Mask  = Op.getOperand(5);
14769     SDValue Scale = Op.getOperand(6);
14770     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14771                           Subtarget);
14772   }
14773   case SCATTER: {
14774   //scatter(base, mask, index, v1, scale);
14775     SDValue Chain = Op.getOperand(0);
14776     SDValue Base  = Op.getOperand(2);
14777     SDValue Mask  = Op.getOperand(3);
14778     SDValue Index = Op.getOperand(4);
14779     SDValue Src   = Op.getOperand(5);
14780     SDValue Scale = Op.getOperand(6);
14781     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14782   }
14783   case PREFETCH: {
14784     SDValue Hint = Op.getOperand(6);
14785     unsigned HintVal;
14786     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14787         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14788       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14789     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14790     SDValue Chain = Op.getOperand(0);
14791     SDValue Mask  = Op.getOperand(2);
14792     SDValue Index = Op.getOperand(3);
14793     SDValue Base  = Op.getOperand(4);
14794     SDValue Scale = Op.getOperand(5);
14795     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14796   }
14797   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14798   case RDTSC: {
14799     SmallVector<SDValue, 2> Results;
14800     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14801     return DAG.getMergeValues(Results, dl);
14802   }
14803   // Read Performance Monitoring Counters.
14804   case RDPMC: {
14805     SmallVector<SDValue, 2> Results;
14806     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14807     return DAG.getMergeValues(Results, dl);
14808   }
14809   // XTEST intrinsics.
14810   case XTEST: {
14811     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14812     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14813     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14814                                 DAG.getConstant(X86::COND_NE, MVT::i8),
14815                                 InTrans);
14816     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14817     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14818                        Ret, SDValue(InTrans.getNode(), 1));
14819   }
14820   }
14821   llvm_unreachable("Unknown Intrinsic Type");
14822 }
14823
14824 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14825                                            SelectionDAG &DAG) const {
14826   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14827   MFI->setReturnAddressIsTaken(true);
14828
14829   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14830     return SDValue();
14831
14832   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14833   SDLoc dl(Op);
14834   EVT PtrVT = getPointerTy();
14835
14836   if (Depth > 0) {
14837     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14838     const X86RegisterInfo *RegInfo =
14839       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14840     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14841     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14842                        DAG.getNode(ISD::ADD, dl, PtrVT,
14843                                    FrameAddr, Offset),
14844                        MachinePointerInfo(), false, false, false, 0);
14845   }
14846
14847   // Just load the return address.
14848   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14849   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14850                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14851 }
14852
14853 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14854   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14855   MFI->setFrameAddressIsTaken(true);
14856
14857   EVT VT = Op.getValueType();
14858   SDLoc dl(Op);  // FIXME probably not meaningful
14859   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14860   const X86RegisterInfo *RegInfo =
14861     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14862   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14863   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14864           (FrameReg == X86::EBP && VT == MVT::i32)) &&
14865          "Invalid Frame Register!");
14866   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14867   while (Depth--)
14868     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14869                             MachinePointerInfo(),
14870                             false, false, false, 0);
14871   return FrameAddr;
14872 }
14873
14874 // FIXME? Maybe this could be a TableGen attribute on some registers and
14875 // this table could be generated automatically from RegInfo.
14876 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14877                                               EVT VT) const {
14878   unsigned Reg = StringSwitch<unsigned>(RegName)
14879                        .Case("esp", X86::ESP)
14880                        .Case("rsp", X86::RSP)
14881                        .Default(0);
14882   if (Reg)
14883     return Reg;
14884   report_fatal_error("Invalid register name global variable");
14885 }
14886
14887 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14888                                                      SelectionDAG &DAG) const {
14889   const X86RegisterInfo *RegInfo =
14890     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14891   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14892 }
14893
14894 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14895   SDValue Chain     = Op.getOperand(0);
14896   SDValue Offset    = Op.getOperand(1);
14897   SDValue Handler   = Op.getOperand(2);
14898   SDLoc dl      (Op);
14899
14900   EVT PtrVT = getPointerTy();
14901   const X86RegisterInfo *RegInfo =
14902     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14903   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14904   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14905           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14906          "Invalid Frame Register!");
14907   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14908   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14909
14910   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14911                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14912   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14913   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14914                        false, false, 0);
14915   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14916
14917   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14918                      DAG.getRegister(StoreAddrReg, PtrVT));
14919 }
14920
14921 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14922                                                SelectionDAG &DAG) const {
14923   SDLoc DL(Op);
14924   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14925                      DAG.getVTList(MVT::i32, MVT::Other),
14926                      Op.getOperand(0), Op.getOperand(1));
14927 }
14928
14929 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14930                                                 SelectionDAG &DAG) const {
14931   SDLoc DL(Op);
14932   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14933                      Op.getOperand(0), Op.getOperand(1));
14934 }
14935
14936 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14937   return Op.getOperand(0);
14938 }
14939
14940 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14941                                                 SelectionDAG &DAG) const {
14942   SDValue Root = Op.getOperand(0);
14943   SDValue Trmp = Op.getOperand(1); // trampoline
14944   SDValue FPtr = Op.getOperand(2); // nested function
14945   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14946   SDLoc dl (Op);
14947
14948   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14949   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14950
14951   if (Subtarget->is64Bit()) {
14952     SDValue OutChains[6];
14953
14954     // Large code-model.
14955     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
14956     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14957
14958     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14959     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14960
14961     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14962
14963     // Load the pointer to the nested function into R11.
14964     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14965     SDValue Addr = Trmp;
14966     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14967                                 Addr, MachinePointerInfo(TrmpAddr),
14968                                 false, false, 0);
14969
14970     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14971                        DAG.getConstant(2, MVT::i64));
14972     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14973                                 MachinePointerInfo(TrmpAddr, 2),
14974                                 false, false, 2);
14975
14976     // Load the 'nest' parameter value into R10.
14977     // R10 is specified in X86CallingConv.td
14978     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14979     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14980                        DAG.getConstant(10, MVT::i64));
14981     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14982                                 Addr, MachinePointerInfo(TrmpAddr, 10),
14983                                 false, false, 0);
14984
14985     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14986                        DAG.getConstant(12, MVT::i64));
14987     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14988                                 MachinePointerInfo(TrmpAddr, 12),
14989                                 false, false, 2);
14990
14991     // Jump to the nested function.
14992     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14993     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14994                        DAG.getConstant(20, MVT::i64));
14995     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14996                                 Addr, MachinePointerInfo(TrmpAddr, 20),
14997                                 false, false, 0);
14998
14999     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15000     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15001                        DAG.getConstant(22, MVT::i64));
15002     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15003                                 MachinePointerInfo(TrmpAddr, 22),
15004                                 false, false, 0);
15005
15006     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15007   } else {
15008     const Function *Func =
15009       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15010     CallingConv::ID CC = Func->getCallingConv();
15011     unsigned NestReg;
15012
15013     switch (CC) {
15014     default:
15015       llvm_unreachable("Unsupported calling convention");
15016     case CallingConv::C:
15017     case CallingConv::X86_StdCall: {
15018       // Pass 'nest' parameter in ECX.
15019       // Must be kept in sync with X86CallingConv.td
15020       NestReg = X86::ECX;
15021
15022       // Check that ECX wasn't needed by an 'inreg' parameter.
15023       FunctionType *FTy = Func->getFunctionType();
15024       const AttributeSet &Attrs = Func->getAttributes();
15025
15026       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15027         unsigned InRegCount = 0;
15028         unsigned Idx = 1;
15029
15030         for (FunctionType::param_iterator I = FTy->param_begin(),
15031              E = FTy->param_end(); I != E; ++I, ++Idx)
15032           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15033             // FIXME: should only count parameters that are lowered to integers.
15034             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15035
15036         if (InRegCount > 2) {
15037           report_fatal_error("Nest register in use - reduce number of inreg"
15038                              " parameters!");
15039         }
15040       }
15041       break;
15042     }
15043     case CallingConv::X86_FastCall:
15044     case CallingConv::X86_ThisCall:
15045     case CallingConv::Fast:
15046       // Pass 'nest' parameter in EAX.
15047       // Must be kept in sync with X86CallingConv.td
15048       NestReg = X86::EAX;
15049       break;
15050     }
15051
15052     SDValue OutChains[4];
15053     SDValue Addr, Disp;
15054
15055     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15056                        DAG.getConstant(10, MVT::i32));
15057     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15058
15059     // This is storing the opcode for MOV32ri.
15060     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15061     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15062     OutChains[0] = DAG.getStore(Root, dl,
15063                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15064                                 Trmp, MachinePointerInfo(TrmpAddr),
15065                                 false, false, 0);
15066
15067     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15068                        DAG.getConstant(1, MVT::i32));
15069     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15070                                 MachinePointerInfo(TrmpAddr, 1),
15071                                 false, false, 1);
15072
15073     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15074     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15075                        DAG.getConstant(5, MVT::i32));
15076     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15077                                 MachinePointerInfo(TrmpAddr, 5),
15078                                 false, false, 1);
15079
15080     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15081                        DAG.getConstant(6, MVT::i32));
15082     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15083                                 MachinePointerInfo(TrmpAddr, 6),
15084                                 false, false, 1);
15085
15086     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15087   }
15088 }
15089
15090 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15091                                             SelectionDAG &DAG) const {
15092   /*
15093    The rounding mode is in bits 11:10 of FPSR, and has the following
15094    settings:
15095      00 Round to nearest
15096      01 Round to -inf
15097      10 Round to +inf
15098      11 Round to 0
15099
15100   FLT_ROUNDS, on the other hand, expects the following:
15101     -1 Undefined
15102      0 Round to 0
15103      1 Round to nearest
15104      2 Round to +inf
15105      3 Round to -inf
15106
15107   To perform the conversion, we do:
15108     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15109   */
15110
15111   MachineFunction &MF = DAG.getMachineFunction();
15112   const TargetMachine &TM = MF.getTarget();
15113   const TargetFrameLowering &TFI = *TM.getFrameLowering();
15114   unsigned StackAlignment = TFI.getStackAlignment();
15115   MVT VT = Op.getSimpleValueType();
15116   SDLoc DL(Op);
15117
15118   // Save FP Control Word to stack slot
15119   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15120   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15121
15122   MachineMemOperand *MMO =
15123    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15124                            MachineMemOperand::MOStore, 2, 2);
15125
15126   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15127   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15128                                           DAG.getVTList(MVT::Other),
15129                                           Ops, MVT::i16, MMO);
15130
15131   // Load FP Control Word from stack slot
15132   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15133                             MachinePointerInfo(), false, false, false, 0);
15134
15135   // Transform as necessary
15136   SDValue CWD1 =
15137     DAG.getNode(ISD::SRL, DL, MVT::i16,
15138                 DAG.getNode(ISD::AND, DL, MVT::i16,
15139                             CWD, DAG.getConstant(0x800, MVT::i16)),
15140                 DAG.getConstant(11, MVT::i8));
15141   SDValue CWD2 =
15142     DAG.getNode(ISD::SRL, DL, MVT::i16,
15143                 DAG.getNode(ISD::AND, DL, MVT::i16,
15144                             CWD, DAG.getConstant(0x400, MVT::i16)),
15145                 DAG.getConstant(9, MVT::i8));
15146
15147   SDValue RetVal =
15148     DAG.getNode(ISD::AND, DL, MVT::i16,
15149                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15150                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15151                             DAG.getConstant(1, MVT::i16)),
15152                 DAG.getConstant(3, MVT::i16));
15153
15154   return DAG.getNode((VT.getSizeInBits() < 16 ?
15155                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15156 }
15157
15158 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15159   MVT VT = Op.getSimpleValueType();
15160   EVT OpVT = VT;
15161   unsigned NumBits = VT.getSizeInBits();
15162   SDLoc dl(Op);
15163
15164   Op = Op.getOperand(0);
15165   if (VT == MVT::i8) {
15166     // Zero extend to i32 since there is not an i8 bsr.
15167     OpVT = MVT::i32;
15168     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15169   }
15170
15171   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15172   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15173   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15174
15175   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15176   SDValue Ops[] = {
15177     Op,
15178     DAG.getConstant(NumBits+NumBits-1, OpVT),
15179     DAG.getConstant(X86::COND_E, MVT::i8),
15180     Op.getValue(1)
15181   };
15182   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15183
15184   // Finally xor with NumBits-1.
15185   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15186
15187   if (VT == MVT::i8)
15188     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15189   return Op;
15190 }
15191
15192 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15193   MVT VT = Op.getSimpleValueType();
15194   EVT OpVT = VT;
15195   unsigned NumBits = VT.getSizeInBits();
15196   SDLoc dl(Op);
15197
15198   Op = Op.getOperand(0);
15199   if (VT == MVT::i8) {
15200     // Zero extend to i32 since there is not an i8 bsr.
15201     OpVT = MVT::i32;
15202     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15203   }
15204
15205   // Issue a bsr (scan bits in reverse).
15206   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15207   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15208
15209   // And xor with NumBits-1.
15210   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15211
15212   if (VT == MVT::i8)
15213     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15214   return Op;
15215 }
15216
15217 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15218   MVT VT = Op.getSimpleValueType();
15219   unsigned NumBits = VT.getSizeInBits();
15220   SDLoc dl(Op);
15221   Op = Op.getOperand(0);
15222
15223   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15224   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15225   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15226
15227   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15228   SDValue Ops[] = {
15229     Op,
15230     DAG.getConstant(NumBits, VT),
15231     DAG.getConstant(X86::COND_E, MVT::i8),
15232     Op.getValue(1)
15233   };
15234   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15235 }
15236
15237 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15238 // ones, and then concatenate the result back.
15239 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15240   MVT VT = Op.getSimpleValueType();
15241
15242   assert(VT.is256BitVector() && VT.isInteger() &&
15243          "Unsupported value type for operation");
15244
15245   unsigned NumElems = VT.getVectorNumElements();
15246   SDLoc dl(Op);
15247
15248   // Extract the LHS vectors
15249   SDValue LHS = Op.getOperand(0);
15250   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15251   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15252
15253   // Extract the RHS vectors
15254   SDValue RHS = Op.getOperand(1);
15255   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15256   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15257
15258   MVT EltVT = VT.getVectorElementType();
15259   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15260
15261   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15262                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15263                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15264 }
15265
15266 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15267   assert(Op.getSimpleValueType().is256BitVector() &&
15268          Op.getSimpleValueType().isInteger() &&
15269          "Only handle AVX 256-bit vector integer operation");
15270   return Lower256IntArith(Op, DAG);
15271 }
15272
15273 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15274   assert(Op.getSimpleValueType().is256BitVector() &&
15275          Op.getSimpleValueType().isInteger() &&
15276          "Only handle AVX 256-bit vector integer operation");
15277   return Lower256IntArith(Op, DAG);
15278 }
15279
15280 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15281                         SelectionDAG &DAG) {
15282   SDLoc dl(Op);
15283   MVT VT = Op.getSimpleValueType();
15284
15285   // Decompose 256-bit ops into smaller 128-bit ops.
15286   if (VT.is256BitVector() && !Subtarget->hasInt256())
15287     return Lower256IntArith(Op, DAG);
15288
15289   SDValue A = Op.getOperand(0);
15290   SDValue B = Op.getOperand(1);
15291
15292   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15293   if (VT == MVT::v4i32) {
15294     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15295            "Should not custom lower when pmuldq is available!");
15296
15297     // Extract the odd parts.
15298     static const int UnpackMask[] = { 1, -1, 3, -1 };
15299     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15300     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15301
15302     // Multiply the even parts.
15303     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15304     // Now multiply odd parts.
15305     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15306
15307     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15308     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15309
15310     // Merge the two vectors back together with a shuffle. This expands into 2
15311     // shuffles.
15312     static const int ShufMask[] = { 0, 4, 2, 6 };
15313     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15314   }
15315
15316   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15317          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15318
15319   //  Ahi = psrlqi(a, 32);
15320   //  Bhi = psrlqi(b, 32);
15321   //
15322   //  AloBlo = pmuludq(a, b);
15323   //  AloBhi = pmuludq(a, Bhi);
15324   //  AhiBlo = pmuludq(Ahi, b);
15325
15326   //  AloBhi = psllqi(AloBhi, 32);
15327   //  AhiBlo = psllqi(AhiBlo, 32);
15328   //  return AloBlo + AloBhi + AhiBlo;
15329
15330   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15331   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15332
15333   // Bit cast to 32-bit vectors for MULUDQ
15334   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15335                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15336   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15337   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15338   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15339   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15340
15341   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15342   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15343   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15344
15345   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15346   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15347
15348   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15349   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15350 }
15351
15352 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15353   assert(Subtarget->isTargetWin64() && "Unexpected target");
15354   EVT VT = Op.getValueType();
15355   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15356          "Unexpected return type for lowering");
15357
15358   RTLIB::Libcall LC;
15359   bool isSigned;
15360   switch (Op->getOpcode()) {
15361   default: llvm_unreachable("Unexpected request for libcall!");
15362   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15363   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15364   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15365   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15366   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15367   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15368   }
15369
15370   SDLoc dl(Op);
15371   SDValue InChain = DAG.getEntryNode();
15372
15373   TargetLowering::ArgListTy Args;
15374   TargetLowering::ArgListEntry Entry;
15375   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15376     EVT ArgVT = Op->getOperand(i).getValueType();
15377     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15378            "Unexpected argument type for lowering");
15379     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15380     Entry.Node = StackPtr;
15381     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15382                            false, false, 16);
15383     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15384     Entry.Ty = PointerType::get(ArgTy,0);
15385     Entry.isSExt = false;
15386     Entry.isZExt = false;
15387     Args.push_back(Entry);
15388   }
15389
15390   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15391                                          getPointerTy());
15392
15393   TargetLowering::CallLoweringInfo CLI(DAG);
15394   CLI.setDebugLoc(dl).setChain(InChain)
15395     .setCallee(getLibcallCallingConv(LC),
15396                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15397                Callee, std::move(Args), 0)
15398     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15399
15400   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15401   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15402 }
15403
15404 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15405                              SelectionDAG &DAG) {
15406   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15407   EVT VT = Op0.getValueType();
15408   SDLoc dl(Op);
15409
15410   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15411          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15412
15413   // PMULxD operations multiply each even value (starting at 0) of LHS with
15414   // the related value of RHS and produce a widen result.
15415   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15416   // => <2 x i64> <ae|cg>
15417   //
15418   // In other word, to have all the results, we need to perform two PMULxD:
15419   // 1. one with the even values.
15420   // 2. one with the odd values.
15421   // To achieve #2, with need to place the odd values at an even position.
15422   //
15423   // Place the odd value at an even position (basically, shift all values 1
15424   // step to the left):
15425   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15426   // <a|b|c|d> => <b|undef|d|undef>
15427   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15428   // <e|f|g|h> => <f|undef|h|undef>
15429   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15430
15431   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15432   // ints.
15433   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15434   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15435   unsigned Opcode =
15436       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15437   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15438   // => <2 x i64> <ae|cg>
15439   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15440                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15441   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15442   // => <2 x i64> <bf|dh>
15443   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15444                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15445
15446   // Shuffle it back into the right order.
15447   SDValue Highs, Lows;
15448   if (VT == MVT::v8i32) {
15449     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15450     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15451     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15452     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15453   } else {
15454     const int HighMask[] = {1, 5, 3, 7};
15455     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15456     const int LowMask[] = {1, 4, 2, 6};
15457     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15458   }
15459
15460   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15461   // unsigned multiply.
15462   if (IsSigned && !Subtarget->hasSSE41()) {
15463     SDValue ShAmt =
15464         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15465     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15466                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15467     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15468                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15469
15470     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15471     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15472   }
15473
15474   // The first result of MUL_LOHI is actually the low value, followed by the
15475   // high value.
15476   SDValue Ops[] = {Lows, Highs};
15477   return DAG.getMergeValues(Ops, dl);
15478 }
15479
15480 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15481                                          const X86Subtarget *Subtarget) {
15482   MVT VT = Op.getSimpleValueType();
15483   SDLoc dl(Op);
15484   SDValue R = Op.getOperand(0);
15485   SDValue Amt = Op.getOperand(1);
15486
15487   // Optimize shl/srl/sra with constant shift amount.
15488   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15489     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15490       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15491
15492       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15493           (Subtarget->hasInt256() &&
15494            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15495           (Subtarget->hasAVX512() &&
15496            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15497         if (Op.getOpcode() == ISD::SHL)
15498           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15499                                             DAG);
15500         if (Op.getOpcode() == ISD::SRL)
15501           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15502                                             DAG);
15503         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15504           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15505                                             DAG);
15506       }
15507
15508       if (VT == MVT::v16i8) {
15509         if (Op.getOpcode() == ISD::SHL) {
15510           // Make a large shift.
15511           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15512                                                    MVT::v8i16, R, ShiftAmt,
15513                                                    DAG);
15514           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15515           // Zero out the rightmost bits.
15516           SmallVector<SDValue, 16> V(16,
15517                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15518                                                      MVT::i8));
15519           return DAG.getNode(ISD::AND, dl, VT, SHL,
15520                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15521         }
15522         if (Op.getOpcode() == ISD::SRL) {
15523           // Make a large shift.
15524           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15525                                                    MVT::v8i16, R, ShiftAmt,
15526                                                    DAG);
15527           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15528           // Zero out the leftmost bits.
15529           SmallVector<SDValue, 16> V(16,
15530                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15531                                                      MVT::i8));
15532           return DAG.getNode(ISD::AND, dl, VT, SRL,
15533                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15534         }
15535         if (Op.getOpcode() == ISD::SRA) {
15536           if (ShiftAmt == 7) {
15537             // R s>> 7  ===  R s< 0
15538             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15539             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15540           }
15541
15542           // R s>> a === ((R u>> a) ^ m) - m
15543           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15544           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15545                                                          MVT::i8));
15546           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15547           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15548           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15549           return Res;
15550         }
15551         llvm_unreachable("Unknown shift opcode.");
15552       }
15553
15554       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15555         if (Op.getOpcode() == ISD::SHL) {
15556           // Make a large shift.
15557           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15558                                                    MVT::v16i16, R, ShiftAmt,
15559                                                    DAG);
15560           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15561           // Zero out the rightmost bits.
15562           SmallVector<SDValue, 32> V(32,
15563                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15564                                                      MVT::i8));
15565           return DAG.getNode(ISD::AND, dl, VT, SHL,
15566                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15567         }
15568         if (Op.getOpcode() == ISD::SRL) {
15569           // Make a large shift.
15570           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15571                                                    MVT::v16i16, R, ShiftAmt,
15572                                                    DAG);
15573           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15574           // Zero out the leftmost bits.
15575           SmallVector<SDValue, 32> V(32,
15576                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15577                                                      MVT::i8));
15578           return DAG.getNode(ISD::AND, dl, VT, SRL,
15579                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15580         }
15581         if (Op.getOpcode() == ISD::SRA) {
15582           if (ShiftAmt == 7) {
15583             // R s>> 7  ===  R s< 0
15584             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15585             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15586           }
15587
15588           // R s>> a === ((R u>> a) ^ m) - m
15589           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15590           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15591                                                          MVT::i8));
15592           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15593           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15594           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15595           return Res;
15596         }
15597         llvm_unreachable("Unknown shift opcode.");
15598       }
15599     }
15600   }
15601
15602   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15603   if (!Subtarget->is64Bit() &&
15604       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15605       Amt.getOpcode() == ISD::BITCAST &&
15606       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15607     Amt = Amt.getOperand(0);
15608     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15609                      VT.getVectorNumElements();
15610     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15611     uint64_t ShiftAmt = 0;
15612     for (unsigned i = 0; i != Ratio; ++i) {
15613       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15614       if (!C)
15615         return SDValue();
15616       // 6 == Log2(64)
15617       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15618     }
15619     // Check remaining shift amounts.
15620     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15621       uint64_t ShAmt = 0;
15622       for (unsigned j = 0; j != Ratio; ++j) {
15623         ConstantSDNode *C =
15624           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15625         if (!C)
15626           return SDValue();
15627         // 6 == Log2(64)
15628         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15629       }
15630       if (ShAmt != ShiftAmt)
15631         return SDValue();
15632     }
15633     switch (Op.getOpcode()) {
15634     default:
15635       llvm_unreachable("Unknown shift opcode!");
15636     case ISD::SHL:
15637       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15638                                         DAG);
15639     case ISD::SRL:
15640       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15641                                         DAG);
15642     case ISD::SRA:
15643       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15644                                         DAG);
15645     }
15646   }
15647
15648   return SDValue();
15649 }
15650
15651 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15652                                         const X86Subtarget* Subtarget) {
15653   MVT VT = Op.getSimpleValueType();
15654   SDLoc dl(Op);
15655   SDValue R = Op.getOperand(0);
15656   SDValue Amt = Op.getOperand(1);
15657
15658   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15659       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15660       (Subtarget->hasInt256() &&
15661        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15662         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15663        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15664     SDValue BaseShAmt;
15665     EVT EltVT = VT.getVectorElementType();
15666
15667     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15668       unsigned NumElts = VT.getVectorNumElements();
15669       unsigned i, j;
15670       for (i = 0; i != NumElts; ++i) {
15671         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15672           continue;
15673         break;
15674       }
15675       for (j = i; j != NumElts; ++j) {
15676         SDValue Arg = Amt.getOperand(j);
15677         if (Arg.getOpcode() == ISD::UNDEF) continue;
15678         if (Arg != Amt.getOperand(i))
15679           break;
15680       }
15681       if (i != NumElts && j == NumElts)
15682         BaseShAmt = Amt.getOperand(i);
15683     } else {
15684       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15685         Amt = Amt.getOperand(0);
15686       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15687                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15688         SDValue InVec = Amt.getOperand(0);
15689         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15690           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15691           unsigned i = 0;
15692           for (; i != NumElts; ++i) {
15693             SDValue Arg = InVec.getOperand(i);
15694             if (Arg.getOpcode() == ISD::UNDEF) continue;
15695             BaseShAmt = Arg;
15696             break;
15697           }
15698         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15699            if (ConstantSDNode *C =
15700                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15701              unsigned SplatIdx =
15702                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15703              if (C->getZExtValue() == SplatIdx)
15704                BaseShAmt = InVec.getOperand(1);
15705            }
15706         }
15707         if (!BaseShAmt.getNode())
15708           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15709                                   DAG.getIntPtrConstant(0));
15710       }
15711     }
15712
15713     if (BaseShAmt.getNode()) {
15714       if (EltVT.bitsGT(MVT::i32))
15715         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15716       else if (EltVT.bitsLT(MVT::i32))
15717         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15718
15719       switch (Op.getOpcode()) {
15720       default:
15721         llvm_unreachable("Unknown shift opcode!");
15722       case ISD::SHL:
15723         switch (VT.SimpleTy) {
15724         default: return SDValue();
15725         case MVT::v2i64:
15726         case MVT::v4i32:
15727         case MVT::v8i16:
15728         case MVT::v4i64:
15729         case MVT::v8i32:
15730         case MVT::v16i16:
15731         case MVT::v16i32:
15732         case MVT::v8i64:
15733           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15734         }
15735       case ISD::SRA:
15736         switch (VT.SimpleTy) {
15737         default: return SDValue();
15738         case MVT::v4i32:
15739         case MVT::v8i16:
15740         case MVT::v8i32:
15741         case MVT::v16i16:
15742         case MVT::v16i32:
15743         case MVT::v8i64:
15744           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15745         }
15746       case ISD::SRL:
15747         switch (VT.SimpleTy) {
15748         default: return SDValue();
15749         case MVT::v2i64:
15750         case MVT::v4i32:
15751         case MVT::v8i16:
15752         case MVT::v4i64:
15753         case MVT::v8i32:
15754         case MVT::v16i16:
15755         case MVT::v16i32:
15756         case MVT::v8i64:
15757           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15758         }
15759       }
15760     }
15761   }
15762
15763   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15764   if (!Subtarget->is64Bit() &&
15765       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15766       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15767       Amt.getOpcode() == ISD::BITCAST &&
15768       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15769     Amt = Amt.getOperand(0);
15770     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15771                      VT.getVectorNumElements();
15772     std::vector<SDValue> Vals(Ratio);
15773     for (unsigned i = 0; i != Ratio; ++i)
15774       Vals[i] = Amt.getOperand(i);
15775     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15776       for (unsigned j = 0; j != Ratio; ++j)
15777         if (Vals[j] != Amt.getOperand(i + j))
15778           return SDValue();
15779     }
15780     switch (Op.getOpcode()) {
15781     default:
15782       llvm_unreachable("Unknown shift opcode!");
15783     case ISD::SHL:
15784       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15785     case ISD::SRL:
15786       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15787     case ISD::SRA:
15788       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15789     }
15790   }
15791
15792   return SDValue();
15793 }
15794
15795 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15796                           SelectionDAG &DAG) {
15797   MVT VT = Op.getSimpleValueType();
15798   SDLoc dl(Op);
15799   SDValue R = Op.getOperand(0);
15800   SDValue Amt = Op.getOperand(1);
15801   SDValue V;
15802
15803   assert(VT.isVector() && "Custom lowering only for vector shifts!");
15804   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15805
15806   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15807   if (V.getNode())
15808     return V;
15809
15810   V = LowerScalarVariableShift(Op, DAG, Subtarget);
15811   if (V.getNode())
15812       return V;
15813
15814   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15815     return Op;
15816   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15817   if (Subtarget->hasInt256()) {
15818     if (Op.getOpcode() == ISD::SRL &&
15819         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15820          VT == MVT::v4i64 || VT == MVT::v8i32))
15821       return Op;
15822     if (Op.getOpcode() == ISD::SHL &&
15823         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15824          VT == MVT::v4i64 || VT == MVT::v8i32))
15825       return Op;
15826     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15827       return Op;
15828   }
15829
15830   // If possible, lower this packed shift into a vector multiply instead of
15831   // expanding it into a sequence of scalar shifts.
15832   // Do this only if the vector shift count is a constant build_vector.
15833   if (Op.getOpcode() == ISD::SHL && 
15834       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15835        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15836       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15837     SmallVector<SDValue, 8> Elts;
15838     EVT SVT = VT.getScalarType();
15839     unsigned SVTBits = SVT.getSizeInBits();
15840     const APInt &One = APInt(SVTBits, 1);
15841     unsigned NumElems = VT.getVectorNumElements();
15842
15843     for (unsigned i=0; i !=NumElems; ++i) {
15844       SDValue Op = Amt->getOperand(i);
15845       if (Op->getOpcode() == ISD::UNDEF) {
15846         Elts.push_back(Op);
15847         continue;
15848       }
15849
15850       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15851       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15852       uint64_t ShAmt = C.getZExtValue();
15853       if (ShAmt >= SVTBits) {
15854         Elts.push_back(DAG.getUNDEF(SVT));
15855         continue;
15856       }
15857       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15858     }
15859     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15860     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15861   }
15862
15863   // Lower SHL with variable shift amount.
15864   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15865     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15866
15867     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15868     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15869     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15870     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15871   }
15872
15873   // If possible, lower this shift as a sequence of two shifts by
15874   // constant plus a MOVSS/MOVSD instead of scalarizing it.
15875   // Example:
15876   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15877   //
15878   // Could be rewritten as:
15879   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15880   //
15881   // The advantage is that the two shifts from the example would be
15882   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15883   // the vector shift into four scalar shifts plus four pairs of vector
15884   // insert/extract.
15885   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15886       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15887     unsigned TargetOpcode = X86ISD::MOVSS;
15888     bool CanBeSimplified;
15889     // The splat value for the first packed shift (the 'X' from the example).
15890     SDValue Amt1 = Amt->getOperand(0);
15891     // The splat value for the second packed shift (the 'Y' from the example).
15892     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15893                                         Amt->getOperand(2);
15894
15895     // See if it is possible to replace this node with a sequence of
15896     // two shifts followed by a MOVSS/MOVSD
15897     if (VT == MVT::v4i32) {
15898       // Check if it is legal to use a MOVSS.
15899       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15900                         Amt2 == Amt->getOperand(3);
15901       if (!CanBeSimplified) {
15902         // Otherwise, check if we can still simplify this node using a MOVSD.
15903         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15904                           Amt->getOperand(2) == Amt->getOperand(3);
15905         TargetOpcode = X86ISD::MOVSD;
15906         Amt2 = Amt->getOperand(2);
15907       }
15908     } else {
15909       // Do similar checks for the case where the machine value type
15910       // is MVT::v8i16.
15911       CanBeSimplified = Amt1 == Amt->getOperand(1);
15912       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15913         CanBeSimplified = Amt2 == Amt->getOperand(i);
15914
15915       if (!CanBeSimplified) {
15916         TargetOpcode = X86ISD::MOVSD;
15917         CanBeSimplified = true;
15918         Amt2 = Amt->getOperand(4);
15919         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15920           CanBeSimplified = Amt1 == Amt->getOperand(i);
15921         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15922           CanBeSimplified = Amt2 == Amt->getOperand(j);
15923       }
15924     }
15925     
15926     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15927         isa<ConstantSDNode>(Amt2)) {
15928       // Replace this node with two shifts followed by a MOVSS/MOVSD.
15929       EVT CastVT = MVT::v4i32;
15930       SDValue Splat1 = 
15931         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15932       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15933       SDValue Splat2 = 
15934         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15935       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15936       if (TargetOpcode == X86ISD::MOVSD)
15937         CastVT = MVT::v2i64;
15938       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15939       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15940       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15941                                             BitCast1, DAG);
15942       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15943     }
15944   }
15945
15946   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15947     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15948
15949     // a = a << 5;
15950     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15951     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15952
15953     // Turn 'a' into a mask suitable for VSELECT
15954     SDValue VSelM = DAG.getConstant(0x80, VT);
15955     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15956     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15957
15958     SDValue CM1 = DAG.getConstant(0x0f, VT);
15959     SDValue CM2 = DAG.getConstant(0x3f, VT);
15960
15961     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15962     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15963     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15964     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15965     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15966
15967     // a += a
15968     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15969     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15970     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15971
15972     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15973     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15974     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15975     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15976     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15977
15978     // a += a
15979     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15980     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15981     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15982
15983     // return VSELECT(r, r+r, a);
15984     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15985                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15986     return R;
15987   }
15988
15989   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15990   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15991   // solution better.
15992   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15993     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15994     unsigned ExtOpc =
15995         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15996     R = DAG.getNode(ExtOpc, dl, NewVT, R);
15997     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15998     return DAG.getNode(ISD::TRUNCATE, dl, VT,
15999                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16000     }
16001
16002   // Decompose 256-bit shifts into smaller 128-bit shifts.
16003   if (VT.is256BitVector()) {
16004     unsigned NumElems = VT.getVectorNumElements();
16005     MVT EltVT = VT.getVectorElementType();
16006     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16007
16008     // Extract the two vectors
16009     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16010     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16011
16012     // Recreate the shift amount vectors
16013     SDValue Amt1, Amt2;
16014     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16015       // Constant shift amount
16016       SmallVector<SDValue, 4> Amt1Csts;
16017       SmallVector<SDValue, 4> Amt2Csts;
16018       for (unsigned i = 0; i != NumElems/2; ++i)
16019         Amt1Csts.push_back(Amt->getOperand(i));
16020       for (unsigned i = NumElems/2; i != NumElems; ++i)
16021         Amt2Csts.push_back(Amt->getOperand(i));
16022
16023       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16024       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16025     } else {
16026       // Variable shift amount
16027       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16028       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16029     }
16030
16031     // Issue new vector shifts for the smaller types
16032     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16033     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16034
16035     // Concatenate the result back
16036     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16037   }
16038
16039   return SDValue();
16040 }
16041
16042 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16043   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16044   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16045   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16046   // has only one use.
16047   SDNode *N = Op.getNode();
16048   SDValue LHS = N->getOperand(0);
16049   SDValue RHS = N->getOperand(1);
16050   unsigned BaseOp = 0;
16051   unsigned Cond = 0;
16052   SDLoc DL(Op);
16053   switch (Op.getOpcode()) {
16054   default: llvm_unreachable("Unknown ovf instruction!");
16055   case ISD::SADDO:
16056     // A subtract of one will be selected as a INC. Note that INC doesn't
16057     // set CF, so we can't do this for UADDO.
16058     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16059       if (C->isOne()) {
16060         BaseOp = X86ISD::INC;
16061         Cond = X86::COND_O;
16062         break;
16063       }
16064     BaseOp = X86ISD::ADD;
16065     Cond = X86::COND_O;
16066     break;
16067   case ISD::UADDO:
16068     BaseOp = X86ISD::ADD;
16069     Cond = X86::COND_B;
16070     break;
16071   case ISD::SSUBO:
16072     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16073     // set CF, so we can't do this for USUBO.
16074     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16075       if (C->isOne()) {
16076         BaseOp = X86ISD::DEC;
16077         Cond = X86::COND_O;
16078         break;
16079       }
16080     BaseOp = X86ISD::SUB;
16081     Cond = X86::COND_O;
16082     break;
16083   case ISD::USUBO:
16084     BaseOp = X86ISD::SUB;
16085     Cond = X86::COND_B;
16086     break;
16087   case ISD::SMULO:
16088     BaseOp = X86ISD::SMUL;
16089     Cond = X86::COND_O;
16090     break;
16091   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16092     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16093                                  MVT::i32);
16094     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16095
16096     SDValue SetCC =
16097       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16098                   DAG.getConstant(X86::COND_O, MVT::i32),
16099                   SDValue(Sum.getNode(), 2));
16100
16101     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16102   }
16103   }
16104
16105   // Also sets EFLAGS.
16106   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16107   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16108
16109   SDValue SetCC =
16110     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16111                 DAG.getConstant(Cond, MVT::i32),
16112                 SDValue(Sum.getNode(), 1));
16113
16114   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16115 }
16116
16117 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16118                                                   SelectionDAG &DAG) const {
16119   SDLoc dl(Op);
16120   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16121   MVT VT = Op.getSimpleValueType();
16122
16123   if (!Subtarget->hasSSE2() || !VT.isVector())
16124     return SDValue();
16125
16126   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16127                       ExtraVT.getScalarType().getSizeInBits();
16128
16129   switch (VT.SimpleTy) {
16130     default: return SDValue();
16131     case MVT::v8i32:
16132     case MVT::v16i16:
16133       if (!Subtarget->hasFp256())
16134         return SDValue();
16135       if (!Subtarget->hasInt256()) {
16136         // needs to be split
16137         unsigned NumElems = VT.getVectorNumElements();
16138
16139         // Extract the LHS vectors
16140         SDValue LHS = Op.getOperand(0);
16141         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16142         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16143
16144         MVT EltVT = VT.getVectorElementType();
16145         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16146
16147         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16148         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16149         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16150                                    ExtraNumElems/2);
16151         SDValue Extra = DAG.getValueType(ExtraVT);
16152
16153         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16154         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16155
16156         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16157       }
16158       // fall through
16159     case MVT::v4i32:
16160     case MVT::v8i16: {
16161       SDValue Op0 = Op.getOperand(0);
16162       SDValue Op00 = Op0.getOperand(0);
16163       SDValue Tmp1;
16164       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16165       if (Op0.getOpcode() == ISD::BITCAST &&
16166           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16167         // (sext (vzext x)) -> (vsext x)
16168         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16169         if (Tmp1.getNode()) {
16170           EVT ExtraEltVT = ExtraVT.getVectorElementType();
16171           // This folding is only valid when the in-reg type is a vector of i8,
16172           // i16, or i32.
16173           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16174               ExtraEltVT == MVT::i32) {
16175             SDValue Tmp1Op0 = Tmp1.getOperand(0);
16176             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16177                    "This optimization is invalid without a VZEXT.");
16178             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16179           }
16180           Op0 = Tmp1;
16181         }
16182       }
16183
16184       // If the above didn't work, then just use Shift-Left + Shift-Right.
16185       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16186                                         DAG);
16187       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16188                                         DAG);
16189     }
16190   }
16191 }
16192
16193 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16194                                  SelectionDAG &DAG) {
16195   SDLoc dl(Op);
16196   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16197     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16198   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16199     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16200
16201   // The only fence that needs an instruction is a sequentially-consistent
16202   // cross-thread fence.
16203   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16204     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16205     // no-sse2). There isn't any reason to disable it if the target processor
16206     // supports it.
16207     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16208       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16209
16210     SDValue Chain = Op.getOperand(0);
16211     SDValue Zero = DAG.getConstant(0, MVT::i32);
16212     SDValue Ops[] = {
16213       DAG.getRegister(X86::ESP, MVT::i32), // Base
16214       DAG.getTargetConstant(1, MVT::i8),   // Scale
16215       DAG.getRegister(0, MVT::i32),        // Index
16216       DAG.getTargetConstant(0, MVT::i32),  // Disp
16217       DAG.getRegister(0, MVT::i32),        // Segment.
16218       Zero,
16219       Chain
16220     };
16221     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16222     return SDValue(Res, 0);
16223   }
16224
16225   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16226   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16227 }
16228
16229 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16230                              SelectionDAG &DAG) {
16231   MVT T = Op.getSimpleValueType();
16232   SDLoc DL(Op);
16233   unsigned Reg = 0;
16234   unsigned size = 0;
16235   switch(T.SimpleTy) {
16236   default: llvm_unreachable("Invalid value type!");
16237   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16238   case MVT::i16: Reg = X86::AX;  size = 2; break;
16239   case MVT::i32: Reg = X86::EAX; size = 4; break;
16240   case MVT::i64:
16241     assert(Subtarget->is64Bit() && "Node not type legal!");
16242     Reg = X86::RAX; size = 8;
16243     break;
16244   }
16245   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16246                                   Op.getOperand(2), SDValue());
16247   SDValue Ops[] = { cpIn.getValue(0),
16248                     Op.getOperand(1),
16249                     Op.getOperand(3),
16250                     DAG.getTargetConstant(size, MVT::i8),
16251                     cpIn.getValue(1) };
16252   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16253   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16254   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16255                                            Ops, T, MMO);
16256
16257   SDValue cpOut =
16258     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16259   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16260                                       MVT::i32, cpOut.getValue(2));
16261   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16262                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16263
16264   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16265   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16266   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16267   return SDValue();
16268 }
16269
16270 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16271                             SelectionDAG &DAG) {
16272   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16273   MVT DstVT = Op.getSimpleValueType();
16274
16275   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16276     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16277     if (DstVT != MVT::f64)
16278       // This conversion needs to be expanded.
16279       return SDValue();
16280
16281     SDValue InVec = Op->getOperand(0);
16282     SDLoc dl(Op);
16283     unsigned NumElts = SrcVT.getVectorNumElements();
16284     EVT SVT = SrcVT.getVectorElementType();
16285
16286     // Widen the vector in input in the case of MVT::v2i32.
16287     // Example: from MVT::v2i32 to MVT::v4i32.
16288     SmallVector<SDValue, 16> Elts;
16289     for (unsigned i = 0, e = NumElts; i != e; ++i)
16290       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16291                                  DAG.getIntPtrConstant(i)));
16292
16293     // Explicitly mark the extra elements as Undef.
16294     SDValue Undef = DAG.getUNDEF(SVT);
16295     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16296       Elts.push_back(Undef);
16297
16298     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16299     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16300     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16301     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16302                        DAG.getIntPtrConstant(0));
16303   }
16304
16305   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16306          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16307   assert((DstVT == MVT::i64 ||
16308           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16309          "Unexpected custom BITCAST");
16310   // i64 <=> MMX conversions are Legal.
16311   if (SrcVT==MVT::i64 && DstVT.isVector())
16312     return Op;
16313   if (DstVT==MVT::i64 && SrcVT.isVector())
16314     return Op;
16315   // MMX <=> MMX conversions are Legal.
16316   if (SrcVT.isVector() && DstVT.isVector())
16317     return Op;
16318   // All other conversions need to be expanded.
16319   return SDValue();
16320 }
16321
16322 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16323   SDNode *Node = Op.getNode();
16324   SDLoc dl(Node);
16325   EVT T = Node->getValueType(0);
16326   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16327                               DAG.getConstant(0, T), Node->getOperand(2));
16328   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16329                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16330                        Node->getOperand(0),
16331                        Node->getOperand(1), negOp,
16332                        cast<AtomicSDNode>(Node)->getMemOperand(),
16333                        cast<AtomicSDNode>(Node)->getOrdering(),
16334                        cast<AtomicSDNode>(Node)->getSynchScope());
16335 }
16336
16337 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16338   SDNode *Node = Op.getNode();
16339   SDLoc dl(Node);
16340   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16341
16342   // Convert seq_cst store -> xchg
16343   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16344   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16345   //        (The only way to get a 16-byte store is cmpxchg16b)
16346   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16347   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16348       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16349     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16350                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16351                                  Node->getOperand(0),
16352                                  Node->getOperand(1), Node->getOperand(2),
16353                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16354                                  cast<AtomicSDNode>(Node)->getOrdering(),
16355                                  cast<AtomicSDNode>(Node)->getSynchScope());
16356     return Swap.getValue(1);
16357   }
16358   // Other atomic stores have a simple pattern.
16359   return Op;
16360 }
16361
16362 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16363   EVT VT = Op.getNode()->getSimpleValueType(0);
16364
16365   // Let legalize expand this if it isn't a legal type yet.
16366   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16367     return SDValue();
16368
16369   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16370
16371   unsigned Opc;
16372   bool ExtraOp = false;
16373   switch (Op.getOpcode()) {
16374   default: llvm_unreachable("Invalid code");
16375   case ISD::ADDC: Opc = X86ISD::ADD; break;
16376   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16377   case ISD::SUBC: Opc = X86ISD::SUB; break;
16378   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16379   }
16380
16381   if (!ExtraOp)
16382     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16383                        Op.getOperand(1));
16384   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16385                      Op.getOperand(1), Op.getOperand(2));
16386 }
16387
16388 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16389                             SelectionDAG &DAG) {
16390   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16391
16392   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16393   // which returns the values as { float, float } (in XMM0) or
16394   // { double, double } (which is returned in XMM0, XMM1).
16395   SDLoc dl(Op);
16396   SDValue Arg = Op.getOperand(0);
16397   EVT ArgVT = Arg.getValueType();
16398   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16399
16400   TargetLowering::ArgListTy Args;
16401   TargetLowering::ArgListEntry Entry;
16402
16403   Entry.Node = Arg;
16404   Entry.Ty = ArgTy;
16405   Entry.isSExt = false;
16406   Entry.isZExt = false;
16407   Args.push_back(Entry);
16408
16409   bool isF64 = ArgVT == MVT::f64;
16410   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16411   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16412   // the results are returned via SRet in memory.
16413   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16414   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16415   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16416
16417   Type *RetTy = isF64
16418     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16419     : (Type*)VectorType::get(ArgTy, 4);
16420
16421   TargetLowering::CallLoweringInfo CLI(DAG);
16422   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16423     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16424
16425   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16426
16427   if (isF64)
16428     // Returned in xmm0 and xmm1.
16429     return CallResult.first;
16430
16431   // Returned in bits 0:31 and 32:64 xmm0.
16432   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16433                                CallResult.first, DAG.getIntPtrConstant(0));
16434   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16435                                CallResult.first, DAG.getIntPtrConstant(1));
16436   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16437   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16438 }
16439
16440 /// LowerOperation - Provide custom lowering hooks for some operations.
16441 ///
16442 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16443   switch (Op.getOpcode()) {
16444   default: llvm_unreachable("Should not custom lower this!");
16445   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16446   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16447   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16448     return LowerCMP_SWAP(Op, Subtarget, DAG);
16449   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16450   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16451   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16452   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16453   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16454   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16455   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16456   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16457   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16458   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16459   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16460   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16461   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16462   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16463   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16464   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16465   case ISD::SHL_PARTS:
16466   case ISD::SRA_PARTS:
16467   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16468   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16469   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16470   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16471   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16472   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16473   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16474   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16475   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16476   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16477   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16478   case ISD::FABS:               return LowerFABS(Op, DAG);
16479   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16480   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16481   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16482   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16483   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16484   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16485   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16486   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16487   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16488   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16489   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16490   case ISD::INTRINSIC_VOID:
16491   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16492   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16493   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16494   case ISD::FRAME_TO_ARGS_OFFSET:
16495                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16496   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16497   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16498   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16499   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16500   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16501   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16502   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16503   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16504   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16505   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16506   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16507   case ISD::UMUL_LOHI:
16508   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16509   case ISD::SRA:
16510   case ISD::SRL:
16511   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16512   case ISD::SADDO:
16513   case ISD::UADDO:
16514   case ISD::SSUBO:
16515   case ISD::USUBO:
16516   case ISD::SMULO:
16517   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16518   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16519   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16520   case ISD::ADDC:
16521   case ISD::ADDE:
16522   case ISD::SUBC:
16523   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16524   case ISD::ADD:                return LowerADD(Op, DAG);
16525   case ISD::SUB:                return LowerSUB(Op, DAG);
16526   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16527   }
16528 }
16529
16530 static void ReplaceATOMIC_LOAD(SDNode *Node,
16531                                SmallVectorImpl<SDValue> &Results,
16532                                SelectionDAG &DAG) {
16533   SDLoc dl(Node);
16534   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16535
16536   // Convert wide load -> cmpxchg8b/cmpxchg16b
16537   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16538   //        (The only way to get a 16-byte load is cmpxchg16b)
16539   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16540   SDValue Zero = DAG.getConstant(0, VT);
16541   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16542   SDValue Swap =
16543       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16544                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16545                            cast<AtomicSDNode>(Node)->getMemOperand(),
16546                            cast<AtomicSDNode>(Node)->getOrdering(),
16547                            cast<AtomicSDNode>(Node)->getOrdering(),
16548                            cast<AtomicSDNode>(Node)->getSynchScope());
16549   Results.push_back(Swap.getValue(0));
16550   Results.push_back(Swap.getValue(2));
16551 }
16552
16553 /// ReplaceNodeResults - Replace a node with an illegal result type
16554 /// with a new node built out of custom code.
16555 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16556                                            SmallVectorImpl<SDValue>&Results,
16557                                            SelectionDAG &DAG) const {
16558   SDLoc dl(N);
16559   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16560   switch (N->getOpcode()) {
16561   default:
16562     llvm_unreachable("Do not know how to custom type legalize this operation!");
16563   case ISD::SIGN_EXTEND_INREG:
16564   case ISD::ADDC:
16565   case ISD::ADDE:
16566   case ISD::SUBC:
16567   case ISD::SUBE:
16568     // We don't want to expand or promote these.
16569     return;
16570   case ISD::SDIV:
16571   case ISD::UDIV:
16572   case ISD::SREM:
16573   case ISD::UREM:
16574   case ISD::SDIVREM:
16575   case ISD::UDIVREM: {
16576     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16577     Results.push_back(V);
16578     return;
16579   }
16580   case ISD::FP_TO_SINT:
16581   case ISD::FP_TO_UINT: {
16582     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16583
16584     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16585       return;
16586
16587     std::pair<SDValue,SDValue> Vals =
16588         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16589     SDValue FIST = Vals.first, StackSlot = Vals.second;
16590     if (FIST.getNode()) {
16591       EVT VT = N->getValueType(0);
16592       // Return a load from the stack slot.
16593       if (StackSlot.getNode())
16594         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16595                                       MachinePointerInfo(),
16596                                       false, false, false, 0));
16597       else
16598         Results.push_back(FIST);
16599     }
16600     return;
16601   }
16602   case ISD::UINT_TO_FP: {
16603     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16604     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16605         N->getValueType(0) != MVT::v2f32)
16606       return;
16607     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16608                                  N->getOperand(0));
16609     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16610                                      MVT::f64);
16611     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16612     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16613                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16614     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16615     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16616     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16617     return;
16618   }
16619   case ISD::FP_ROUND: {
16620     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16621         return;
16622     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16623     Results.push_back(V);
16624     return;
16625   }
16626   case ISD::INTRINSIC_W_CHAIN: {
16627     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16628     switch (IntNo) {
16629     default : llvm_unreachable("Do not know how to custom type "
16630                                "legalize this intrinsic operation!");
16631     case Intrinsic::x86_rdtsc:
16632       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16633                                      Results);
16634     case Intrinsic::x86_rdtscp:
16635       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16636                                      Results);
16637     case Intrinsic::x86_rdpmc:
16638       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16639     }
16640   }
16641   case ISD::READCYCLECOUNTER: {
16642     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16643                                    Results);
16644   }
16645   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16646     EVT T = N->getValueType(0);
16647     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16648     bool Regs64bit = T == MVT::i128;
16649     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16650     SDValue cpInL, cpInH;
16651     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16652                         DAG.getConstant(0, HalfT));
16653     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16654                         DAG.getConstant(1, HalfT));
16655     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16656                              Regs64bit ? X86::RAX : X86::EAX,
16657                              cpInL, SDValue());
16658     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16659                              Regs64bit ? X86::RDX : X86::EDX,
16660                              cpInH, cpInL.getValue(1));
16661     SDValue swapInL, swapInH;
16662     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16663                           DAG.getConstant(0, HalfT));
16664     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16665                           DAG.getConstant(1, HalfT));
16666     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16667                                Regs64bit ? X86::RBX : X86::EBX,
16668                                swapInL, cpInH.getValue(1));
16669     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16670                                Regs64bit ? X86::RCX : X86::ECX,
16671                                swapInH, swapInL.getValue(1));
16672     SDValue Ops[] = { swapInH.getValue(0),
16673                       N->getOperand(1),
16674                       swapInH.getValue(1) };
16675     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16676     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16677     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16678                                   X86ISD::LCMPXCHG8_DAG;
16679     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16680     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16681                                         Regs64bit ? X86::RAX : X86::EAX,
16682                                         HalfT, Result.getValue(1));
16683     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16684                                         Regs64bit ? X86::RDX : X86::EDX,
16685                                         HalfT, cpOutL.getValue(2));
16686     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16687
16688     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16689                                         MVT::i32, cpOutH.getValue(2));
16690     SDValue Success =
16691         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16692                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16693     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16694
16695     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16696     Results.push_back(Success);
16697     Results.push_back(EFLAGS.getValue(1));
16698     return;
16699   }
16700   case ISD::ATOMIC_SWAP:
16701   case ISD::ATOMIC_LOAD_ADD:
16702   case ISD::ATOMIC_LOAD_SUB:
16703   case ISD::ATOMIC_LOAD_AND:
16704   case ISD::ATOMIC_LOAD_OR:
16705   case ISD::ATOMIC_LOAD_XOR:
16706   case ISD::ATOMIC_LOAD_NAND:
16707   case ISD::ATOMIC_LOAD_MIN:
16708   case ISD::ATOMIC_LOAD_MAX:
16709   case ISD::ATOMIC_LOAD_UMIN:
16710   case ISD::ATOMIC_LOAD_UMAX:
16711     // Delegate to generic TypeLegalization. Situations we can really handle
16712     // should have already been dealt with by X86AtomicExpand.cpp.
16713     break;
16714   case ISD::ATOMIC_LOAD: {
16715     ReplaceATOMIC_LOAD(N, Results, DAG);
16716     return;
16717   }
16718   case ISD::BITCAST: {
16719     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16720     EVT DstVT = N->getValueType(0);
16721     EVT SrcVT = N->getOperand(0)->getValueType(0);
16722
16723     if (SrcVT != MVT::f64 ||
16724         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16725       return;
16726
16727     unsigned NumElts = DstVT.getVectorNumElements();
16728     EVT SVT = DstVT.getVectorElementType();
16729     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16730     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16731                                    MVT::v2f64, N->getOperand(0));
16732     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16733
16734     if (ExperimentalVectorWideningLegalization) {
16735       // If we are legalizing vectors by widening, we already have the desired
16736       // legal vector type, just return it.
16737       Results.push_back(ToVecInt);
16738       return;
16739     }
16740
16741     SmallVector<SDValue, 8> Elts;
16742     for (unsigned i = 0, e = NumElts; i != e; ++i)
16743       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16744                                    ToVecInt, DAG.getIntPtrConstant(i)));
16745
16746     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16747   }
16748   }
16749 }
16750
16751 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16752   switch (Opcode) {
16753   default: return nullptr;
16754   case X86ISD::BSF:                return "X86ISD::BSF";
16755   case X86ISD::BSR:                return "X86ISD::BSR";
16756   case X86ISD::SHLD:               return "X86ISD::SHLD";
16757   case X86ISD::SHRD:               return "X86ISD::SHRD";
16758   case X86ISD::FAND:               return "X86ISD::FAND";
16759   case X86ISD::FANDN:              return "X86ISD::FANDN";
16760   case X86ISD::FOR:                return "X86ISD::FOR";
16761   case X86ISD::FXOR:               return "X86ISD::FXOR";
16762   case X86ISD::FSRL:               return "X86ISD::FSRL";
16763   case X86ISD::FILD:               return "X86ISD::FILD";
16764   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16765   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16766   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16767   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16768   case X86ISD::FLD:                return "X86ISD::FLD";
16769   case X86ISD::FST:                return "X86ISD::FST";
16770   case X86ISD::CALL:               return "X86ISD::CALL";
16771   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16772   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16773   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
16774   case X86ISD::BT:                 return "X86ISD::BT";
16775   case X86ISD::CMP:                return "X86ISD::CMP";
16776   case X86ISD::COMI:               return "X86ISD::COMI";
16777   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16778   case X86ISD::CMPM:               return "X86ISD::CMPM";
16779   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16780   case X86ISD::SETCC:              return "X86ISD::SETCC";
16781   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16782   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16783   case X86ISD::CMOV:               return "X86ISD::CMOV";
16784   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16785   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16786   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
16787   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
16788   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
16789   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
16790   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
16791   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
16792   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
16793   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
16794   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
16795   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
16796   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
16797   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
16798   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
16799   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
16800   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
16801   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
16802   case X86ISD::HADD:               return "X86ISD::HADD";
16803   case X86ISD::HSUB:               return "X86ISD::HSUB";
16804   case X86ISD::FHADD:              return "X86ISD::FHADD";
16805   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
16806   case X86ISD::UMAX:               return "X86ISD::UMAX";
16807   case X86ISD::UMIN:               return "X86ISD::UMIN";
16808   case X86ISD::SMAX:               return "X86ISD::SMAX";
16809   case X86ISD::SMIN:               return "X86ISD::SMIN";
16810   case X86ISD::FMAX:               return "X86ISD::FMAX";
16811   case X86ISD::FMIN:               return "X86ISD::FMIN";
16812   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
16813   case X86ISD::FMINC:              return "X86ISD::FMINC";
16814   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
16815   case X86ISD::FRCP:               return "X86ISD::FRCP";
16816   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
16817   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
16818   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
16819   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
16820   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
16821   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
16822   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
16823   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
16824   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
16825   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
16826   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
16827   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
16828   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
16829   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
16830   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
16831   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
16832   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
16833   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
16834   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
16835   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
16836   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
16837   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
16838   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
16839   case X86ISD::VSHL:               return "X86ISD::VSHL";
16840   case X86ISD::VSRL:               return "X86ISD::VSRL";
16841   case X86ISD::VSRA:               return "X86ISD::VSRA";
16842   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
16843   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
16844   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
16845   case X86ISD::CMPP:               return "X86ISD::CMPP";
16846   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
16847   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
16848   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
16849   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
16850   case X86ISD::ADD:                return "X86ISD::ADD";
16851   case X86ISD::SUB:                return "X86ISD::SUB";
16852   case X86ISD::ADC:                return "X86ISD::ADC";
16853   case X86ISD::SBB:                return "X86ISD::SBB";
16854   case X86ISD::SMUL:               return "X86ISD::SMUL";
16855   case X86ISD::UMUL:               return "X86ISD::UMUL";
16856   case X86ISD::INC:                return "X86ISD::INC";
16857   case X86ISD::DEC:                return "X86ISD::DEC";
16858   case X86ISD::OR:                 return "X86ISD::OR";
16859   case X86ISD::XOR:                return "X86ISD::XOR";
16860   case X86ISD::AND:                return "X86ISD::AND";
16861   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
16862   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
16863   case X86ISD::PTEST:              return "X86ISD::PTEST";
16864   case X86ISD::TESTP:              return "X86ISD::TESTP";
16865   case X86ISD::TESTM:              return "X86ISD::TESTM";
16866   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
16867   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
16868   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
16869   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
16870   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
16871   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
16872   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
16873   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
16874   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
16875   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
16876   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
16877   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
16878   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
16879   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
16880   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
16881   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
16882   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
16883   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
16884   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
16885   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
16886   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
16887   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
16888   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
16889   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
16890   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
16891   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
16892   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
16893   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
16894   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
16895   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
16896   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
16897   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
16898   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16899   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
16900   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
16901   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
16902   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
16903   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
16904   case X86ISD::SAHF:               return "X86ISD::SAHF";
16905   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
16906   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
16907   case X86ISD::FMADD:              return "X86ISD::FMADD";
16908   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
16909   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
16910   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
16911   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
16912   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
16913   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
16914   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
16915   case X86ISD::XTEST:              return "X86ISD::XTEST";
16916   }
16917 }
16918
16919 // isLegalAddressingMode - Return true if the addressing mode represented
16920 // by AM is legal for this target, for a load/store of the specified type.
16921 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16922                                               Type *Ty) const {
16923   // X86 supports extremely general addressing modes.
16924   CodeModel::Model M = getTargetMachine().getCodeModel();
16925   Reloc::Model R = getTargetMachine().getRelocationModel();
16926
16927   // X86 allows a sign-extended 32-bit immediate field as a displacement.
16928   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16929     return false;
16930
16931   if (AM.BaseGV) {
16932     unsigned GVFlags =
16933       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16934
16935     // If a reference to this global requires an extra load, we can't fold it.
16936     if (isGlobalStubReference(GVFlags))
16937       return false;
16938
16939     // If BaseGV requires a register for the PIC base, we cannot also have a
16940     // BaseReg specified.
16941     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16942       return false;
16943
16944     // If lower 4G is not available, then we must use rip-relative addressing.
16945     if ((M != CodeModel::Small || R != Reloc::Static) &&
16946         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16947       return false;
16948   }
16949
16950   switch (AM.Scale) {
16951   case 0:
16952   case 1:
16953   case 2:
16954   case 4:
16955   case 8:
16956     // These scales always work.
16957     break;
16958   case 3:
16959   case 5:
16960   case 9:
16961     // These scales are formed with basereg+scalereg.  Only accept if there is
16962     // no basereg yet.
16963     if (AM.HasBaseReg)
16964       return false;
16965     break;
16966   default:  // Other stuff never works.
16967     return false;
16968   }
16969
16970   return true;
16971 }
16972
16973 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16974   unsigned Bits = Ty->getScalarSizeInBits();
16975
16976   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16977   // particularly cheaper than those without.
16978   if (Bits == 8)
16979     return false;
16980
16981   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16982   // variable shifts just as cheap as scalar ones.
16983   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16984     return false;
16985
16986   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16987   // fully general vector.
16988   return true;
16989 }
16990
16991 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16992   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16993     return false;
16994   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16995   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16996   return NumBits1 > NumBits2;
16997 }
16998
16999 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17000   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17001     return false;
17002
17003   if (!isTypeLegal(EVT::getEVT(Ty1)))
17004     return false;
17005
17006   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17007
17008   // Assuming the caller doesn't have a zeroext or signext return parameter,
17009   // truncation all the way down to i1 is valid.
17010   return true;
17011 }
17012
17013 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17014   return isInt<32>(Imm);
17015 }
17016
17017 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17018   // Can also use sub to handle negated immediates.
17019   return isInt<32>(Imm);
17020 }
17021
17022 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17023   if (!VT1.isInteger() || !VT2.isInteger())
17024     return false;
17025   unsigned NumBits1 = VT1.getSizeInBits();
17026   unsigned NumBits2 = VT2.getSizeInBits();
17027   return NumBits1 > NumBits2;
17028 }
17029
17030 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17031   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17032   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17033 }
17034
17035 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17036   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17037   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17038 }
17039
17040 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17041   EVT VT1 = Val.getValueType();
17042   if (isZExtFree(VT1, VT2))
17043     return true;
17044
17045   if (Val.getOpcode() != ISD::LOAD)
17046     return false;
17047
17048   if (!VT1.isSimple() || !VT1.isInteger() ||
17049       !VT2.isSimple() || !VT2.isInteger())
17050     return false;
17051
17052   switch (VT1.getSimpleVT().SimpleTy) {
17053   default: break;
17054   case MVT::i8:
17055   case MVT::i16:
17056   case MVT::i32:
17057     // X86 has 8, 16, and 32-bit zero-extending loads.
17058     return true;
17059   }
17060
17061   return false;
17062 }
17063
17064 bool
17065 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17066   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17067     return false;
17068
17069   VT = VT.getScalarType();
17070
17071   if (!VT.isSimple())
17072     return false;
17073
17074   switch (VT.getSimpleVT().SimpleTy) {
17075   case MVT::f32:
17076   case MVT::f64:
17077     return true;
17078   default:
17079     break;
17080   }
17081
17082   return false;
17083 }
17084
17085 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17086   // i16 instructions are longer (0x66 prefix) and potentially slower.
17087   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17088 }
17089
17090 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17091 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17092 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17093 /// are assumed to be legal.
17094 bool
17095 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17096                                       EVT VT) const {
17097   if (!VT.isSimple())
17098     return false;
17099
17100   MVT SVT = VT.getSimpleVT();
17101
17102   // Very little shuffling can be done for 64-bit vectors right now.
17103   if (VT.getSizeInBits() == 64)
17104     return false;
17105
17106   // If this is a single-input shuffle with no 128 bit lane crossings we can
17107   // lower it into pshufb.
17108   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17109       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17110     bool isLegal = true;
17111     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17112       if (M[I] >= (int)SVT.getVectorNumElements() ||
17113           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17114         isLegal = false;
17115         break;
17116       }
17117     }
17118     if (isLegal)
17119       return true;
17120   }
17121
17122   // FIXME: blends, shifts.
17123   return (SVT.getVectorNumElements() == 2 ||
17124           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17125           isMOVLMask(M, SVT) ||
17126           isMOVHLPSMask(M, SVT) ||
17127           isSHUFPMask(M, SVT) ||
17128           isPSHUFDMask(M, SVT) ||
17129           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17130           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17131           isPALIGNRMask(M, SVT, Subtarget) ||
17132           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17133           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17134           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17135           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17136           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17137 }
17138
17139 bool
17140 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17141                                           EVT VT) const {
17142   if (!VT.isSimple())
17143     return false;
17144
17145   MVT SVT = VT.getSimpleVT();
17146   unsigned NumElts = SVT.getVectorNumElements();
17147   // FIXME: This collection of masks seems suspect.
17148   if (NumElts == 2)
17149     return true;
17150   if (NumElts == 4 && SVT.is128BitVector()) {
17151     return (isMOVLMask(Mask, SVT)  ||
17152             isCommutedMOVLMask(Mask, SVT, true) ||
17153             isSHUFPMask(Mask, SVT) ||
17154             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17155   }
17156   return false;
17157 }
17158
17159 //===----------------------------------------------------------------------===//
17160 //                           X86 Scheduler Hooks
17161 //===----------------------------------------------------------------------===//
17162
17163 /// Utility function to emit xbegin specifying the start of an RTM region.
17164 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17165                                      const TargetInstrInfo *TII) {
17166   DebugLoc DL = MI->getDebugLoc();
17167
17168   const BasicBlock *BB = MBB->getBasicBlock();
17169   MachineFunction::iterator I = MBB;
17170   ++I;
17171
17172   // For the v = xbegin(), we generate
17173   //
17174   // thisMBB:
17175   //  xbegin sinkMBB
17176   //
17177   // mainMBB:
17178   //  eax = -1
17179   //
17180   // sinkMBB:
17181   //  v = eax
17182
17183   MachineBasicBlock *thisMBB = MBB;
17184   MachineFunction *MF = MBB->getParent();
17185   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17186   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17187   MF->insert(I, mainMBB);
17188   MF->insert(I, sinkMBB);
17189
17190   // Transfer the remainder of BB and its successor edges to sinkMBB.
17191   sinkMBB->splice(sinkMBB->begin(), MBB,
17192                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17193   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17194
17195   // thisMBB:
17196   //  xbegin sinkMBB
17197   //  # fallthrough to mainMBB
17198   //  # abortion to sinkMBB
17199   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17200   thisMBB->addSuccessor(mainMBB);
17201   thisMBB->addSuccessor(sinkMBB);
17202
17203   // mainMBB:
17204   //  EAX = -1
17205   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17206   mainMBB->addSuccessor(sinkMBB);
17207
17208   // sinkMBB:
17209   // EAX is live into the sinkMBB
17210   sinkMBB->addLiveIn(X86::EAX);
17211   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17212           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17213     .addReg(X86::EAX);
17214
17215   MI->eraseFromParent();
17216   return sinkMBB;
17217 }
17218
17219 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17220 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17221 // in the .td file.
17222 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17223                                        const TargetInstrInfo *TII) {
17224   unsigned Opc;
17225   switch (MI->getOpcode()) {
17226   default: llvm_unreachable("illegal opcode!");
17227   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17228   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17229   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17230   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17231   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17232   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17233   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17234   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17235   }
17236
17237   DebugLoc dl = MI->getDebugLoc();
17238   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17239
17240   unsigned NumArgs = MI->getNumOperands();
17241   for (unsigned i = 1; i < NumArgs; ++i) {
17242     MachineOperand &Op = MI->getOperand(i);
17243     if (!(Op.isReg() && Op.isImplicit()))
17244       MIB.addOperand(Op);
17245   }
17246   if (MI->hasOneMemOperand())
17247     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17248
17249   BuildMI(*BB, MI, dl,
17250     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17251     .addReg(X86::XMM0);
17252
17253   MI->eraseFromParent();
17254   return BB;
17255 }
17256
17257 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17258 // defs in an instruction pattern
17259 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17260                                        const TargetInstrInfo *TII) {
17261   unsigned Opc;
17262   switch (MI->getOpcode()) {
17263   default: llvm_unreachable("illegal opcode!");
17264   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17265   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17266   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17267   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17268   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17269   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17270   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17271   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17272   }
17273
17274   DebugLoc dl = MI->getDebugLoc();
17275   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17276
17277   unsigned NumArgs = MI->getNumOperands(); // remove the results
17278   for (unsigned i = 1; i < NumArgs; ++i) {
17279     MachineOperand &Op = MI->getOperand(i);
17280     if (!(Op.isReg() && Op.isImplicit()))
17281       MIB.addOperand(Op);
17282   }
17283   if (MI->hasOneMemOperand())
17284     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17285
17286   BuildMI(*BB, MI, dl,
17287     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17288     .addReg(X86::ECX);
17289
17290   MI->eraseFromParent();
17291   return BB;
17292 }
17293
17294 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17295                                        const TargetInstrInfo *TII,
17296                                        const X86Subtarget* Subtarget) {
17297   DebugLoc dl = MI->getDebugLoc();
17298
17299   // Address into RAX/EAX, other two args into ECX, EDX.
17300   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17301   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17302   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17303   for (int i = 0; i < X86::AddrNumOperands; ++i)
17304     MIB.addOperand(MI->getOperand(i));
17305
17306   unsigned ValOps = X86::AddrNumOperands;
17307   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17308     .addReg(MI->getOperand(ValOps).getReg());
17309   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17310     .addReg(MI->getOperand(ValOps+1).getReg());
17311
17312   // The instruction doesn't actually take any operands though.
17313   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17314
17315   MI->eraseFromParent(); // The pseudo is gone now.
17316   return BB;
17317 }
17318
17319 MachineBasicBlock *
17320 X86TargetLowering::EmitVAARG64WithCustomInserter(
17321                    MachineInstr *MI,
17322                    MachineBasicBlock *MBB) const {
17323   // Emit va_arg instruction on X86-64.
17324
17325   // Operands to this pseudo-instruction:
17326   // 0  ) Output        : destination address (reg)
17327   // 1-5) Input         : va_list address (addr, i64mem)
17328   // 6  ) ArgSize       : Size (in bytes) of vararg type
17329   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17330   // 8  ) Align         : Alignment of type
17331   // 9  ) EFLAGS (implicit-def)
17332
17333   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17334   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17335
17336   unsigned DestReg = MI->getOperand(0).getReg();
17337   MachineOperand &Base = MI->getOperand(1);
17338   MachineOperand &Scale = MI->getOperand(2);
17339   MachineOperand &Index = MI->getOperand(3);
17340   MachineOperand &Disp = MI->getOperand(4);
17341   MachineOperand &Segment = MI->getOperand(5);
17342   unsigned ArgSize = MI->getOperand(6).getImm();
17343   unsigned ArgMode = MI->getOperand(7).getImm();
17344   unsigned Align = MI->getOperand(8).getImm();
17345
17346   // Memory Reference
17347   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17348   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17349   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17350
17351   // Machine Information
17352   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17353   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17354   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17355   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17356   DebugLoc DL = MI->getDebugLoc();
17357
17358   // struct va_list {
17359   //   i32   gp_offset
17360   //   i32   fp_offset
17361   //   i64   overflow_area (address)
17362   //   i64   reg_save_area (address)
17363   // }
17364   // sizeof(va_list) = 24
17365   // alignment(va_list) = 8
17366
17367   unsigned TotalNumIntRegs = 6;
17368   unsigned TotalNumXMMRegs = 8;
17369   bool UseGPOffset = (ArgMode == 1);
17370   bool UseFPOffset = (ArgMode == 2);
17371   unsigned MaxOffset = TotalNumIntRegs * 8 +
17372                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17373
17374   /* Align ArgSize to a multiple of 8 */
17375   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17376   bool NeedsAlign = (Align > 8);
17377
17378   MachineBasicBlock *thisMBB = MBB;
17379   MachineBasicBlock *overflowMBB;
17380   MachineBasicBlock *offsetMBB;
17381   MachineBasicBlock *endMBB;
17382
17383   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17384   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17385   unsigned OffsetReg = 0;
17386
17387   if (!UseGPOffset && !UseFPOffset) {
17388     // If we only pull from the overflow region, we don't create a branch.
17389     // We don't need to alter control flow.
17390     OffsetDestReg = 0; // unused
17391     OverflowDestReg = DestReg;
17392
17393     offsetMBB = nullptr;
17394     overflowMBB = thisMBB;
17395     endMBB = thisMBB;
17396   } else {
17397     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17398     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17399     // If not, pull from overflow_area. (branch to overflowMBB)
17400     //
17401     //       thisMBB
17402     //         |     .
17403     //         |        .
17404     //     offsetMBB   overflowMBB
17405     //         |        .
17406     //         |     .
17407     //        endMBB
17408
17409     // Registers for the PHI in endMBB
17410     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17411     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17412
17413     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17414     MachineFunction *MF = MBB->getParent();
17415     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17416     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17417     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17418
17419     MachineFunction::iterator MBBIter = MBB;
17420     ++MBBIter;
17421
17422     // Insert the new basic blocks
17423     MF->insert(MBBIter, offsetMBB);
17424     MF->insert(MBBIter, overflowMBB);
17425     MF->insert(MBBIter, endMBB);
17426
17427     // Transfer the remainder of MBB and its successor edges to endMBB.
17428     endMBB->splice(endMBB->begin(), thisMBB,
17429                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17430     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17431
17432     // Make offsetMBB and overflowMBB successors of thisMBB
17433     thisMBB->addSuccessor(offsetMBB);
17434     thisMBB->addSuccessor(overflowMBB);
17435
17436     // endMBB is a successor of both offsetMBB and overflowMBB
17437     offsetMBB->addSuccessor(endMBB);
17438     overflowMBB->addSuccessor(endMBB);
17439
17440     // Load the offset value into a register
17441     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17442     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17443       .addOperand(Base)
17444       .addOperand(Scale)
17445       .addOperand(Index)
17446       .addDisp(Disp, UseFPOffset ? 4 : 0)
17447       .addOperand(Segment)
17448       .setMemRefs(MMOBegin, MMOEnd);
17449
17450     // Check if there is enough room left to pull this argument.
17451     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17452       .addReg(OffsetReg)
17453       .addImm(MaxOffset + 8 - ArgSizeA8);
17454
17455     // Branch to "overflowMBB" if offset >= max
17456     // Fall through to "offsetMBB" otherwise
17457     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17458       .addMBB(overflowMBB);
17459   }
17460
17461   // In offsetMBB, emit code to use the reg_save_area.
17462   if (offsetMBB) {
17463     assert(OffsetReg != 0);
17464
17465     // Read the reg_save_area address.
17466     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17467     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17468       .addOperand(Base)
17469       .addOperand(Scale)
17470       .addOperand(Index)
17471       .addDisp(Disp, 16)
17472       .addOperand(Segment)
17473       .setMemRefs(MMOBegin, MMOEnd);
17474
17475     // Zero-extend the offset
17476     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17477       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17478         .addImm(0)
17479         .addReg(OffsetReg)
17480         .addImm(X86::sub_32bit);
17481
17482     // Add the offset to the reg_save_area to get the final address.
17483     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17484       .addReg(OffsetReg64)
17485       .addReg(RegSaveReg);
17486
17487     // Compute the offset for the next argument
17488     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17489     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17490       .addReg(OffsetReg)
17491       .addImm(UseFPOffset ? 16 : 8);
17492
17493     // Store it back into the va_list.
17494     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17495       .addOperand(Base)
17496       .addOperand(Scale)
17497       .addOperand(Index)
17498       .addDisp(Disp, UseFPOffset ? 4 : 0)
17499       .addOperand(Segment)
17500       .addReg(NextOffsetReg)
17501       .setMemRefs(MMOBegin, MMOEnd);
17502
17503     // Jump to endMBB
17504     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17505       .addMBB(endMBB);
17506   }
17507
17508   //
17509   // Emit code to use overflow area
17510   //
17511
17512   // Load the overflow_area address into a register.
17513   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17514   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17515     .addOperand(Base)
17516     .addOperand(Scale)
17517     .addOperand(Index)
17518     .addDisp(Disp, 8)
17519     .addOperand(Segment)
17520     .setMemRefs(MMOBegin, MMOEnd);
17521
17522   // If we need to align it, do so. Otherwise, just copy the address
17523   // to OverflowDestReg.
17524   if (NeedsAlign) {
17525     // Align the overflow address
17526     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17527     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17528
17529     // aligned_addr = (addr + (align-1)) & ~(align-1)
17530     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17531       .addReg(OverflowAddrReg)
17532       .addImm(Align-1);
17533
17534     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17535       .addReg(TmpReg)
17536       .addImm(~(uint64_t)(Align-1));
17537   } else {
17538     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17539       .addReg(OverflowAddrReg);
17540   }
17541
17542   // Compute the next overflow address after this argument.
17543   // (the overflow address should be kept 8-byte aligned)
17544   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17545   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17546     .addReg(OverflowDestReg)
17547     .addImm(ArgSizeA8);
17548
17549   // Store the new overflow address.
17550   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17551     .addOperand(Base)
17552     .addOperand(Scale)
17553     .addOperand(Index)
17554     .addDisp(Disp, 8)
17555     .addOperand(Segment)
17556     .addReg(NextAddrReg)
17557     .setMemRefs(MMOBegin, MMOEnd);
17558
17559   // If we branched, emit the PHI to the front of endMBB.
17560   if (offsetMBB) {
17561     BuildMI(*endMBB, endMBB->begin(), DL,
17562             TII->get(X86::PHI), DestReg)
17563       .addReg(OffsetDestReg).addMBB(offsetMBB)
17564       .addReg(OverflowDestReg).addMBB(overflowMBB);
17565   }
17566
17567   // Erase the pseudo instruction
17568   MI->eraseFromParent();
17569
17570   return endMBB;
17571 }
17572
17573 MachineBasicBlock *
17574 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17575                                                  MachineInstr *MI,
17576                                                  MachineBasicBlock *MBB) const {
17577   // Emit code to save XMM registers to the stack. The ABI says that the
17578   // number of registers to save is given in %al, so it's theoretically
17579   // possible to do an indirect jump trick to avoid saving all of them,
17580   // however this code takes a simpler approach and just executes all
17581   // of the stores if %al is non-zero. It's less code, and it's probably
17582   // easier on the hardware branch predictor, and stores aren't all that
17583   // expensive anyway.
17584
17585   // Create the new basic blocks. One block contains all the XMM stores,
17586   // and one block is the final destination regardless of whether any
17587   // stores were performed.
17588   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17589   MachineFunction *F = MBB->getParent();
17590   MachineFunction::iterator MBBIter = MBB;
17591   ++MBBIter;
17592   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17593   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17594   F->insert(MBBIter, XMMSaveMBB);
17595   F->insert(MBBIter, EndMBB);
17596
17597   // Transfer the remainder of MBB and its successor edges to EndMBB.
17598   EndMBB->splice(EndMBB->begin(), MBB,
17599                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17600   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17601
17602   // The original block will now fall through to the XMM save block.
17603   MBB->addSuccessor(XMMSaveMBB);
17604   // The XMMSaveMBB will fall through to the end block.
17605   XMMSaveMBB->addSuccessor(EndMBB);
17606
17607   // Now add the instructions.
17608   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17609   DebugLoc DL = MI->getDebugLoc();
17610
17611   unsigned CountReg = MI->getOperand(0).getReg();
17612   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17613   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17614
17615   if (!Subtarget->isTargetWin64()) {
17616     // If %al is 0, branch around the XMM save block.
17617     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17618     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17619     MBB->addSuccessor(EndMBB);
17620   }
17621
17622   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17623   // that was just emitted, but clearly shouldn't be "saved".
17624   assert((MI->getNumOperands() <= 3 ||
17625           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17626           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17627          && "Expected last argument to be EFLAGS");
17628   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17629   // In the XMM save block, save all the XMM argument registers.
17630   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17631     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17632     MachineMemOperand *MMO =
17633       F->getMachineMemOperand(
17634           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17635         MachineMemOperand::MOStore,
17636         /*Size=*/16, /*Align=*/16);
17637     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17638       .addFrameIndex(RegSaveFrameIndex)
17639       .addImm(/*Scale=*/1)
17640       .addReg(/*IndexReg=*/0)
17641       .addImm(/*Disp=*/Offset)
17642       .addReg(/*Segment=*/0)
17643       .addReg(MI->getOperand(i).getReg())
17644       .addMemOperand(MMO);
17645   }
17646
17647   MI->eraseFromParent();   // The pseudo instruction is gone now.
17648
17649   return EndMBB;
17650 }
17651
17652 // The EFLAGS operand of SelectItr might be missing a kill marker
17653 // because there were multiple uses of EFLAGS, and ISel didn't know
17654 // which to mark. Figure out whether SelectItr should have had a
17655 // kill marker, and set it if it should. Returns the correct kill
17656 // marker value.
17657 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17658                                      MachineBasicBlock* BB,
17659                                      const TargetRegisterInfo* TRI) {
17660   // Scan forward through BB for a use/def of EFLAGS.
17661   MachineBasicBlock::iterator miI(std::next(SelectItr));
17662   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17663     const MachineInstr& mi = *miI;
17664     if (mi.readsRegister(X86::EFLAGS))
17665       return false;
17666     if (mi.definesRegister(X86::EFLAGS))
17667       break; // Should have kill-flag - update below.
17668   }
17669
17670   // If we hit the end of the block, check whether EFLAGS is live into a
17671   // successor.
17672   if (miI == BB->end()) {
17673     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17674                                           sEnd = BB->succ_end();
17675          sItr != sEnd; ++sItr) {
17676       MachineBasicBlock* succ = *sItr;
17677       if (succ->isLiveIn(X86::EFLAGS))
17678         return false;
17679     }
17680   }
17681
17682   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17683   // out. SelectMI should have a kill flag on EFLAGS.
17684   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17685   return true;
17686 }
17687
17688 MachineBasicBlock *
17689 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17690                                      MachineBasicBlock *BB) const {
17691   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17692   DebugLoc DL = MI->getDebugLoc();
17693
17694   // To "insert" a SELECT_CC instruction, we actually have to insert the
17695   // diamond control-flow pattern.  The incoming instruction knows the
17696   // destination vreg to set, the condition code register to branch on, the
17697   // true/false values to select between, and a branch opcode to use.
17698   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17699   MachineFunction::iterator It = BB;
17700   ++It;
17701
17702   //  thisMBB:
17703   //  ...
17704   //   TrueVal = ...
17705   //   cmpTY ccX, r1, r2
17706   //   bCC copy1MBB
17707   //   fallthrough --> copy0MBB
17708   MachineBasicBlock *thisMBB = BB;
17709   MachineFunction *F = BB->getParent();
17710   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17711   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17712   F->insert(It, copy0MBB);
17713   F->insert(It, sinkMBB);
17714
17715   // If the EFLAGS register isn't dead in the terminator, then claim that it's
17716   // live into the sink and copy blocks.
17717   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17718   if (!MI->killsRegister(X86::EFLAGS) &&
17719       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17720     copy0MBB->addLiveIn(X86::EFLAGS);
17721     sinkMBB->addLiveIn(X86::EFLAGS);
17722   }
17723
17724   // Transfer the remainder of BB and its successor edges to sinkMBB.
17725   sinkMBB->splice(sinkMBB->begin(), BB,
17726                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
17727   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17728
17729   // Add the true and fallthrough blocks as its successors.
17730   BB->addSuccessor(copy0MBB);
17731   BB->addSuccessor(sinkMBB);
17732
17733   // Create the conditional branch instruction.
17734   unsigned Opc =
17735     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17736   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17737
17738   //  copy0MBB:
17739   //   %FalseValue = ...
17740   //   # fallthrough to sinkMBB
17741   copy0MBB->addSuccessor(sinkMBB);
17742
17743   //  sinkMBB:
17744   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17745   //  ...
17746   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17747           TII->get(X86::PHI), MI->getOperand(0).getReg())
17748     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17749     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17750
17751   MI->eraseFromParent();   // The pseudo instruction is gone now.
17752   return sinkMBB;
17753 }
17754
17755 MachineBasicBlock *
17756 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17757                                         bool Is64Bit) const {
17758   MachineFunction *MF = BB->getParent();
17759   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17760   DebugLoc DL = MI->getDebugLoc();
17761   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17762
17763   assert(MF->shouldSplitStack());
17764
17765   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17766   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17767
17768   // BB:
17769   //  ... [Till the alloca]
17770   // If stacklet is not large enough, jump to mallocMBB
17771   //
17772   // bumpMBB:
17773   //  Allocate by subtracting from RSP
17774   //  Jump to continueMBB
17775   //
17776   // mallocMBB:
17777   //  Allocate by call to runtime
17778   //
17779   // continueMBB:
17780   //  ...
17781   //  [rest of original BB]
17782   //
17783
17784   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17785   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17786   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17787
17788   MachineRegisterInfo &MRI = MF->getRegInfo();
17789   const TargetRegisterClass *AddrRegClass =
17790     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17791
17792   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17793     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17794     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17795     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17796     sizeVReg = MI->getOperand(1).getReg(),
17797     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17798
17799   MachineFunction::iterator MBBIter = BB;
17800   ++MBBIter;
17801
17802   MF->insert(MBBIter, bumpMBB);
17803   MF->insert(MBBIter, mallocMBB);
17804   MF->insert(MBBIter, continueMBB);
17805
17806   continueMBB->splice(continueMBB->begin(), BB,
17807                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
17808   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17809
17810   // Add code to the main basic block to check if the stack limit has been hit,
17811   // and if so, jump to mallocMBB otherwise to bumpMBB.
17812   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17813   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17814     .addReg(tmpSPVReg).addReg(sizeVReg);
17815   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17816     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17817     .addReg(SPLimitVReg);
17818   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17819
17820   // bumpMBB simply decreases the stack pointer, since we know the current
17821   // stacklet has enough space.
17822   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17823     .addReg(SPLimitVReg);
17824   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17825     .addReg(SPLimitVReg);
17826   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17827
17828   // Calls into a routine in libgcc to allocate more space from the heap.
17829   const uint32_t *RegMask =
17830     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17831   if (Is64Bit) {
17832     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17833       .addReg(sizeVReg);
17834     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17835       .addExternalSymbol("__morestack_allocate_stack_space")
17836       .addRegMask(RegMask)
17837       .addReg(X86::RDI, RegState::Implicit)
17838       .addReg(X86::RAX, RegState::ImplicitDefine);
17839   } else {
17840     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17841       .addImm(12);
17842     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17843     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17844       .addExternalSymbol("__morestack_allocate_stack_space")
17845       .addRegMask(RegMask)
17846       .addReg(X86::EAX, RegState::ImplicitDefine);
17847   }
17848
17849   if (!Is64Bit)
17850     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17851       .addImm(16);
17852
17853   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17854     .addReg(Is64Bit ? X86::RAX : X86::EAX);
17855   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17856
17857   // Set up the CFG correctly.
17858   BB->addSuccessor(bumpMBB);
17859   BB->addSuccessor(mallocMBB);
17860   mallocMBB->addSuccessor(continueMBB);
17861   bumpMBB->addSuccessor(continueMBB);
17862
17863   // Take care of the PHI nodes.
17864   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17865           MI->getOperand(0).getReg())
17866     .addReg(mallocPtrVReg).addMBB(mallocMBB)
17867     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17868
17869   // Delete the original pseudo instruction.
17870   MI->eraseFromParent();
17871
17872   // And we're done.
17873   return continueMBB;
17874 }
17875
17876 MachineBasicBlock *
17877 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17878                                         MachineBasicBlock *BB) const {
17879   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17880   DebugLoc DL = MI->getDebugLoc();
17881
17882   assert(!Subtarget->isTargetMacho());
17883
17884   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
17885   // non-trivial part is impdef of ESP.
17886
17887   if (Subtarget->isTargetWin64()) {
17888     if (Subtarget->isTargetCygMing()) {
17889       // ___chkstk(Mingw64):
17890       // Clobbers R10, R11, RAX and EFLAGS.
17891       // Updates RSP.
17892       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17893         .addExternalSymbol("___chkstk")
17894         .addReg(X86::RAX, RegState::Implicit)
17895         .addReg(X86::RSP, RegState::Implicit)
17896         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17897         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17898         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17899     } else {
17900       // __chkstk(MSVCRT): does not update stack pointer.
17901       // Clobbers R10, R11 and EFLAGS.
17902       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17903         .addExternalSymbol("__chkstk")
17904         .addReg(X86::RAX, RegState::Implicit)
17905         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17906       // RAX has the offset to be subtracted from RSP.
17907       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17908         .addReg(X86::RSP)
17909         .addReg(X86::RAX);
17910     }
17911   } else {
17912     const char *StackProbeSymbol =
17913       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17914
17915     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17916       .addExternalSymbol(StackProbeSymbol)
17917       .addReg(X86::EAX, RegState::Implicit)
17918       .addReg(X86::ESP, RegState::Implicit)
17919       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17920       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17921       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17922   }
17923
17924   MI->eraseFromParent();   // The pseudo instruction is gone now.
17925   return BB;
17926 }
17927
17928 MachineBasicBlock *
17929 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17930                                       MachineBasicBlock *BB) const {
17931   // This is pretty easy.  We're taking the value that we received from
17932   // our load from the relocation, sticking it in either RDI (x86-64)
17933   // or EAX and doing an indirect call.  The return value will then
17934   // be in the normal return register.
17935   MachineFunction *F = BB->getParent();
17936   const X86InstrInfo *TII
17937     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17938   DebugLoc DL = MI->getDebugLoc();
17939
17940   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17941   assert(MI->getOperand(3).isGlobal() && "This should be a global");
17942
17943   // Get a register mask for the lowered call.
17944   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17945   // proper register mask.
17946   const uint32_t *RegMask =
17947     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17948   if (Subtarget->is64Bit()) {
17949     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17950                                       TII->get(X86::MOV64rm), X86::RDI)
17951     .addReg(X86::RIP)
17952     .addImm(0).addReg(0)
17953     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17954                       MI->getOperand(3).getTargetFlags())
17955     .addReg(0);
17956     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17957     addDirectMem(MIB, X86::RDI);
17958     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17959   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17960     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17961                                       TII->get(X86::MOV32rm), X86::EAX)
17962     .addReg(0)
17963     .addImm(0).addReg(0)
17964     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17965                       MI->getOperand(3).getTargetFlags())
17966     .addReg(0);
17967     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17968     addDirectMem(MIB, X86::EAX);
17969     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17970   } else {
17971     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17972                                       TII->get(X86::MOV32rm), X86::EAX)
17973     .addReg(TII->getGlobalBaseReg(F))
17974     .addImm(0).addReg(0)
17975     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17976                       MI->getOperand(3).getTargetFlags())
17977     .addReg(0);
17978     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17979     addDirectMem(MIB, X86::EAX);
17980     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17981   }
17982
17983   MI->eraseFromParent(); // The pseudo instruction is gone now.
17984   return BB;
17985 }
17986
17987 MachineBasicBlock *
17988 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17989                                     MachineBasicBlock *MBB) const {
17990   DebugLoc DL = MI->getDebugLoc();
17991   MachineFunction *MF = MBB->getParent();
17992   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17993   MachineRegisterInfo &MRI = MF->getRegInfo();
17994
17995   const BasicBlock *BB = MBB->getBasicBlock();
17996   MachineFunction::iterator I = MBB;
17997   ++I;
17998
17999   // Memory Reference
18000   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18001   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18002
18003   unsigned DstReg;
18004   unsigned MemOpndSlot = 0;
18005
18006   unsigned CurOp = 0;
18007
18008   DstReg = MI->getOperand(CurOp++).getReg();
18009   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18010   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18011   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18012   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18013
18014   MemOpndSlot = CurOp;
18015
18016   MVT PVT = getPointerTy();
18017   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18018          "Invalid Pointer Size!");
18019
18020   // For v = setjmp(buf), we generate
18021   //
18022   // thisMBB:
18023   //  buf[LabelOffset] = restoreMBB
18024   //  SjLjSetup restoreMBB
18025   //
18026   // mainMBB:
18027   //  v_main = 0
18028   //
18029   // sinkMBB:
18030   //  v = phi(main, restore)
18031   //
18032   // restoreMBB:
18033   //  v_restore = 1
18034
18035   MachineBasicBlock *thisMBB = MBB;
18036   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18037   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18038   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18039   MF->insert(I, mainMBB);
18040   MF->insert(I, sinkMBB);
18041   MF->push_back(restoreMBB);
18042
18043   MachineInstrBuilder MIB;
18044
18045   // Transfer the remainder of BB and its successor edges to sinkMBB.
18046   sinkMBB->splice(sinkMBB->begin(), MBB,
18047                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18048   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18049
18050   // thisMBB:
18051   unsigned PtrStoreOpc = 0;
18052   unsigned LabelReg = 0;
18053   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18054   Reloc::Model RM = MF->getTarget().getRelocationModel();
18055   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18056                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18057
18058   // Prepare IP either in reg or imm.
18059   if (!UseImmLabel) {
18060     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18061     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18062     LabelReg = MRI.createVirtualRegister(PtrRC);
18063     if (Subtarget->is64Bit()) {
18064       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18065               .addReg(X86::RIP)
18066               .addImm(0)
18067               .addReg(0)
18068               .addMBB(restoreMBB)
18069               .addReg(0);
18070     } else {
18071       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18072       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18073               .addReg(XII->getGlobalBaseReg(MF))
18074               .addImm(0)
18075               .addReg(0)
18076               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18077               .addReg(0);
18078     }
18079   } else
18080     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18081   // Store IP
18082   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18083   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18084     if (i == X86::AddrDisp)
18085       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18086     else
18087       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18088   }
18089   if (!UseImmLabel)
18090     MIB.addReg(LabelReg);
18091   else
18092     MIB.addMBB(restoreMBB);
18093   MIB.setMemRefs(MMOBegin, MMOEnd);
18094   // Setup
18095   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18096           .addMBB(restoreMBB);
18097
18098   const X86RegisterInfo *RegInfo =
18099     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18100   MIB.addRegMask(RegInfo->getNoPreservedMask());
18101   thisMBB->addSuccessor(mainMBB);
18102   thisMBB->addSuccessor(restoreMBB);
18103
18104   // mainMBB:
18105   //  EAX = 0
18106   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18107   mainMBB->addSuccessor(sinkMBB);
18108
18109   // sinkMBB:
18110   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18111           TII->get(X86::PHI), DstReg)
18112     .addReg(mainDstReg).addMBB(mainMBB)
18113     .addReg(restoreDstReg).addMBB(restoreMBB);
18114
18115   // restoreMBB:
18116   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18117   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18118   restoreMBB->addSuccessor(sinkMBB);
18119
18120   MI->eraseFromParent();
18121   return sinkMBB;
18122 }
18123
18124 MachineBasicBlock *
18125 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18126                                      MachineBasicBlock *MBB) const {
18127   DebugLoc DL = MI->getDebugLoc();
18128   MachineFunction *MF = MBB->getParent();
18129   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18130   MachineRegisterInfo &MRI = MF->getRegInfo();
18131
18132   // Memory Reference
18133   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18134   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18135
18136   MVT PVT = getPointerTy();
18137   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18138          "Invalid Pointer Size!");
18139
18140   const TargetRegisterClass *RC =
18141     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18142   unsigned Tmp = MRI.createVirtualRegister(RC);
18143   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18144   const X86RegisterInfo *RegInfo =
18145     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18146   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18147   unsigned SP = RegInfo->getStackRegister();
18148
18149   MachineInstrBuilder MIB;
18150
18151   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18152   const int64_t SPOffset = 2 * PVT.getStoreSize();
18153
18154   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18155   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18156
18157   // Reload FP
18158   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18159   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18160     MIB.addOperand(MI->getOperand(i));
18161   MIB.setMemRefs(MMOBegin, MMOEnd);
18162   // Reload IP
18163   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18164   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18165     if (i == X86::AddrDisp)
18166       MIB.addDisp(MI->getOperand(i), LabelOffset);
18167     else
18168       MIB.addOperand(MI->getOperand(i));
18169   }
18170   MIB.setMemRefs(MMOBegin, MMOEnd);
18171   // Reload SP
18172   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18173   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18174     if (i == X86::AddrDisp)
18175       MIB.addDisp(MI->getOperand(i), SPOffset);
18176     else
18177       MIB.addOperand(MI->getOperand(i));
18178   }
18179   MIB.setMemRefs(MMOBegin, MMOEnd);
18180   // Jump
18181   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18182
18183   MI->eraseFromParent();
18184   return MBB;
18185 }
18186
18187 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18188 // accumulator loops. Writing back to the accumulator allows the coalescer
18189 // to remove extra copies in the loop.   
18190 MachineBasicBlock *
18191 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18192                                  MachineBasicBlock *MBB) const {
18193   MachineOperand &AddendOp = MI->getOperand(3);
18194
18195   // Bail out early if the addend isn't a register - we can't switch these.
18196   if (!AddendOp.isReg())
18197     return MBB;
18198
18199   MachineFunction &MF = *MBB->getParent();
18200   MachineRegisterInfo &MRI = MF.getRegInfo();
18201
18202   // Check whether the addend is defined by a PHI:
18203   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18204   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18205   if (!AddendDef.isPHI())
18206     return MBB;
18207
18208   // Look for the following pattern:
18209   // loop:
18210   //   %addend = phi [%entry, 0], [%loop, %result]
18211   //   ...
18212   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18213
18214   // Replace with:
18215   //   loop:
18216   //   %addend = phi [%entry, 0], [%loop, %result]
18217   //   ...
18218   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18219
18220   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18221     assert(AddendDef.getOperand(i).isReg());
18222     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18223     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18224     if (&PHISrcInst == MI) {
18225       // Found a matching instruction.
18226       unsigned NewFMAOpc = 0;
18227       switch (MI->getOpcode()) {
18228         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18229         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18230         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18231         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18232         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18233         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18234         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18235         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18236         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18237         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18238         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18239         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18240         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18241         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18242         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18243         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18244         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18245         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18246         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18247         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18248         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18249         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18250         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18251         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18252         default: llvm_unreachable("Unrecognized FMA variant.");
18253       }
18254
18255       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18256       MachineInstrBuilder MIB =
18257         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18258         .addOperand(MI->getOperand(0))
18259         .addOperand(MI->getOperand(3))
18260         .addOperand(MI->getOperand(2))
18261         .addOperand(MI->getOperand(1));
18262       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18263       MI->eraseFromParent();
18264     }
18265   }
18266
18267   return MBB;
18268 }
18269
18270 MachineBasicBlock *
18271 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18272                                                MachineBasicBlock *BB) const {
18273   switch (MI->getOpcode()) {
18274   default: llvm_unreachable("Unexpected instr type to insert");
18275   case X86::TAILJMPd64:
18276   case X86::TAILJMPr64:
18277   case X86::TAILJMPm64:
18278     llvm_unreachable("TAILJMP64 would not be touched here.");
18279   case X86::TCRETURNdi64:
18280   case X86::TCRETURNri64:
18281   case X86::TCRETURNmi64:
18282     return BB;
18283   case X86::WIN_ALLOCA:
18284     return EmitLoweredWinAlloca(MI, BB);
18285   case X86::SEG_ALLOCA_32:
18286     return EmitLoweredSegAlloca(MI, BB, false);
18287   case X86::SEG_ALLOCA_64:
18288     return EmitLoweredSegAlloca(MI, BB, true);
18289   case X86::TLSCall_32:
18290   case X86::TLSCall_64:
18291     return EmitLoweredTLSCall(MI, BB);
18292   case X86::CMOV_GR8:
18293   case X86::CMOV_FR32:
18294   case X86::CMOV_FR64:
18295   case X86::CMOV_V4F32:
18296   case X86::CMOV_V2F64:
18297   case X86::CMOV_V2I64:
18298   case X86::CMOV_V8F32:
18299   case X86::CMOV_V4F64:
18300   case X86::CMOV_V4I64:
18301   case X86::CMOV_V16F32:
18302   case X86::CMOV_V8F64:
18303   case X86::CMOV_V8I64:
18304   case X86::CMOV_GR16:
18305   case X86::CMOV_GR32:
18306   case X86::CMOV_RFP32:
18307   case X86::CMOV_RFP64:
18308   case X86::CMOV_RFP80:
18309     return EmitLoweredSelect(MI, BB);
18310
18311   case X86::FP32_TO_INT16_IN_MEM:
18312   case X86::FP32_TO_INT32_IN_MEM:
18313   case X86::FP32_TO_INT64_IN_MEM:
18314   case X86::FP64_TO_INT16_IN_MEM:
18315   case X86::FP64_TO_INT32_IN_MEM:
18316   case X86::FP64_TO_INT64_IN_MEM:
18317   case X86::FP80_TO_INT16_IN_MEM:
18318   case X86::FP80_TO_INT32_IN_MEM:
18319   case X86::FP80_TO_INT64_IN_MEM: {
18320     MachineFunction *F = BB->getParent();
18321     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18322     DebugLoc DL = MI->getDebugLoc();
18323
18324     // Change the floating point control register to use "round towards zero"
18325     // mode when truncating to an integer value.
18326     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18327     addFrameReference(BuildMI(*BB, MI, DL,
18328                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18329
18330     // Load the old value of the high byte of the control word...
18331     unsigned OldCW =
18332       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18333     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18334                       CWFrameIdx);
18335
18336     // Set the high part to be round to zero...
18337     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18338       .addImm(0xC7F);
18339
18340     // Reload the modified control word now...
18341     addFrameReference(BuildMI(*BB, MI, DL,
18342                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18343
18344     // Restore the memory image of control word to original value
18345     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18346       .addReg(OldCW);
18347
18348     // Get the X86 opcode to use.
18349     unsigned Opc;
18350     switch (MI->getOpcode()) {
18351     default: llvm_unreachable("illegal opcode!");
18352     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18353     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18354     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18355     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18356     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18357     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18358     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18359     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18360     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18361     }
18362
18363     X86AddressMode AM;
18364     MachineOperand &Op = MI->getOperand(0);
18365     if (Op.isReg()) {
18366       AM.BaseType = X86AddressMode::RegBase;
18367       AM.Base.Reg = Op.getReg();
18368     } else {
18369       AM.BaseType = X86AddressMode::FrameIndexBase;
18370       AM.Base.FrameIndex = Op.getIndex();
18371     }
18372     Op = MI->getOperand(1);
18373     if (Op.isImm())
18374       AM.Scale = Op.getImm();
18375     Op = MI->getOperand(2);
18376     if (Op.isImm())
18377       AM.IndexReg = Op.getImm();
18378     Op = MI->getOperand(3);
18379     if (Op.isGlobal()) {
18380       AM.GV = Op.getGlobal();
18381     } else {
18382       AM.Disp = Op.getImm();
18383     }
18384     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18385                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18386
18387     // Reload the original control word now.
18388     addFrameReference(BuildMI(*BB, MI, DL,
18389                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18390
18391     MI->eraseFromParent();   // The pseudo instruction is gone now.
18392     return BB;
18393   }
18394     // String/text processing lowering.
18395   case X86::PCMPISTRM128REG:
18396   case X86::VPCMPISTRM128REG:
18397   case X86::PCMPISTRM128MEM:
18398   case X86::VPCMPISTRM128MEM:
18399   case X86::PCMPESTRM128REG:
18400   case X86::VPCMPESTRM128REG:
18401   case X86::PCMPESTRM128MEM:
18402   case X86::VPCMPESTRM128MEM:
18403     assert(Subtarget->hasSSE42() &&
18404            "Target must have SSE4.2 or AVX features enabled");
18405     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18406
18407   // String/text processing lowering.
18408   case X86::PCMPISTRIREG:
18409   case X86::VPCMPISTRIREG:
18410   case X86::PCMPISTRIMEM:
18411   case X86::VPCMPISTRIMEM:
18412   case X86::PCMPESTRIREG:
18413   case X86::VPCMPESTRIREG:
18414   case X86::PCMPESTRIMEM:
18415   case X86::VPCMPESTRIMEM:
18416     assert(Subtarget->hasSSE42() &&
18417            "Target must have SSE4.2 or AVX features enabled");
18418     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18419
18420   // Thread synchronization.
18421   case X86::MONITOR:
18422     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18423
18424   // xbegin
18425   case X86::XBEGIN:
18426     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18427
18428   case X86::VASTART_SAVE_XMM_REGS:
18429     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18430
18431   case X86::VAARG_64:
18432     return EmitVAARG64WithCustomInserter(MI, BB);
18433
18434   case X86::EH_SjLj_SetJmp32:
18435   case X86::EH_SjLj_SetJmp64:
18436     return emitEHSjLjSetJmp(MI, BB);
18437
18438   case X86::EH_SjLj_LongJmp32:
18439   case X86::EH_SjLj_LongJmp64:
18440     return emitEHSjLjLongJmp(MI, BB);
18441
18442   case TargetOpcode::STACKMAP:
18443   case TargetOpcode::PATCHPOINT:
18444     return emitPatchPoint(MI, BB);
18445
18446   case X86::VFMADDPDr213r:
18447   case X86::VFMADDPSr213r:
18448   case X86::VFMADDSDr213r:
18449   case X86::VFMADDSSr213r:
18450   case X86::VFMSUBPDr213r:
18451   case X86::VFMSUBPSr213r:
18452   case X86::VFMSUBSDr213r:
18453   case X86::VFMSUBSSr213r:
18454   case X86::VFNMADDPDr213r:
18455   case X86::VFNMADDPSr213r:
18456   case X86::VFNMADDSDr213r:
18457   case X86::VFNMADDSSr213r:
18458   case X86::VFNMSUBPDr213r:
18459   case X86::VFNMSUBPSr213r:
18460   case X86::VFNMSUBSDr213r:
18461   case X86::VFNMSUBSSr213r:
18462   case X86::VFMADDPDr213rY:
18463   case X86::VFMADDPSr213rY:
18464   case X86::VFMSUBPDr213rY:
18465   case X86::VFMSUBPSr213rY:
18466   case X86::VFNMADDPDr213rY:
18467   case X86::VFNMADDPSr213rY:
18468   case X86::VFNMSUBPDr213rY:
18469   case X86::VFNMSUBPSr213rY:
18470     return emitFMA3Instr(MI, BB);
18471   }
18472 }
18473
18474 //===----------------------------------------------------------------------===//
18475 //                           X86 Optimization Hooks
18476 //===----------------------------------------------------------------------===//
18477
18478 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18479                                                       APInt &KnownZero,
18480                                                       APInt &KnownOne,
18481                                                       const SelectionDAG &DAG,
18482                                                       unsigned Depth) const {
18483   unsigned BitWidth = KnownZero.getBitWidth();
18484   unsigned Opc = Op.getOpcode();
18485   assert((Opc >= ISD::BUILTIN_OP_END ||
18486           Opc == ISD::INTRINSIC_WO_CHAIN ||
18487           Opc == ISD::INTRINSIC_W_CHAIN ||
18488           Opc == ISD::INTRINSIC_VOID) &&
18489          "Should use MaskedValueIsZero if you don't know whether Op"
18490          " is a target node!");
18491
18492   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18493   switch (Opc) {
18494   default: break;
18495   case X86ISD::ADD:
18496   case X86ISD::SUB:
18497   case X86ISD::ADC:
18498   case X86ISD::SBB:
18499   case X86ISD::SMUL:
18500   case X86ISD::UMUL:
18501   case X86ISD::INC:
18502   case X86ISD::DEC:
18503   case X86ISD::OR:
18504   case X86ISD::XOR:
18505   case X86ISD::AND:
18506     // These nodes' second result is a boolean.
18507     if (Op.getResNo() == 0)
18508       break;
18509     // Fallthrough
18510   case X86ISD::SETCC:
18511     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18512     break;
18513   case ISD::INTRINSIC_WO_CHAIN: {
18514     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18515     unsigned NumLoBits = 0;
18516     switch (IntId) {
18517     default: break;
18518     case Intrinsic::x86_sse_movmsk_ps:
18519     case Intrinsic::x86_avx_movmsk_ps_256:
18520     case Intrinsic::x86_sse2_movmsk_pd:
18521     case Intrinsic::x86_avx_movmsk_pd_256:
18522     case Intrinsic::x86_mmx_pmovmskb:
18523     case Intrinsic::x86_sse2_pmovmskb_128:
18524     case Intrinsic::x86_avx2_pmovmskb: {
18525       // High bits of movmskp{s|d}, pmovmskb are known zero.
18526       switch (IntId) {
18527         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18528         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18529         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18530         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18531         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18532         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18533         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18534         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18535       }
18536       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18537       break;
18538     }
18539     }
18540     break;
18541   }
18542   }
18543 }
18544
18545 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18546   SDValue Op,
18547   const SelectionDAG &,
18548   unsigned Depth) const {
18549   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18550   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18551     return Op.getValueType().getScalarType().getSizeInBits();
18552
18553   // Fallback case.
18554   return 1;
18555 }
18556
18557 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18558 /// node is a GlobalAddress + offset.
18559 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18560                                        const GlobalValue* &GA,
18561                                        int64_t &Offset) const {
18562   if (N->getOpcode() == X86ISD::Wrapper) {
18563     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18564       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18565       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18566       return true;
18567     }
18568   }
18569   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18570 }
18571
18572 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18573 /// same as extracting the high 128-bit part of 256-bit vector and then
18574 /// inserting the result into the low part of a new 256-bit vector
18575 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18576   EVT VT = SVOp->getValueType(0);
18577   unsigned NumElems = VT.getVectorNumElements();
18578
18579   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18580   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18581     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18582         SVOp->getMaskElt(j) >= 0)
18583       return false;
18584
18585   return true;
18586 }
18587
18588 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18589 /// same as extracting the low 128-bit part of 256-bit vector and then
18590 /// inserting the result into the high part of a new 256-bit vector
18591 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18592   EVT VT = SVOp->getValueType(0);
18593   unsigned NumElems = VT.getVectorNumElements();
18594
18595   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18596   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18597     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18598         SVOp->getMaskElt(j) >= 0)
18599       return false;
18600
18601   return true;
18602 }
18603
18604 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18605 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18606                                         TargetLowering::DAGCombinerInfo &DCI,
18607                                         const X86Subtarget* Subtarget) {
18608   SDLoc dl(N);
18609   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18610   SDValue V1 = SVOp->getOperand(0);
18611   SDValue V2 = SVOp->getOperand(1);
18612   EVT VT = SVOp->getValueType(0);
18613   unsigned NumElems = VT.getVectorNumElements();
18614
18615   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18616       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18617     //
18618     //                   0,0,0,...
18619     //                      |
18620     //    V      UNDEF    BUILD_VECTOR    UNDEF
18621     //     \      /           \           /
18622     //  CONCAT_VECTOR         CONCAT_VECTOR
18623     //         \                  /
18624     //          \                /
18625     //          RESULT: V + zero extended
18626     //
18627     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18628         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18629         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18630       return SDValue();
18631
18632     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18633       return SDValue();
18634
18635     // To match the shuffle mask, the first half of the mask should
18636     // be exactly the first vector, and all the rest a splat with the
18637     // first element of the second one.
18638     for (unsigned i = 0; i != NumElems/2; ++i)
18639       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18640           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18641         return SDValue();
18642
18643     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18644     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18645       if (Ld->hasNUsesOfValue(1, 0)) {
18646         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18647         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18648         SDValue ResNode =
18649           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18650                                   Ld->getMemoryVT(),
18651                                   Ld->getPointerInfo(),
18652                                   Ld->getAlignment(),
18653                                   false/*isVolatile*/, true/*ReadMem*/,
18654                                   false/*WriteMem*/);
18655
18656         // Make sure the newly-created LOAD is in the same position as Ld in
18657         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18658         // and update uses of Ld's output chain to use the TokenFactor.
18659         if (Ld->hasAnyUseOfValue(1)) {
18660           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18661                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18662           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18663           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18664                                  SDValue(ResNode.getNode(), 1));
18665         }
18666
18667         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18668       }
18669     }
18670
18671     // Emit a zeroed vector and insert the desired subvector on its
18672     // first half.
18673     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18674     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18675     return DCI.CombineTo(N, InsV);
18676   }
18677
18678   //===--------------------------------------------------------------------===//
18679   // Combine some shuffles into subvector extracts and inserts:
18680   //
18681
18682   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18683   if (isShuffleHigh128VectorInsertLow(SVOp)) {
18684     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18685     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18686     return DCI.CombineTo(N, InsV);
18687   }
18688
18689   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18690   if (isShuffleLow128VectorInsertHigh(SVOp)) {
18691     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18692     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18693     return DCI.CombineTo(N, InsV);
18694   }
18695
18696   return SDValue();
18697 }
18698
18699 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
18700 /// possible.
18701 ///
18702 /// This is the leaf of the recursive combinine below. When we have found some
18703 /// chain of single-use x86 shuffle instructions and accumulated the combined
18704 /// shuffle mask represented by them, this will try to pattern match that mask
18705 /// into either a single instruction if there is a special purpose instruction
18706 /// for this operation, or into a PSHUFB instruction which is a fully general
18707 /// instruction but should only be used to replace chains over a certain depth.
18708 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
18709                                    int Depth, SelectionDAG &DAG,
18710                                    TargetLowering::DAGCombinerInfo &DCI,
18711                                    const X86Subtarget *Subtarget) {
18712   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
18713
18714   // Find the operand that enters the chain. Note that multiple uses are OK
18715   // here, we're not going to remove the operand we find.
18716   SDValue Input = Op.getOperand(0);
18717   while (Input.getOpcode() == ISD::BITCAST)
18718     Input = Input.getOperand(0);
18719
18720   MVT VT = Input.getSimpleValueType();
18721   MVT RootVT = Root.getSimpleValueType();
18722   SDLoc DL(Root);
18723
18724   // Just remove no-op shuffle masks.
18725   if (Mask.size() == 1) {
18726     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
18727                   /*AddTo*/ true);
18728     return true;
18729   }
18730
18731   // Use the float domain if the operand type is a floatingc point type.
18732   bool FloatDomain = VT.isFloatingPoint();
18733
18734   // If we don't have access to VEX encodings, the generic PSHUF instructions
18735   // are preferable to some of the specialized forms despite requiring one more
18736   // byte to encode because they can implicitly copy.
18737   //
18738   // IF we *do* have VEX encodings, than we can use shorter, more specific
18739   // shuffle instructions freely as they can copy due to the extra register
18740   // operand.
18741   if (Subtarget->hasAVX()) {
18742     // We have both floatincg point and integer variants of shuffles that dup
18743     // either tho low or high half of the vector.
18744     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
18745       bool Lo = Mask.equals(0, 0);
18746       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
18747                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
18748       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
18749       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
18750       DCI.AddToWorklist(Op.getNode());
18751       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
18752       DCI.AddToWorklist(Op.getNode());
18753       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
18754                     /*AddTo*/ true);
18755       return true;
18756     }
18757
18758     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
18759
18760     // For the integer domain we have specialized instructions for duplicating
18761     // any element size from the low or high half.
18762     if (!FloatDomain &&
18763         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
18764          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
18765          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
18766          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
18767          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
18768                      15))) {
18769       bool Lo = Mask[0] == 0;
18770       MVT ShuffleVT;
18771       switch (Mask.size()) {
18772       case 4: ShuffleVT = MVT::v4i32; break;
18773       case 8: ShuffleVT = MVT::v8i32; break;
18774       case 16: ShuffleVT = MVT::v16i32; break;
18775       };
18776       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
18777       DCI.AddToWorklist(Op.getNode());
18778       Op = DAG.getNode(Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL, ShuffleVT, Op,
18779                        Op);
18780       DCI.AddToWorklist(Op.getNode());
18781       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
18782                     /*AddTo*/ true);
18783       return true;
18784     }
18785   }
18786
18787   // Bail if we have fewer than 3 shuffle instructions in the chain.
18788   if (Depth < 3)
18789     return false;
18790
18791   // If we have 3 or more shuffle instructions, we can replace them with
18792   // a single PSHUFB instruction profitably. Intel's manuals suggest only using
18793   // PSHUFB if doing so replacing 5 instructions, but in practice PSHUFB tends
18794   // to be *very* fast so we're more aggressive.
18795   if (Subtarget->hasSSSE3()) {
18796     SmallVector<SDValue, 16> PSHUFBMask;
18797     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
18798     int Ratio = 16 / Mask.size();
18799     for (unsigned i = 0; i < 16; ++i) {
18800       int M = Ratio * Mask[i / Ratio] + i % Ratio;
18801       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
18802     }
18803     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
18804     DCI.AddToWorklist(Op.getNode());
18805     SDValue PSHUFBMaskOp =
18806         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
18807     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
18808     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
18809     DCI.AddToWorklist(Op.getNode());
18810     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
18811                   /*AddTo*/ true);
18812     return true;
18813   }
18814
18815   // Failed to find any combines.
18816   return false;
18817 }
18818
18819 /// \brief Fully generic combining of x86 shuffle instructions.
18820 ///
18821 /// This should be the last combine run over the x86 shuffle instructions. Once
18822 /// they have been fully optimized, this will recursively consdier all chains
18823 /// of single-use shuffle instructions, build a generic model of the cumulative
18824 /// shuffle operation, and check for simpler instructions which implement this
18825 /// operation. We use this primarily for two purposes:
18826 ///
18827 /// 1) Collapse generic shuffles to specialized single instructions when
18828 ///    equivalent. In most cases, this is just an encoding size win, but
18829 ///    sometimes we will collapse multiple generic shuffles into a single
18830 ///    special-purpose shuffle.
18831 /// 2) Look for sequences of shuffle instructions with 3 or more total
18832 ///    instructions, and replace them with the slightly more expensive SSSE3
18833 ///    PSHUFB instruction if available. We do this as the last combining step
18834 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
18835 ///    a suitable short sequence of other instructions. The PHUFB will either
18836 ///    use a register or have to read from memory and so is slightly (but only
18837 ///    slightly) more expensive than the other shuffle instructions.
18838 ///
18839 /// Because this is inherently a quadratic operation (for each shuffle in
18840 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
18841 /// This should never be an issue in practice as the shuffle lowering doesn't
18842 /// produce sequences of more than 8 instructions.
18843 ///
18844 /// FIXME: Currently, we don't collapse instructions *into* PSHUFB. We should,
18845 /// and we should do so more aggressively than we form PSHUFB because once we
18846 /// have a PSHUFB, we might as well do as much shuffling as we can.
18847 ///
18848 /// FIXME: We will currently miss some cases where the redundant shuffling
18849 /// would simplify under the threshold for PSHUFB formation because of
18850 /// combine-ordering. To fix this, we should do the redundant instruction
18851 /// combining in this recursive walk.
18852 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
18853                                           ArrayRef<int> IncomingMask, int Depth,
18854                                           SelectionDAG &DAG,
18855                                           TargetLowering::DAGCombinerInfo &DCI,
18856                                           const X86Subtarget *Subtarget) {
18857   // Bound the depth of our recursive combine because this is ultimately
18858   // quadratic in nature.
18859   if (Depth > 8)
18860     return false;
18861
18862   // Directly rip through bitcasts to find the underlying operand.
18863   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
18864     Op = Op.getOperand(0);
18865
18866   MVT VT = Op.getSimpleValueType();
18867   if (!VT.isVector())
18868     return false; // Bail if we hit a non-vector.
18869   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
18870   // version should be added.
18871   if (VT.getSizeInBits() != 128)
18872     return false;
18873
18874   MVT RootVT = Root.getSimpleValueType();
18875   assert(RootVT.isVector() && "Shuffles operate on vector types!");
18876   assert(VT.getSizeInBits() == RootVT.getSizeInBits() &&
18877          "Can only combine shuffles of the same vector register size.");
18878
18879   if (!isTargetShuffle(Op.getOpcode()))
18880     return false;
18881   SmallVector<int, 16> OpMask;
18882   bool IsUnary;
18883   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
18884   // We only can combine unary shuffles which we can decode the mask for.
18885   if (!HaveMask || !IsUnary)
18886     return false;
18887
18888   assert(VT.getVectorNumElements() == OpMask.size() &&
18889          "Different mask size from vector size!");
18890
18891   SmallVector<int, 16> Mask;
18892   Mask.reserve(std::max(OpMask.size(), IncomingMask.size()));
18893
18894   // Merge this shuffle operation's mask into our accumulated mask. This is
18895   // a bit tricky as the shuffle may have a different size from the root.
18896   if (OpMask.size() == IncomingMask.size()) {
18897     for (int M : IncomingMask)
18898       Mask.push_back(OpMask[M]);
18899   } else if (OpMask.size() < IncomingMask.size()) {
18900     assert(IncomingMask.size() % OpMask.size() == 0 &&
18901            "The smaller number of elements must divide the larger.");
18902     int Ratio = IncomingMask.size() / OpMask.size();
18903     for (int M : IncomingMask)
18904       Mask.push_back(Ratio * OpMask[M / Ratio] + M % Ratio);
18905   } else {
18906     assert(OpMask.size() > IncomingMask.size() && "All other cases handled!");
18907     assert(OpMask.size() % IncomingMask.size() == 0 &&
18908            "The smaller number of elements must divide the larger.");
18909     int Ratio = OpMask.size() / IncomingMask.size();
18910     for (int i = 0, e = OpMask.size(); i < e; ++i)
18911       Mask.push_back(OpMask[Ratio * IncomingMask[i / Ratio] + i % Ratio]);
18912   }
18913
18914   // See if we can recurse into the operand to combine more things.
18915   switch (Op.getOpcode()) {
18916     case X86ISD::PSHUFD:
18917     case X86ISD::PSHUFHW:
18918     case X86ISD::PSHUFLW:
18919       if (Op.getOperand(0).hasOneUse() &&
18920           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
18921                                         DAG, DCI, Subtarget))
18922         return true;
18923       break;
18924
18925     case X86ISD::UNPCKL:
18926     case X86ISD::UNPCKH:
18927       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
18928       // We can't check for single use, we have to check that this shuffle is the only user.
18929       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
18930           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
18931                                         DAG, DCI, Subtarget))
18932           return true;
18933       break;
18934   }
18935
18936   // Minor canonicalization of the accumulated shuffle mask to make it easier
18937   // to match below. All this does is detect masks with squential pairs of
18938   // elements, and shrink them to the half-width mask. It does this in a loop
18939   // so it will reduce the size of the mask to the minimal width mask which
18940   // performs an equivalent shuffle.
18941   while (Mask.size() > 1) {
18942     SmallVector<int, 16> NewMask;
18943     for (int i = 0, e = Mask.size()/2; i < e; ++i) {
18944       if (Mask[2*i] % 2 != 0 || Mask[2*i] != Mask[2*i + 1] + 1) {
18945         NewMask.clear();
18946         break;
18947       }
18948       NewMask.push_back(Mask[2*i] / 2);
18949     }
18950     if (NewMask.empty())
18951       break;
18952     Mask.swap(NewMask);
18953   }
18954
18955   return combineX86ShuffleChain(Op, Root, Mask, Depth, DAG, DCI, Subtarget);
18956 }
18957
18958 /// \brief Get the PSHUF-style mask from PSHUF node.
18959 ///
18960 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18961 /// PSHUF-style masks that can be reused with such instructions.
18962 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18963   SmallVector<int, 4> Mask;
18964   bool IsUnary;
18965   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18966   (void)HaveMask;
18967   assert(HaveMask);
18968
18969   switch (N.getOpcode()) {
18970   case X86ISD::PSHUFD:
18971     return Mask;
18972   case X86ISD::PSHUFLW:
18973     Mask.resize(4);
18974     return Mask;
18975   case X86ISD::PSHUFHW:
18976     Mask.erase(Mask.begin(), Mask.begin() + 4);
18977     for (int &M : Mask)
18978       M -= 4;
18979     return Mask;
18980   default:
18981     llvm_unreachable("No valid shuffle instruction found!");
18982   }
18983 }
18984
18985 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18986 ///
18987 /// We walk up the chain and look for a combinable shuffle, skipping over
18988 /// shuffles that we could hoist this shuffle's transformation past without
18989 /// altering anything.
18990 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18991                                          SelectionDAG &DAG,
18992                                          TargetLowering::DAGCombinerInfo &DCI) {
18993   assert(N.getOpcode() == X86ISD::PSHUFD &&
18994          "Called with something other than an x86 128-bit half shuffle!");
18995   SDLoc DL(N);
18996
18997   // Walk up a single-use chain looking for a combinable shuffle.
18998   SDValue V = N.getOperand(0);
18999   for (; V.hasOneUse(); V = V.getOperand(0)) {
19000     switch (V.getOpcode()) {
19001     default:
19002       return false; // Nothing combined!
19003
19004     case ISD::BITCAST:
19005       // Skip bitcasts as we always know the type for the target specific
19006       // instructions.
19007       continue;
19008
19009     case X86ISD::PSHUFD:
19010       // Found another dword shuffle.
19011       break;
19012
19013     case X86ISD::PSHUFLW:
19014       // Check that the low words (being shuffled) are the identity in the
19015       // dword shuffle, and the high words are self-contained.
19016       if (Mask[0] != 0 || Mask[1] != 1 ||
19017           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19018         return false;
19019
19020       continue;
19021
19022     case X86ISD::PSHUFHW:
19023       // Check that the high words (being shuffled) are the identity in the
19024       // dword shuffle, and the low words are self-contained.
19025       if (Mask[2] != 2 || Mask[3] != 3 ||
19026           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19027         return false;
19028
19029       continue;
19030
19031     case X86ISD::UNPCKL:
19032     case X86ISD::UNPCKH:
19033       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19034       // shuffle into a preceding word shuffle.
19035       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19036         return false;
19037
19038       // Search for a half-shuffle which we can combine with.
19039       unsigned CombineOp =
19040           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19041       if (V.getOperand(0) != V.getOperand(1) ||
19042           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19043         return false;
19044       V = V.getOperand(0);
19045       do {
19046         switch (V.getOpcode()) {
19047         default:
19048           return false; // Nothing to combine.
19049
19050         case X86ISD::PSHUFLW:
19051         case X86ISD::PSHUFHW:
19052           if (V.getOpcode() == CombineOp)
19053             break;
19054
19055           // Fallthrough!
19056         case ISD::BITCAST:
19057           V = V.getOperand(0);
19058           continue;
19059         }
19060         break;
19061       } while (V.hasOneUse());
19062       break;
19063     }
19064     // Break out of the loop if we break out of the switch.
19065     break;
19066   }
19067
19068   if (!V.hasOneUse())
19069     // We fell out of the loop without finding a viable combining instruction.
19070     return false;
19071
19072   // Record the old value to use in RAUW-ing.
19073   SDValue Old = V;
19074
19075   // Merge this node's mask and our incoming mask.
19076   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19077   for (int &M : Mask)
19078     M = VMask[M];
19079   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19080                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19081
19082   // It is possible that one of the combinable shuffles was completely absorbed
19083   // by the other, just replace it and revisit all users in that case.
19084   if (Old.getNode() == V.getNode()) {
19085     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19086     return true;
19087   }
19088
19089   // Replace N with its operand as we're going to combine that shuffle away.
19090   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19091
19092   // Replace the combinable shuffle with the combined one, updating all users
19093   // so that we re-evaluate the chain here.
19094   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19095   return true;
19096 }
19097
19098 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19099 ///
19100 /// We walk up the chain, skipping shuffles of the other half and looking
19101 /// through shuffles which switch halves trying to find a shuffle of the same
19102 /// pair of dwords.
19103 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19104                                         SelectionDAG &DAG,
19105                                         TargetLowering::DAGCombinerInfo &DCI) {
19106   assert(
19107       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19108       "Called with something other than an x86 128-bit half shuffle!");
19109   SDLoc DL(N);
19110   unsigned CombineOpcode = N.getOpcode();
19111
19112   // Walk up a single-use chain looking for a combinable shuffle.
19113   SDValue V = N.getOperand(0);
19114   for (; V.hasOneUse(); V = V.getOperand(0)) {
19115     switch (V.getOpcode()) {
19116     default:
19117       return false; // Nothing combined!
19118
19119     case ISD::BITCAST:
19120       // Skip bitcasts as we always know the type for the target specific
19121       // instructions.
19122       continue;
19123
19124     case X86ISD::PSHUFLW:
19125     case X86ISD::PSHUFHW:
19126       if (V.getOpcode() == CombineOpcode)
19127         break;
19128
19129       // Other-half shuffles are no-ops.
19130       continue;
19131
19132     case X86ISD::PSHUFD: {
19133       // We can only handle pshufd if the half we are combining either stays in
19134       // its half, or switches to the other half. Bail if one of these isn't
19135       // true.
19136       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19137       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
19138       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
19139             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
19140         return false;
19141
19142       // Map the mask through the pshufd and keep walking up the chain.
19143       for (int i = 0; i < 4; ++i)
19144         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
19145
19146       // Switch halves if the pshufd does.
19147       CombineOpcode =
19148           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19149       continue;
19150     }
19151     }
19152     // Break out of the loop if we break out of the switch.
19153     break;
19154   }
19155
19156   if (!V.hasOneUse())
19157     // We fell out of the loop without finding a viable combining instruction.
19158     return false;
19159
19160   // Record the old value to use in RAUW-ing.
19161   SDValue Old = V;
19162
19163   // Merge this node's mask and our incoming mask (adjusted to account for all
19164   // the pshufd instructions encountered).
19165   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19166   for (int &M : Mask)
19167     M = VMask[M];
19168   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19169                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19170
19171   // Replace N with its operand as we're going to combine that shuffle away.
19172   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19173
19174   // Replace the combinable shuffle with the combined one, updating all users
19175   // so that we re-evaluate the chain here.
19176   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19177   return true;
19178 }
19179
19180 /// \brief Try to combine x86 target specific shuffles.
19181 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19182                                            TargetLowering::DAGCombinerInfo &DCI,
19183                                            const X86Subtarget *Subtarget) {
19184   SDLoc DL(N);
19185   MVT VT = N.getSimpleValueType();
19186   SmallVector<int, 4> Mask;
19187
19188   switch (N.getOpcode()) {
19189   case X86ISD::PSHUFD:
19190   case X86ISD::PSHUFLW:
19191   case X86ISD::PSHUFHW:
19192     Mask = getPSHUFShuffleMask(N);
19193     assert(Mask.size() == 4);
19194     break;
19195   default:
19196     return SDValue();
19197   }
19198
19199   // Nuke no-op shuffles that show up after combining.
19200   if (isNoopShuffleMask(Mask))
19201     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19202
19203   // Look for simplifications involving one or two shuffle instructions.
19204   SDValue V = N.getOperand(0);
19205   switch (N.getOpcode()) {
19206   default:
19207     break;
19208   case X86ISD::PSHUFLW:
19209   case X86ISD::PSHUFHW:
19210     assert(VT == MVT::v8i16);
19211     (void)VT;
19212
19213     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19214       return SDValue(); // We combined away this shuffle, so we're done.
19215
19216     // See if this reduces to a PSHUFD which is no more expensive and can
19217     // combine with more operations.
19218     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
19219         areAdjacentMasksSequential(Mask)) {
19220       int DMask[] = {-1, -1, -1, -1};
19221       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19222       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19223       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19224       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19225       DCI.AddToWorklist(V.getNode());
19226       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19227                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19228       DCI.AddToWorklist(V.getNode());
19229       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19230     }
19231
19232     // Look for shuffle patterns which can be implemented as a single unpack.
19233     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19234     // only works when we have a PSHUFD followed by two half-shuffles.
19235     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19236         (V.getOpcode() == X86ISD::PSHUFLW ||
19237          V.getOpcode() == X86ISD::PSHUFHW) &&
19238         V.getOpcode() != N.getOpcode() &&
19239         V.hasOneUse()) {
19240       SDValue D = V.getOperand(0);
19241       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19242         D = D.getOperand(0);
19243       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19244         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19245         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19246         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19247         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19248         int WordMask[8];
19249         for (int i = 0; i < 4; ++i) {
19250           WordMask[i + NOffset] = Mask[i] + NOffset;
19251           WordMask[i + VOffset] = VMask[i] + VOffset;
19252         }
19253         // Map the word mask through the DWord mask.
19254         int MappedMask[8];
19255         for (int i = 0; i < 8; ++i)
19256           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19257         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19258         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19259         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19260                        std::begin(UnpackLoMask)) ||
19261             std::equal(std::begin(MappedMask), std::end(MappedMask),
19262                        std::begin(UnpackHiMask))) {
19263           // We can replace all three shuffles with an unpack.
19264           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19265           DCI.AddToWorklist(V.getNode());
19266           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19267                                                 : X86ISD::UNPCKH,
19268                              DL, MVT::v8i16, V, V);
19269         }
19270       }
19271     }
19272
19273     break;
19274
19275   case X86ISD::PSHUFD:
19276     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19277       return SDValue(); // We combined away this shuffle.
19278
19279     break;
19280   }
19281
19282   return SDValue();
19283 }
19284
19285 /// PerformShuffleCombine - Performs several different shuffle combines.
19286 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19287                                      TargetLowering::DAGCombinerInfo &DCI,
19288                                      const X86Subtarget *Subtarget) {
19289   SDLoc dl(N);
19290   SDValue N0 = N->getOperand(0);
19291   SDValue N1 = N->getOperand(1);
19292   EVT VT = N->getValueType(0);
19293
19294   // Don't create instructions with illegal types after legalize types has run.
19295   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19296   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19297     return SDValue();
19298
19299   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19300   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19301       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19302     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19303
19304   // During Type Legalization, when promoting illegal vector types,
19305   // the backend might introduce new shuffle dag nodes and bitcasts.
19306   //
19307   // This code performs the following transformation:
19308   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19309   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19310   //
19311   // We do this only if both the bitcast and the BINOP dag nodes have
19312   // one use. Also, perform this transformation only if the new binary
19313   // operation is legal. This is to avoid introducing dag nodes that
19314   // potentially need to be further expanded (or custom lowered) into a
19315   // less optimal sequence of dag nodes.
19316   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19317       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19318       N0.getOpcode() == ISD::BITCAST) {
19319     SDValue BC0 = N0.getOperand(0);
19320     EVT SVT = BC0.getValueType();
19321     unsigned Opcode = BC0.getOpcode();
19322     unsigned NumElts = VT.getVectorNumElements();
19323     
19324     if (BC0.hasOneUse() && SVT.isVector() &&
19325         SVT.getVectorNumElements() * 2 == NumElts &&
19326         TLI.isOperationLegal(Opcode, VT)) {
19327       bool CanFold = false;
19328       switch (Opcode) {
19329       default : break;
19330       case ISD::ADD :
19331       case ISD::FADD :
19332       case ISD::SUB :
19333       case ISD::FSUB :
19334       case ISD::MUL :
19335       case ISD::FMUL :
19336         CanFold = true;
19337       }
19338
19339       unsigned SVTNumElts = SVT.getVectorNumElements();
19340       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19341       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19342         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19343       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19344         CanFold = SVOp->getMaskElt(i) < 0;
19345
19346       if (CanFold) {
19347         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19348         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19349         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19350         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19351       }
19352     }
19353   }
19354
19355   // Only handle 128 wide vector from here on.
19356   if (!VT.is128BitVector())
19357     return SDValue();
19358
19359   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19360   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19361   // consecutive, non-overlapping, and in the right order.
19362   SmallVector<SDValue, 16> Elts;
19363   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19364     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19365
19366   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19367   if (LD.getNode())
19368     return LD;
19369
19370   if (isTargetShuffle(N->getOpcode())) {
19371     SDValue Shuffle =
19372         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19373     if (Shuffle.getNode())
19374       return Shuffle;
19375
19376     // Try recursively combining arbitrary sequences of x86 shuffle
19377     // instructions into higher-order shuffles. We do this after combining
19378     // specific PSHUF instruction sequences into their minimal form so that we
19379     // can evaluate how many specialized shuffle instructions are involved in
19380     // a particular chain.
19381     SmallVector<int, 1> NonceMask; // Just a placeholder.
19382     NonceMask.push_back(0);
19383     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19384                                       /*Depth*/ 1, DAG, DCI, Subtarget))
19385       return SDValue(); // This routine will use CombineTo to replace N.
19386   }
19387
19388   return SDValue();
19389 }
19390
19391 /// PerformTruncateCombine - Converts truncate operation to
19392 /// a sequence of vector shuffle operations.
19393 /// It is possible when we truncate 256-bit vector to 128-bit vector
19394 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19395                                       TargetLowering::DAGCombinerInfo &DCI,
19396                                       const X86Subtarget *Subtarget)  {
19397   return SDValue();
19398 }
19399
19400 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19401 /// specific shuffle of a load can be folded into a single element load.
19402 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19403 /// shuffles have been customed lowered so we need to handle those here.
19404 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19405                                          TargetLowering::DAGCombinerInfo &DCI) {
19406   if (DCI.isBeforeLegalizeOps())
19407     return SDValue();
19408
19409   SDValue InVec = N->getOperand(0);
19410   SDValue EltNo = N->getOperand(1);
19411
19412   if (!isa<ConstantSDNode>(EltNo))
19413     return SDValue();
19414
19415   EVT VT = InVec.getValueType();
19416
19417   bool HasShuffleIntoBitcast = false;
19418   if (InVec.getOpcode() == ISD::BITCAST) {
19419     // Don't duplicate a load with other uses.
19420     if (!InVec.hasOneUse())
19421       return SDValue();
19422     EVT BCVT = InVec.getOperand(0).getValueType();
19423     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19424       return SDValue();
19425     InVec = InVec.getOperand(0);
19426     HasShuffleIntoBitcast = true;
19427   }
19428
19429   if (!isTargetShuffle(InVec.getOpcode()))
19430     return SDValue();
19431
19432   // Don't duplicate a load with other uses.
19433   if (!InVec.hasOneUse())
19434     return SDValue();
19435
19436   SmallVector<int, 16> ShuffleMask;
19437   bool UnaryShuffle;
19438   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19439                             UnaryShuffle))
19440     return SDValue();
19441
19442   // Select the input vector, guarding against out of range extract vector.
19443   unsigned NumElems = VT.getVectorNumElements();
19444   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19445   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19446   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19447                                          : InVec.getOperand(1);
19448
19449   // If inputs to shuffle are the same for both ops, then allow 2 uses
19450   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19451
19452   if (LdNode.getOpcode() == ISD::BITCAST) {
19453     // Don't duplicate a load with other uses.
19454     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19455       return SDValue();
19456
19457     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19458     LdNode = LdNode.getOperand(0);
19459   }
19460
19461   if (!ISD::isNormalLoad(LdNode.getNode()))
19462     return SDValue();
19463
19464   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19465
19466   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19467     return SDValue();
19468
19469   if (HasShuffleIntoBitcast) {
19470     // If there's a bitcast before the shuffle, check if the load type and
19471     // alignment is valid.
19472     unsigned Align = LN0->getAlignment();
19473     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19474     unsigned NewAlign = TLI.getDataLayout()->
19475       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19476
19477     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19478       return SDValue();
19479   }
19480
19481   // All checks match so transform back to vector_shuffle so that DAG combiner
19482   // can finish the job
19483   SDLoc dl(N);
19484
19485   // Create shuffle node taking into account the case that its a unary shuffle
19486   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19487   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19488                                  InVec.getOperand(0), Shuffle,
19489                                  &ShuffleMask[0]);
19490   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19491   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19492                      EltNo);
19493 }
19494
19495 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19496 /// generation and convert it from being a bunch of shuffles and extracts
19497 /// to a simple store and scalar loads to extract the elements.
19498 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19499                                          TargetLowering::DAGCombinerInfo &DCI) {
19500   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19501   if (NewOp.getNode())
19502     return NewOp;
19503
19504   SDValue InputVector = N->getOperand(0);
19505
19506   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19507   // from mmx to v2i32 has a single usage.
19508   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19509       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19510       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19511     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19512                        N->getValueType(0),
19513                        InputVector.getNode()->getOperand(0));
19514
19515   // Only operate on vectors of 4 elements, where the alternative shuffling
19516   // gets to be more expensive.
19517   if (InputVector.getValueType() != MVT::v4i32)
19518     return SDValue();
19519
19520   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19521   // single use which is a sign-extend or zero-extend, and all elements are
19522   // used.
19523   SmallVector<SDNode *, 4> Uses;
19524   unsigned ExtractedElements = 0;
19525   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19526        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19527     if (UI.getUse().getResNo() != InputVector.getResNo())
19528       return SDValue();
19529
19530     SDNode *Extract = *UI;
19531     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19532       return SDValue();
19533
19534     if (Extract->getValueType(0) != MVT::i32)
19535       return SDValue();
19536     if (!Extract->hasOneUse())
19537       return SDValue();
19538     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19539         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19540       return SDValue();
19541     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19542       return SDValue();
19543
19544     // Record which element was extracted.
19545     ExtractedElements |=
19546       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19547
19548     Uses.push_back(Extract);
19549   }
19550
19551   // If not all the elements were used, this may not be worthwhile.
19552   if (ExtractedElements != 15)
19553     return SDValue();
19554
19555   // Ok, we've now decided to do the transformation.
19556   SDLoc dl(InputVector);
19557
19558   // Store the value to a temporary stack slot.
19559   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19560   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19561                             MachinePointerInfo(), false, false, 0);
19562
19563   // Replace each use (extract) with a load of the appropriate element.
19564   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19565        UE = Uses.end(); UI != UE; ++UI) {
19566     SDNode *Extract = *UI;
19567
19568     // cOMpute the element's address.
19569     SDValue Idx = Extract->getOperand(1);
19570     unsigned EltSize =
19571         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19572     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19573     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19574     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19575
19576     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19577                                      StackPtr, OffsetVal);
19578
19579     // Load the scalar.
19580     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19581                                      ScalarAddr, MachinePointerInfo(),
19582                                      false, false, false, 0);
19583
19584     // Replace the exact with the load.
19585     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19586   }
19587
19588   // The replacement was made in place; don't return anything.
19589   return SDValue();
19590 }
19591
19592 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19593 static std::pair<unsigned, bool>
19594 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19595                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19596   if (!VT.isVector())
19597     return std::make_pair(0, false);
19598
19599   bool NeedSplit = false;
19600   switch (VT.getSimpleVT().SimpleTy) {
19601   default: return std::make_pair(0, false);
19602   case MVT::v32i8:
19603   case MVT::v16i16:
19604   case MVT::v8i32:
19605     if (!Subtarget->hasAVX2())
19606       NeedSplit = true;
19607     if (!Subtarget->hasAVX())
19608       return std::make_pair(0, false);
19609     break;
19610   case MVT::v16i8:
19611   case MVT::v8i16:
19612   case MVT::v4i32:
19613     if (!Subtarget->hasSSE2())
19614       return std::make_pair(0, false);
19615   }
19616
19617   // SSE2 has only a small subset of the operations.
19618   bool hasUnsigned = Subtarget->hasSSE41() ||
19619                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19620   bool hasSigned = Subtarget->hasSSE41() ||
19621                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19622
19623   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19624
19625   unsigned Opc = 0;
19626   // Check for x CC y ? x : y.
19627   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19628       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19629     switch (CC) {
19630     default: break;
19631     case ISD::SETULT:
19632     case ISD::SETULE:
19633       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19634     case ISD::SETUGT:
19635     case ISD::SETUGE:
19636       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19637     case ISD::SETLT:
19638     case ISD::SETLE:
19639       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19640     case ISD::SETGT:
19641     case ISD::SETGE:
19642       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19643     }
19644   // Check for x CC y ? y : x -- a min/max with reversed arms.
19645   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19646              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19647     switch (CC) {
19648     default: break;
19649     case ISD::SETULT:
19650     case ISD::SETULE:
19651       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19652     case ISD::SETUGT:
19653     case ISD::SETUGE:
19654       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19655     case ISD::SETLT:
19656     case ISD::SETLE:
19657       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19658     case ISD::SETGT:
19659     case ISD::SETGE:
19660       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19661     }
19662   }
19663
19664   return std::make_pair(Opc, NeedSplit);
19665 }
19666
19667 static SDValue
19668 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19669                                       const X86Subtarget *Subtarget) {
19670   SDLoc dl(N);
19671   SDValue Cond = N->getOperand(0);
19672   SDValue LHS = N->getOperand(1);
19673   SDValue RHS = N->getOperand(2);
19674
19675   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19676     SDValue CondSrc = Cond->getOperand(0);
19677     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19678       Cond = CondSrc->getOperand(0);
19679   }
19680
19681   MVT VT = N->getSimpleValueType(0);
19682   MVT EltVT = VT.getVectorElementType();
19683   unsigned NumElems = VT.getVectorNumElements();
19684   // There is no blend with immediate in AVX-512.
19685   if (VT.is512BitVector())
19686     return SDValue();
19687
19688   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19689     return SDValue();
19690   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19691     return SDValue();
19692
19693   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19694     return SDValue();
19695
19696   unsigned MaskValue = 0;
19697   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19698     return SDValue();
19699
19700   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19701   for (unsigned i = 0; i < NumElems; ++i) {
19702     // Be sure we emit undef where we can.
19703     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19704       ShuffleMask[i] = -1;
19705     else
19706       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19707   }
19708
19709   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19710 }
19711
19712 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19713 /// nodes.
19714 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19715                                     TargetLowering::DAGCombinerInfo &DCI,
19716                                     const X86Subtarget *Subtarget) {
19717   SDLoc DL(N);
19718   SDValue Cond = N->getOperand(0);
19719   // Get the LHS/RHS of the select.
19720   SDValue LHS = N->getOperand(1);
19721   SDValue RHS = N->getOperand(2);
19722   EVT VT = LHS.getValueType();
19723   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19724
19725   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19726   // instructions match the semantics of the common C idiom x<y?x:y but not
19727   // x<=y?x:y, because of how they handle negative zero (which can be
19728   // ignored in unsafe-math mode).
19729   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19730       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19731       (Subtarget->hasSSE2() ||
19732        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19733     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19734
19735     unsigned Opcode = 0;
19736     // Check for x CC y ? x : y.
19737     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19738         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19739       switch (CC) {
19740       default: break;
19741       case ISD::SETULT:
19742         // Converting this to a min would handle NaNs incorrectly, and swapping
19743         // the operands would cause it to handle comparisons between positive
19744         // and negative zero incorrectly.
19745         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19746           if (!DAG.getTarget().Options.UnsafeFPMath &&
19747               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19748             break;
19749           std::swap(LHS, RHS);
19750         }
19751         Opcode = X86ISD::FMIN;
19752         break;
19753       case ISD::SETOLE:
19754         // Converting this to a min would handle comparisons between positive
19755         // and negative zero incorrectly.
19756         if (!DAG.getTarget().Options.UnsafeFPMath &&
19757             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19758           break;
19759         Opcode = X86ISD::FMIN;
19760         break;
19761       case ISD::SETULE:
19762         // Converting this to a min would handle both negative zeros and NaNs
19763         // incorrectly, but we can swap the operands to fix both.
19764         std::swap(LHS, RHS);
19765       case ISD::SETOLT:
19766       case ISD::SETLT:
19767       case ISD::SETLE:
19768         Opcode = X86ISD::FMIN;
19769         break;
19770
19771       case ISD::SETOGE:
19772         // Converting this to a max would handle comparisons between positive
19773         // and negative zero incorrectly.
19774         if (!DAG.getTarget().Options.UnsafeFPMath &&
19775             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19776           break;
19777         Opcode = X86ISD::FMAX;
19778         break;
19779       case ISD::SETUGT:
19780         // Converting this to a max would handle NaNs incorrectly, and swapping
19781         // the operands would cause it to handle comparisons between positive
19782         // and negative zero incorrectly.
19783         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19784           if (!DAG.getTarget().Options.UnsafeFPMath &&
19785               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19786             break;
19787           std::swap(LHS, RHS);
19788         }
19789         Opcode = X86ISD::FMAX;
19790         break;
19791       case ISD::SETUGE:
19792         // Converting this to a max would handle both negative zeros and NaNs
19793         // incorrectly, but we can swap the operands to fix both.
19794         std::swap(LHS, RHS);
19795       case ISD::SETOGT:
19796       case ISD::SETGT:
19797       case ISD::SETGE:
19798         Opcode = X86ISD::FMAX;
19799         break;
19800       }
19801     // Check for x CC y ? y : x -- a min/max with reversed arms.
19802     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19803                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19804       switch (CC) {
19805       default: break;
19806       case ISD::SETOGE:
19807         // Converting this to a min would handle comparisons between positive
19808         // and negative zero incorrectly, and swapping the operands would
19809         // cause it to handle NaNs incorrectly.
19810         if (!DAG.getTarget().Options.UnsafeFPMath &&
19811             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19812           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19813             break;
19814           std::swap(LHS, RHS);
19815         }
19816         Opcode = X86ISD::FMIN;
19817         break;
19818       case ISD::SETUGT:
19819         // Converting this to a min would handle NaNs incorrectly.
19820         if (!DAG.getTarget().Options.UnsafeFPMath &&
19821             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19822           break;
19823         Opcode = X86ISD::FMIN;
19824         break;
19825       case ISD::SETUGE:
19826         // Converting this to a min would handle both negative zeros and NaNs
19827         // incorrectly, but we can swap the operands to fix both.
19828         std::swap(LHS, RHS);
19829       case ISD::SETOGT:
19830       case ISD::SETGT:
19831       case ISD::SETGE:
19832         Opcode = X86ISD::FMIN;
19833         break;
19834
19835       case ISD::SETULT:
19836         // Converting this to a max would handle NaNs incorrectly.
19837         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19838           break;
19839         Opcode = X86ISD::FMAX;
19840         break;
19841       case ISD::SETOLE:
19842         // Converting this to a max would handle comparisons between positive
19843         // and negative zero incorrectly, and swapping the operands would
19844         // cause it to handle NaNs incorrectly.
19845         if (!DAG.getTarget().Options.UnsafeFPMath &&
19846             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19847           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19848             break;
19849           std::swap(LHS, RHS);
19850         }
19851         Opcode = X86ISD::FMAX;
19852         break;
19853       case ISD::SETULE:
19854         // Converting this to a max would handle both negative zeros and NaNs
19855         // incorrectly, but we can swap the operands to fix both.
19856         std::swap(LHS, RHS);
19857       case ISD::SETOLT:
19858       case ISD::SETLT:
19859       case ISD::SETLE:
19860         Opcode = X86ISD::FMAX;
19861         break;
19862       }
19863     }
19864
19865     if (Opcode)
19866       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19867   }
19868
19869   EVT CondVT = Cond.getValueType();
19870   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19871       CondVT.getVectorElementType() == MVT::i1) {
19872     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19873     // lowering on AVX-512. In this case we convert it to
19874     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19875     // The same situation for all 128 and 256-bit vectors of i8 and i16
19876     EVT OpVT = LHS.getValueType();
19877     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19878         (OpVT.getVectorElementType() == MVT::i8 ||
19879          OpVT.getVectorElementType() == MVT::i16)) {
19880       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19881       DCI.AddToWorklist(Cond.getNode());
19882       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19883     }
19884   }
19885   // If this is a select between two integer constants, try to do some
19886   // optimizations.
19887   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19888     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19889       // Don't do this for crazy integer types.
19890       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19891         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19892         // so that TrueC (the true value) is larger than FalseC.
19893         bool NeedsCondInvert = false;
19894
19895         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19896             // Efficiently invertible.
19897             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
19898              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
19899               isa<ConstantSDNode>(Cond.getOperand(1))))) {
19900           NeedsCondInvert = true;
19901           std::swap(TrueC, FalseC);
19902         }
19903
19904         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
19905         if (FalseC->getAPIntValue() == 0 &&
19906             TrueC->getAPIntValue().isPowerOf2()) {
19907           if (NeedsCondInvert) // Invert the condition if needed.
19908             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19909                                DAG.getConstant(1, Cond.getValueType()));
19910
19911           // Zero extend the condition if needed.
19912           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19913
19914           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19915           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19916                              DAG.getConstant(ShAmt, MVT::i8));
19917         }
19918
19919         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19920         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19921           if (NeedsCondInvert) // Invert the condition if needed.
19922             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19923                                DAG.getConstant(1, Cond.getValueType()));
19924
19925           // Zero extend the condition if needed.
19926           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19927                              FalseC->getValueType(0), Cond);
19928           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19929                              SDValue(FalseC, 0));
19930         }
19931
19932         // Optimize cases that will turn into an LEA instruction.  This requires
19933         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19934         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19935           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19936           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19937
19938           bool isFastMultiplier = false;
19939           if (Diff < 10) {
19940             switch ((unsigned char)Diff) {
19941               default: break;
19942               case 1:  // result = add base, cond
19943               case 2:  // result = lea base(    , cond*2)
19944               case 3:  // result = lea base(cond, cond*2)
19945               case 4:  // result = lea base(    , cond*4)
19946               case 5:  // result = lea base(cond, cond*4)
19947               case 8:  // result = lea base(    , cond*8)
19948               case 9:  // result = lea base(cond, cond*8)
19949                 isFastMultiplier = true;
19950                 break;
19951             }
19952           }
19953
19954           if (isFastMultiplier) {
19955             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19956             if (NeedsCondInvert) // Invert the condition if needed.
19957               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19958                                  DAG.getConstant(1, Cond.getValueType()));
19959
19960             // Zero extend the condition if needed.
19961             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19962                                Cond);
19963             // Scale the condition by the difference.
19964             if (Diff != 1)
19965               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19966                                  DAG.getConstant(Diff, Cond.getValueType()));
19967
19968             // Add the base if non-zero.
19969             if (FalseC->getAPIntValue() != 0)
19970               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19971                                  SDValue(FalseC, 0));
19972             return Cond;
19973           }
19974         }
19975       }
19976   }
19977
19978   // Canonicalize max and min:
19979   // (x > y) ? x : y -> (x >= y) ? x : y
19980   // (x < y) ? x : y -> (x <= y) ? x : y
19981   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19982   // the need for an extra compare
19983   // against zero. e.g.
19984   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19985   // subl   %esi, %edi
19986   // testl  %edi, %edi
19987   // movl   $0, %eax
19988   // cmovgl %edi, %eax
19989   // =>
19990   // xorl   %eax, %eax
19991   // subl   %esi, $edi
19992   // cmovsl %eax, %edi
19993   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19994       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19995       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19996     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19997     switch (CC) {
19998     default: break;
19999     case ISD::SETLT:
20000     case ISD::SETGT: {
20001       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20002       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20003                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20004       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20005     }
20006     }
20007   }
20008
20009   // Early exit check
20010   if (!TLI.isTypeLegal(VT))
20011     return SDValue();
20012
20013   // Match VSELECTs into subs with unsigned saturation.
20014   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20015       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20016       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20017        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20018     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20019
20020     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20021     // left side invert the predicate to simplify logic below.
20022     SDValue Other;
20023     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20024       Other = RHS;
20025       CC = ISD::getSetCCInverse(CC, true);
20026     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20027       Other = LHS;
20028     }
20029
20030     if (Other.getNode() && Other->getNumOperands() == 2 &&
20031         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20032       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20033       SDValue CondRHS = Cond->getOperand(1);
20034
20035       // Look for a general sub with unsigned saturation first.
20036       // x >= y ? x-y : 0 --> subus x, y
20037       // x >  y ? x-y : 0 --> subus x, y
20038       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20039           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20040         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20041
20042       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20043         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20044           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20045             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20046               // If the RHS is a constant we have to reverse the const
20047               // canonicalization.
20048               // x > C-1 ? x+-C : 0 --> subus x, C
20049               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20050                   CondRHSConst->getAPIntValue() ==
20051                       (-OpRHSConst->getAPIntValue() - 1))
20052                 return DAG.getNode(
20053                     X86ISD::SUBUS, DL, VT, OpLHS,
20054                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20055
20056           // Another special case: If C was a sign bit, the sub has been
20057           // canonicalized into a xor.
20058           // FIXME: Would it be better to use computeKnownBits to determine
20059           //        whether it's safe to decanonicalize the xor?
20060           // x s< 0 ? x^C : 0 --> subus x, C
20061           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20062               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20063               OpRHSConst->getAPIntValue().isSignBit())
20064             // Note that we have to rebuild the RHS constant here to ensure we
20065             // don't rely on particular values of undef lanes.
20066             return DAG.getNode(
20067                 X86ISD::SUBUS, DL, VT, OpLHS,
20068                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20069         }
20070     }
20071   }
20072
20073   // Try to match a min/max vector operation.
20074   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20075     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20076     unsigned Opc = ret.first;
20077     bool NeedSplit = ret.second;
20078
20079     if (Opc && NeedSplit) {
20080       unsigned NumElems = VT.getVectorNumElements();
20081       // Extract the LHS vectors
20082       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20083       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20084
20085       // Extract the RHS vectors
20086       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20087       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20088
20089       // Create min/max for each subvector
20090       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20091       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20092
20093       // Merge the result
20094       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20095     } else if (Opc)
20096       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20097   }
20098
20099   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20100   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20101       // Check if SETCC has already been promoted
20102       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20103       // Check that condition value type matches vselect operand type
20104       CondVT == VT) { 
20105
20106     assert(Cond.getValueType().isVector() &&
20107            "vector select expects a vector selector!");
20108
20109     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20110     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20111
20112     if (!TValIsAllOnes && !FValIsAllZeros) {
20113       // Try invert the condition if true value is not all 1s and false value
20114       // is not all 0s.
20115       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20116       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20117
20118       if (TValIsAllZeros || FValIsAllOnes) {
20119         SDValue CC = Cond.getOperand(2);
20120         ISD::CondCode NewCC =
20121           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20122                                Cond.getOperand(0).getValueType().isInteger());
20123         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20124         std::swap(LHS, RHS);
20125         TValIsAllOnes = FValIsAllOnes;
20126         FValIsAllZeros = TValIsAllZeros;
20127       }
20128     }
20129
20130     if (TValIsAllOnes || FValIsAllZeros) {
20131       SDValue Ret;
20132
20133       if (TValIsAllOnes && FValIsAllZeros)
20134         Ret = Cond;
20135       else if (TValIsAllOnes)
20136         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20137                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20138       else if (FValIsAllZeros)
20139         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20140                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20141
20142       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20143     }
20144   }
20145
20146   // Try to fold this VSELECT into a MOVSS/MOVSD
20147   if (N->getOpcode() == ISD::VSELECT &&
20148       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20149     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20150         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20151       bool CanFold = false;
20152       unsigned NumElems = Cond.getNumOperands();
20153       SDValue A = LHS;
20154       SDValue B = RHS;
20155       
20156       if (isZero(Cond.getOperand(0))) {
20157         CanFold = true;
20158
20159         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20160         // fold (vselect <0,-1> -> (movsd A, B)
20161         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20162           CanFold = isAllOnes(Cond.getOperand(i));
20163       } else if (isAllOnes(Cond.getOperand(0))) {
20164         CanFold = true;
20165         std::swap(A, B);
20166
20167         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20168         // fold (vselect <-1,0> -> (movsd B, A)
20169         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20170           CanFold = isZero(Cond.getOperand(i));
20171       }
20172
20173       if (CanFold) {
20174         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20175           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20176         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20177       }
20178
20179       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20180         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20181         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20182         //                             (v2i64 (bitcast B)))))
20183         //
20184         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20185         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20186         //                             (v2f64 (bitcast B)))))
20187         //
20188         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20189         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20190         //                             (v2i64 (bitcast A)))))
20191         //
20192         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20193         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20194         //                             (v2f64 (bitcast A)))))
20195
20196         CanFold = (isZero(Cond.getOperand(0)) &&
20197                    isZero(Cond.getOperand(1)) &&
20198                    isAllOnes(Cond.getOperand(2)) &&
20199                    isAllOnes(Cond.getOperand(3)));
20200
20201         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20202             isAllOnes(Cond.getOperand(1)) &&
20203             isZero(Cond.getOperand(2)) &&
20204             isZero(Cond.getOperand(3))) {
20205           CanFold = true;
20206           std::swap(LHS, RHS);
20207         }
20208
20209         if (CanFold) {
20210           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20211           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20212           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20213           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20214                                                 NewB, DAG);
20215           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20216         }
20217       }
20218     }
20219   }
20220
20221   // If we know that this node is legal then we know that it is going to be
20222   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20223   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20224   // to simplify previous instructions.
20225   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20226       !DCI.isBeforeLegalize() &&
20227       // We explicitly check against v8i16 and v16i16 because, although
20228       // they're marked as Custom, they might only be legal when Cond is a
20229       // build_vector of constants. This will be taken care in a later
20230       // condition.
20231       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20232        VT != MVT::v8i16)) {
20233     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20234
20235     // Don't optimize vector selects that map to mask-registers.
20236     if (BitWidth == 1)
20237       return SDValue();
20238
20239     // Check all uses of that condition operand to check whether it will be
20240     // consumed by non-BLEND instructions, which may depend on all bits are set
20241     // properly.
20242     for (SDNode::use_iterator I = Cond->use_begin(),
20243                               E = Cond->use_end(); I != E; ++I)
20244       if (I->getOpcode() != ISD::VSELECT)
20245         // TODO: Add other opcodes eventually lowered into BLEND.
20246         return SDValue();
20247
20248     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20249     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20250
20251     APInt KnownZero, KnownOne;
20252     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20253                                           DCI.isBeforeLegalizeOps());
20254     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20255         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20256       DCI.CommitTargetLoweringOpt(TLO);
20257   }
20258
20259   // We should generate an X86ISD::BLENDI from a vselect if its argument
20260   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20261   // constants. This specific pattern gets generated when we split a
20262   // selector for a 512 bit vector in a machine without AVX512 (but with
20263   // 256-bit vectors), during legalization:
20264   //
20265   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20266   //
20267   // Iff we find this pattern and the build_vectors are built from
20268   // constants, we translate the vselect into a shuffle_vector that we
20269   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20270   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20271     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20272     if (Shuffle.getNode())
20273       return Shuffle;
20274   }
20275
20276   return SDValue();
20277 }
20278
20279 // Check whether a boolean test is testing a boolean value generated by
20280 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20281 // code.
20282 //
20283 // Simplify the following patterns:
20284 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20285 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20286 // to (Op EFLAGS Cond)
20287 //
20288 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20289 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20290 // to (Op EFLAGS !Cond)
20291 //
20292 // where Op could be BRCOND or CMOV.
20293 //
20294 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20295   // Quit if not CMP and SUB with its value result used.
20296   if (Cmp.getOpcode() != X86ISD::CMP &&
20297       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20298       return SDValue();
20299
20300   // Quit if not used as a boolean value.
20301   if (CC != X86::COND_E && CC != X86::COND_NE)
20302     return SDValue();
20303
20304   // Check CMP operands. One of them should be 0 or 1 and the other should be
20305   // an SetCC or extended from it.
20306   SDValue Op1 = Cmp.getOperand(0);
20307   SDValue Op2 = Cmp.getOperand(1);
20308
20309   SDValue SetCC;
20310   const ConstantSDNode* C = nullptr;
20311   bool needOppositeCond = (CC == X86::COND_E);
20312   bool checkAgainstTrue = false; // Is it a comparison against 1?
20313
20314   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20315     SetCC = Op2;
20316   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20317     SetCC = Op1;
20318   else // Quit if all operands are not constants.
20319     return SDValue();
20320
20321   if (C->getZExtValue() == 1) {
20322     needOppositeCond = !needOppositeCond;
20323     checkAgainstTrue = true;
20324   } else if (C->getZExtValue() != 0)
20325     // Quit if the constant is neither 0 or 1.
20326     return SDValue();
20327
20328   bool truncatedToBoolWithAnd = false;
20329   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20330   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20331          SetCC.getOpcode() == ISD::TRUNCATE ||
20332          SetCC.getOpcode() == ISD::AND) {
20333     if (SetCC.getOpcode() == ISD::AND) {
20334       int OpIdx = -1;
20335       ConstantSDNode *CS;
20336       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20337           CS->getZExtValue() == 1)
20338         OpIdx = 1;
20339       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20340           CS->getZExtValue() == 1)
20341         OpIdx = 0;
20342       if (OpIdx == -1)
20343         break;
20344       SetCC = SetCC.getOperand(OpIdx);
20345       truncatedToBoolWithAnd = true;
20346     } else
20347       SetCC = SetCC.getOperand(0);
20348   }
20349
20350   switch (SetCC.getOpcode()) {
20351   case X86ISD::SETCC_CARRY:
20352     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20353     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20354     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20355     // truncated to i1 using 'and'.
20356     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20357       break;
20358     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20359            "Invalid use of SETCC_CARRY!");
20360     // FALL THROUGH
20361   case X86ISD::SETCC:
20362     // Set the condition code or opposite one if necessary.
20363     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20364     if (needOppositeCond)
20365       CC = X86::GetOppositeBranchCondition(CC);
20366     return SetCC.getOperand(1);
20367   case X86ISD::CMOV: {
20368     // Check whether false/true value has canonical one, i.e. 0 or 1.
20369     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20370     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20371     // Quit if true value is not a constant.
20372     if (!TVal)
20373       return SDValue();
20374     // Quit if false value is not a constant.
20375     if (!FVal) {
20376       SDValue Op = SetCC.getOperand(0);
20377       // Skip 'zext' or 'trunc' node.
20378       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20379           Op.getOpcode() == ISD::TRUNCATE)
20380         Op = Op.getOperand(0);
20381       // A special case for rdrand/rdseed, where 0 is set if false cond is
20382       // found.
20383       if ((Op.getOpcode() != X86ISD::RDRAND &&
20384            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20385         return SDValue();
20386     }
20387     // Quit if false value is not the constant 0 or 1.
20388     bool FValIsFalse = true;
20389     if (FVal && FVal->getZExtValue() != 0) {
20390       if (FVal->getZExtValue() != 1)
20391         return SDValue();
20392       // If FVal is 1, opposite cond is needed.
20393       needOppositeCond = !needOppositeCond;
20394       FValIsFalse = false;
20395     }
20396     // Quit if TVal is not the constant opposite of FVal.
20397     if (FValIsFalse && TVal->getZExtValue() != 1)
20398       return SDValue();
20399     if (!FValIsFalse && TVal->getZExtValue() != 0)
20400       return SDValue();
20401     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20402     if (needOppositeCond)
20403       CC = X86::GetOppositeBranchCondition(CC);
20404     return SetCC.getOperand(3);
20405   }
20406   }
20407
20408   return SDValue();
20409 }
20410
20411 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20412 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20413                                   TargetLowering::DAGCombinerInfo &DCI,
20414                                   const X86Subtarget *Subtarget) {
20415   SDLoc DL(N);
20416
20417   // If the flag operand isn't dead, don't touch this CMOV.
20418   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20419     return SDValue();
20420
20421   SDValue FalseOp = N->getOperand(0);
20422   SDValue TrueOp = N->getOperand(1);
20423   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20424   SDValue Cond = N->getOperand(3);
20425
20426   if (CC == X86::COND_E || CC == X86::COND_NE) {
20427     switch (Cond.getOpcode()) {
20428     default: break;
20429     case X86ISD::BSR:
20430     case X86ISD::BSF:
20431       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20432       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20433         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20434     }
20435   }
20436
20437   SDValue Flags;
20438
20439   Flags = checkBoolTestSetCCCombine(Cond, CC);
20440   if (Flags.getNode() &&
20441       // Extra check as FCMOV only supports a subset of X86 cond.
20442       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20443     SDValue Ops[] = { FalseOp, TrueOp,
20444                       DAG.getConstant(CC, MVT::i8), Flags };
20445     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20446   }
20447
20448   // If this is a select between two integer constants, try to do some
20449   // optimizations.  Note that the operands are ordered the opposite of SELECT
20450   // operands.
20451   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20452     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20453       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20454       // larger than FalseC (the false value).
20455       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20456         CC = X86::GetOppositeBranchCondition(CC);
20457         std::swap(TrueC, FalseC);
20458         std::swap(TrueOp, FalseOp);
20459       }
20460
20461       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20462       // This is efficient for any integer data type (including i8/i16) and
20463       // shift amount.
20464       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20465         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20466                            DAG.getConstant(CC, MVT::i8), Cond);
20467
20468         // Zero extend the condition if needed.
20469         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20470
20471         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20472         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20473                            DAG.getConstant(ShAmt, MVT::i8));
20474         if (N->getNumValues() == 2)  // Dead flag value?
20475           return DCI.CombineTo(N, Cond, SDValue());
20476         return Cond;
20477       }
20478
20479       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20480       // for any integer data type, including i8/i16.
20481       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20482         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20483                            DAG.getConstant(CC, MVT::i8), Cond);
20484
20485         // Zero extend the condition if needed.
20486         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20487                            FalseC->getValueType(0), Cond);
20488         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20489                            SDValue(FalseC, 0));
20490
20491         if (N->getNumValues() == 2)  // Dead flag value?
20492           return DCI.CombineTo(N, Cond, SDValue());
20493         return Cond;
20494       }
20495
20496       // Optimize cases that will turn into an LEA instruction.  This requires
20497       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20498       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20499         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20500         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20501
20502         bool isFastMultiplier = false;
20503         if (Diff < 10) {
20504           switch ((unsigned char)Diff) {
20505           default: break;
20506           case 1:  // result = add base, cond
20507           case 2:  // result = lea base(    , cond*2)
20508           case 3:  // result = lea base(cond, cond*2)
20509           case 4:  // result = lea base(    , cond*4)
20510           case 5:  // result = lea base(cond, cond*4)
20511           case 8:  // result = lea base(    , cond*8)
20512           case 9:  // result = lea base(cond, cond*8)
20513             isFastMultiplier = true;
20514             break;
20515           }
20516         }
20517
20518         if (isFastMultiplier) {
20519           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20520           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20521                              DAG.getConstant(CC, MVT::i8), Cond);
20522           // Zero extend the condition if needed.
20523           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20524                              Cond);
20525           // Scale the condition by the difference.
20526           if (Diff != 1)
20527             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20528                                DAG.getConstant(Diff, Cond.getValueType()));
20529
20530           // Add the base if non-zero.
20531           if (FalseC->getAPIntValue() != 0)
20532             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20533                                SDValue(FalseC, 0));
20534           if (N->getNumValues() == 2)  // Dead flag value?
20535             return DCI.CombineTo(N, Cond, SDValue());
20536           return Cond;
20537         }
20538       }
20539     }
20540   }
20541
20542   // Handle these cases:
20543   //   (select (x != c), e, c) -> select (x != c), e, x),
20544   //   (select (x == c), c, e) -> select (x == c), x, e)
20545   // where the c is an integer constant, and the "select" is the combination
20546   // of CMOV and CMP.
20547   //
20548   // The rationale for this change is that the conditional-move from a constant
20549   // needs two instructions, however, conditional-move from a register needs
20550   // only one instruction.
20551   //
20552   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20553   //  some instruction-combining opportunities. This opt needs to be
20554   //  postponed as late as possible.
20555   //
20556   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20557     // the DCI.xxxx conditions are provided to postpone the optimization as
20558     // late as possible.
20559
20560     ConstantSDNode *CmpAgainst = nullptr;
20561     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20562         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20563         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20564
20565       if (CC == X86::COND_NE &&
20566           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20567         CC = X86::GetOppositeBranchCondition(CC);
20568         std::swap(TrueOp, FalseOp);
20569       }
20570
20571       if (CC == X86::COND_E &&
20572           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20573         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20574                           DAG.getConstant(CC, MVT::i8), Cond };
20575         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20576       }
20577     }
20578   }
20579
20580   return SDValue();
20581 }
20582
20583 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20584                                                 const X86Subtarget *Subtarget) {
20585   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20586   switch (IntNo) {
20587   default: return SDValue();
20588   // SSE/AVX/AVX2 blend intrinsics.
20589   case Intrinsic::x86_avx2_pblendvb:
20590   case Intrinsic::x86_avx2_pblendw:
20591   case Intrinsic::x86_avx2_pblendd_128:
20592   case Intrinsic::x86_avx2_pblendd_256:
20593     // Don't try to simplify this intrinsic if we don't have AVX2.
20594     if (!Subtarget->hasAVX2())
20595       return SDValue();
20596     // FALL-THROUGH
20597   case Intrinsic::x86_avx_blend_pd_256:
20598   case Intrinsic::x86_avx_blend_ps_256:
20599   case Intrinsic::x86_avx_blendv_pd_256:
20600   case Intrinsic::x86_avx_blendv_ps_256:
20601     // Don't try to simplify this intrinsic if we don't have AVX.
20602     if (!Subtarget->hasAVX())
20603       return SDValue();
20604     // FALL-THROUGH
20605   case Intrinsic::x86_sse41_pblendw:
20606   case Intrinsic::x86_sse41_blendpd:
20607   case Intrinsic::x86_sse41_blendps:
20608   case Intrinsic::x86_sse41_blendvps:
20609   case Intrinsic::x86_sse41_blendvpd:
20610   case Intrinsic::x86_sse41_pblendvb: {
20611     SDValue Op0 = N->getOperand(1);
20612     SDValue Op1 = N->getOperand(2);
20613     SDValue Mask = N->getOperand(3);
20614
20615     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20616     if (!Subtarget->hasSSE41())
20617       return SDValue();
20618
20619     // fold (blend A, A, Mask) -> A
20620     if (Op0 == Op1)
20621       return Op0;
20622     // fold (blend A, B, allZeros) -> A
20623     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20624       return Op0;
20625     // fold (blend A, B, allOnes) -> B
20626     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20627       return Op1;
20628     
20629     // Simplify the case where the mask is a constant i32 value.
20630     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20631       if (C->isNullValue())
20632         return Op0;
20633       if (C->isAllOnesValue())
20634         return Op1;
20635     }
20636
20637     return SDValue();
20638   }
20639
20640   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20641   case Intrinsic::x86_sse2_psrai_w:
20642   case Intrinsic::x86_sse2_psrai_d:
20643   case Intrinsic::x86_avx2_psrai_w:
20644   case Intrinsic::x86_avx2_psrai_d:
20645   case Intrinsic::x86_sse2_psra_w:
20646   case Intrinsic::x86_sse2_psra_d:
20647   case Intrinsic::x86_avx2_psra_w:
20648   case Intrinsic::x86_avx2_psra_d: {
20649     SDValue Op0 = N->getOperand(1);
20650     SDValue Op1 = N->getOperand(2);
20651     EVT VT = Op0.getValueType();
20652     assert(VT.isVector() && "Expected a vector type!");
20653
20654     if (isa<BuildVectorSDNode>(Op1))
20655       Op1 = Op1.getOperand(0);
20656
20657     if (!isa<ConstantSDNode>(Op1))
20658       return SDValue();
20659
20660     EVT SVT = VT.getVectorElementType();
20661     unsigned SVTBits = SVT.getSizeInBits();
20662
20663     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20664     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20665     uint64_t ShAmt = C.getZExtValue();
20666
20667     // Don't try to convert this shift into a ISD::SRA if the shift
20668     // count is bigger than or equal to the element size.
20669     if (ShAmt >= SVTBits)
20670       return SDValue();
20671
20672     // Trivial case: if the shift count is zero, then fold this
20673     // into the first operand.
20674     if (ShAmt == 0)
20675       return Op0;
20676
20677     // Replace this packed shift intrinsic with a target independent
20678     // shift dag node.
20679     SDValue Splat = DAG.getConstant(C, VT);
20680     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20681   }
20682   }
20683 }
20684
20685 /// PerformMulCombine - Optimize a single multiply with constant into two
20686 /// in order to implement it with two cheaper instructions, e.g.
20687 /// LEA + SHL, LEA + LEA.
20688 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20689                                  TargetLowering::DAGCombinerInfo &DCI) {
20690   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20691     return SDValue();
20692
20693   EVT VT = N->getValueType(0);
20694   if (VT != MVT::i64)
20695     return SDValue();
20696
20697   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20698   if (!C)
20699     return SDValue();
20700   uint64_t MulAmt = C->getZExtValue();
20701   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20702     return SDValue();
20703
20704   uint64_t MulAmt1 = 0;
20705   uint64_t MulAmt2 = 0;
20706   if ((MulAmt % 9) == 0) {
20707     MulAmt1 = 9;
20708     MulAmt2 = MulAmt / 9;
20709   } else if ((MulAmt % 5) == 0) {
20710     MulAmt1 = 5;
20711     MulAmt2 = MulAmt / 5;
20712   } else if ((MulAmt % 3) == 0) {
20713     MulAmt1 = 3;
20714     MulAmt2 = MulAmt / 3;
20715   }
20716   if (MulAmt2 &&
20717       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20718     SDLoc DL(N);
20719
20720     if (isPowerOf2_64(MulAmt2) &&
20721         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20722       // If second multiplifer is pow2, issue it first. We want the multiply by
20723       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20724       // is an add.
20725       std::swap(MulAmt1, MulAmt2);
20726
20727     SDValue NewMul;
20728     if (isPowerOf2_64(MulAmt1))
20729       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20730                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20731     else
20732       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20733                            DAG.getConstant(MulAmt1, VT));
20734
20735     if (isPowerOf2_64(MulAmt2))
20736       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20737                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20738     else
20739       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20740                            DAG.getConstant(MulAmt2, VT));
20741
20742     // Do not add new nodes to DAG combiner worklist.
20743     DCI.CombineTo(N, NewMul, false);
20744   }
20745   return SDValue();
20746 }
20747
20748 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20749   SDValue N0 = N->getOperand(0);
20750   SDValue N1 = N->getOperand(1);
20751   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20752   EVT VT = N0.getValueType();
20753
20754   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20755   // since the result of setcc_c is all zero's or all ones.
20756   if (VT.isInteger() && !VT.isVector() &&
20757       N1C && N0.getOpcode() == ISD::AND &&
20758       N0.getOperand(1).getOpcode() == ISD::Constant) {
20759     SDValue N00 = N0.getOperand(0);
20760     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20761         ((N00.getOpcode() == ISD::ANY_EXTEND ||
20762           N00.getOpcode() == ISD::ZERO_EXTEND) &&
20763          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20764       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20765       APInt ShAmt = N1C->getAPIntValue();
20766       Mask = Mask.shl(ShAmt);
20767       if (Mask != 0)
20768         return DAG.getNode(ISD::AND, SDLoc(N), VT,
20769                            N00, DAG.getConstant(Mask, VT));
20770     }
20771   }
20772
20773   // Hardware support for vector shifts is sparse which makes us scalarize the
20774   // vector operations in many cases. Also, on sandybridge ADD is faster than
20775   // shl.
20776   // (shl V, 1) -> add V,V
20777   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20778     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
20779       assert(N0.getValueType().isVector() && "Invalid vector shift type");
20780       // We shift all of the values by one. In many cases we do not have
20781       // hardware support for this operation. This is better expressed as an ADD
20782       // of two values.
20783       if (N1SplatC->getZExtValue() == 1)
20784         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20785     }
20786
20787   return SDValue();
20788 }
20789
20790 /// \brief Returns a vector of 0s if the node in input is a vector logical
20791 /// shift by a constant amount which is known to be bigger than or equal
20792 /// to the vector element size in bits.
20793 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20794                                       const X86Subtarget *Subtarget) {
20795   EVT VT = N->getValueType(0);
20796
20797   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20798       (!Subtarget->hasInt256() ||
20799        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20800     return SDValue();
20801
20802   SDValue Amt = N->getOperand(1);
20803   SDLoc DL(N);
20804   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20805     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
20806       APInt ShiftAmt = AmtSplat->getAPIntValue();
20807       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20808
20809       // SSE2/AVX2 logical shifts always return a vector of 0s
20810       // if the shift amount is bigger than or equal to
20811       // the element size. The constant shift amount will be
20812       // encoded as a 8-bit immediate.
20813       if (ShiftAmt.trunc(8).uge(MaxAmount))
20814         return getZeroVector(VT, Subtarget, DAG, DL);
20815     }
20816
20817   return SDValue();
20818 }
20819
20820 /// PerformShiftCombine - Combine shifts.
20821 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20822                                    TargetLowering::DAGCombinerInfo &DCI,
20823                                    const X86Subtarget *Subtarget) {
20824   if (N->getOpcode() == ISD::SHL) {
20825     SDValue V = PerformSHLCombine(N, DAG);
20826     if (V.getNode()) return V;
20827   }
20828
20829   if (N->getOpcode() != ISD::SRA) {
20830     // Try to fold this logical shift into a zero vector.
20831     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20832     if (V.getNode()) return V;
20833   }
20834
20835   return SDValue();
20836 }
20837
20838 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
20839 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20840 // and friends.  Likewise for OR -> CMPNEQSS.
20841 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20842                             TargetLowering::DAGCombinerInfo &DCI,
20843                             const X86Subtarget *Subtarget) {
20844   unsigned opcode;
20845
20846   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20847   // we're requiring SSE2 for both.
20848   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20849     SDValue N0 = N->getOperand(0);
20850     SDValue N1 = N->getOperand(1);
20851     SDValue CMP0 = N0->getOperand(1);
20852     SDValue CMP1 = N1->getOperand(1);
20853     SDLoc DL(N);
20854
20855     // The SETCCs should both refer to the same CMP.
20856     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20857       return SDValue();
20858
20859     SDValue CMP00 = CMP0->getOperand(0);
20860     SDValue CMP01 = CMP0->getOperand(1);
20861     EVT     VT    = CMP00.getValueType();
20862
20863     if (VT == MVT::f32 || VT == MVT::f64) {
20864       bool ExpectingFlags = false;
20865       // Check for any users that want flags:
20866       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20867            !ExpectingFlags && UI != UE; ++UI)
20868         switch (UI->getOpcode()) {
20869         default:
20870         case ISD::BR_CC:
20871         case ISD::BRCOND:
20872         case ISD::SELECT:
20873           ExpectingFlags = true;
20874           break;
20875         case ISD::CopyToReg:
20876         case ISD::SIGN_EXTEND:
20877         case ISD::ZERO_EXTEND:
20878         case ISD::ANY_EXTEND:
20879           break;
20880         }
20881
20882       if (!ExpectingFlags) {
20883         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20884         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20885
20886         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20887           X86::CondCode tmp = cc0;
20888           cc0 = cc1;
20889           cc1 = tmp;
20890         }
20891
20892         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
20893             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20894           // FIXME: need symbolic constants for these magic numbers.
20895           // See X86ATTInstPrinter.cpp:printSSECC().
20896           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20897           if (Subtarget->hasAVX512()) {
20898             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20899                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
20900             if (N->getValueType(0) != MVT::i1)
20901               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20902                                  FSetCC);
20903             return FSetCC;
20904           }
20905           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20906                                               CMP00.getValueType(), CMP00, CMP01,
20907                                               DAG.getConstant(x86cc, MVT::i8));
20908
20909           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20910           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20911
20912           if (is64BitFP && !Subtarget->is64Bit()) {
20913             // On a 32-bit target, we cannot bitcast the 64-bit float to a
20914             // 64-bit integer, since that's not a legal type. Since
20915             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20916             // bits, but can do this little dance to extract the lowest 32 bits
20917             // and work with those going forward.
20918             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20919                                            OnesOrZeroesF);
20920             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20921                                            Vector64);
20922             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20923                                         Vector32, DAG.getIntPtrConstant(0));
20924             IntVT = MVT::i32;
20925           }
20926
20927           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20928           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20929                                       DAG.getConstant(1, IntVT));
20930           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20931           return OneBitOfTruth;
20932         }
20933       }
20934     }
20935   }
20936   return SDValue();
20937 }
20938
20939 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20940 /// so it can be folded inside ANDNP.
20941 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20942   EVT VT = N->getValueType(0);
20943
20944   // Match direct AllOnes for 128 and 256-bit vectors
20945   if (ISD::isBuildVectorAllOnes(N))
20946     return true;
20947
20948   // Look through a bit convert.
20949   if (N->getOpcode() == ISD::BITCAST)
20950     N = N->getOperand(0).getNode();
20951
20952   // Sometimes the operand may come from a insert_subvector building a 256-bit
20953   // allones vector
20954   if (VT.is256BitVector() &&
20955       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20956     SDValue V1 = N->getOperand(0);
20957     SDValue V2 = N->getOperand(1);
20958
20959     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20960         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20961         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20962         ISD::isBuildVectorAllOnes(V2.getNode()))
20963       return true;
20964   }
20965
20966   return false;
20967 }
20968
20969 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20970 // register. In most cases we actually compare or select YMM-sized registers
20971 // and mixing the two types creates horrible code. This method optimizes
20972 // some of the transition sequences.
20973 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20974                                  TargetLowering::DAGCombinerInfo &DCI,
20975                                  const X86Subtarget *Subtarget) {
20976   EVT VT = N->getValueType(0);
20977   if (!VT.is256BitVector())
20978     return SDValue();
20979
20980   assert((N->getOpcode() == ISD::ANY_EXTEND ||
20981           N->getOpcode() == ISD::ZERO_EXTEND ||
20982           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20983
20984   SDValue Narrow = N->getOperand(0);
20985   EVT NarrowVT = Narrow->getValueType(0);
20986   if (!NarrowVT.is128BitVector())
20987     return SDValue();
20988
20989   if (Narrow->getOpcode() != ISD::XOR &&
20990       Narrow->getOpcode() != ISD::AND &&
20991       Narrow->getOpcode() != ISD::OR)
20992     return SDValue();
20993
20994   SDValue N0  = Narrow->getOperand(0);
20995   SDValue N1  = Narrow->getOperand(1);
20996   SDLoc DL(Narrow);
20997
20998   // The Left side has to be a trunc.
20999   if (N0.getOpcode() != ISD::TRUNCATE)
21000     return SDValue();
21001
21002   // The type of the truncated inputs.
21003   EVT WideVT = N0->getOperand(0)->getValueType(0);
21004   if (WideVT != VT)
21005     return SDValue();
21006
21007   // The right side has to be a 'trunc' or a constant vector.
21008   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21009   ConstantSDNode *RHSConstSplat = nullptr;
21010   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21011     RHSConstSplat = RHSBV->getConstantSplatNode();
21012   if (!RHSTrunc && !RHSConstSplat)
21013     return SDValue();
21014
21015   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21016
21017   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21018     return SDValue();
21019
21020   // Set N0 and N1 to hold the inputs to the new wide operation.
21021   N0 = N0->getOperand(0);
21022   if (RHSConstSplat) {
21023     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21024                      SDValue(RHSConstSplat, 0));
21025     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21026     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21027   } else if (RHSTrunc) {
21028     N1 = N1->getOperand(0);
21029   }
21030
21031   // Generate the wide operation.
21032   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21033   unsigned Opcode = N->getOpcode();
21034   switch (Opcode) {
21035   case ISD::ANY_EXTEND:
21036     return Op;
21037   case ISD::ZERO_EXTEND: {
21038     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21039     APInt Mask = APInt::getAllOnesValue(InBits);
21040     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21041     return DAG.getNode(ISD::AND, DL, VT,
21042                        Op, DAG.getConstant(Mask, VT));
21043   }
21044   case ISD::SIGN_EXTEND:
21045     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21046                        Op, DAG.getValueType(NarrowVT));
21047   default:
21048     llvm_unreachable("Unexpected opcode");
21049   }
21050 }
21051
21052 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21053                                  TargetLowering::DAGCombinerInfo &DCI,
21054                                  const X86Subtarget *Subtarget) {
21055   EVT VT = N->getValueType(0);
21056   if (DCI.isBeforeLegalizeOps())
21057     return SDValue();
21058
21059   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21060   if (R.getNode())
21061     return R;
21062
21063   // Create BEXTR instructions
21064   // BEXTR is ((X >> imm) & (2**size-1))
21065   if (VT == MVT::i32 || VT == MVT::i64) {
21066     SDValue N0 = N->getOperand(0);
21067     SDValue N1 = N->getOperand(1);
21068     SDLoc DL(N);
21069
21070     // Check for BEXTR.
21071     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21072         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21073       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21074       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21075       if (MaskNode && ShiftNode) {
21076         uint64_t Mask = MaskNode->getZExtValue();
21077         uint64_t Shift = ShiftNode->getZExtValue();
21078         if (isMask_64(Mask)) {
21079           uint64_t MaskSize = CountPopulation_64(Mask);
21080           if (Shift + MaskSize <= VT.getSizeInBits())
21081             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21082                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21083         }
21084       }
21085     } // BEXTR
21086
21087     return SDValue();
21088   }
21089
21090   // Want to form ANDNP nodes:
21091   // 1) In the hopes of then easily combining them with OR and AND nodes
21092   //    to form PBLEND/PSIGN.
21093   // 2) To match ANDN packed intrinsics
21094   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21095     return SDValue();
21096
21097   SDValue N0 = N->getOperand(0);
21098   SDValue N1 = N->getOperand(1);
21099   SDLoc DL(N);
21100
21101   // Check LHS for vnot
21102   if (N0.getOpcode() == ISD::XOR &&
21103       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21104       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21105     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21106
21107   // Check RHS for vnot
21108   if (N1.getOpcode() == ISD::XOR &&
21109       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21110       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21111     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21112
21113   return SDValue();
21114 }
21115
21116 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21117                                 TargetLowering::DAGCombinerInfo &DCI,
21118                                 const X86Subtarget *Subtarget) {
21119   if (DCI.isBeforeLegalizeOps())
21120     return SDValue();
21121
21122   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21123   if (R.getNode())
21124     return R;
21125
21126   SDValue N0 = N->getOperand(0);
21127   SDValue N1 = N->getOperand(1);
21128   EVT VT = N->getValueType(0);
21129
21130   // look for psign/blend
21131   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21132     if (!Subtarget->hasSSSE3() ||
21133         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21134       return SDValue();
21135
21136     // Canonicalize pandn to RHS
21137     if (N0.getOpcode() == X86ISD::ANDNP)
21138       std::swap(N0, N1);
21139     // or (and (m, y), (pandn m, x))
21140     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21141       SDValue Mask = N1.getOperand(0);
21142       SDValue X    = N1.getOperand(1);
21143       SDValue Y;
21144       if (N0.getOperand(0) == Mask)
21145         Y = N0.getOperand(1);
21146       if (N0.getOperand(1) == Mask)
21147         Y = N0.getOperand(0);
21148
21149       // Check to see if the mask appeared in both the AND and ANDNP and
21150       if (!Y.getNode())
21151         return SDValue();
21152
21153       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21154       // Look through mask bitcast.
21155       if (Mask.getOpcode() == ISD::BITCAST)
21156         Mask = Mask.getOperand(0);
21157       if (X.getOpcode() == ISD::BITCAST)
21158         X = X.getOperand(0);
21159       if (Y.getOpcode() == ISD::BITCAST)
21160         Y = Y.getOperand(0);
21161
21162       EVT MaskVT = Mask.getValueType();
21163
21164       // Validate that the Mask operand is a vector sra node.
21165       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21166       // there is no psrai.b
21167       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21168       unsigned SraAmt = ~0;
21169       if (Mask.getOpcode() == ISD::SRA) {
21170         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21171           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21172             SraAmt = AmtConst->getZExtValue();
21173       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21174         SDValue SraC = Mask.getOperand(1);
21175         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21176       }
21177       if ((SraAmt + 1) != EltBits)
21178         return SDValue();
21179
21180       SDLoc DL(N);
21181
21182       // Now we know we at least have a plendvb with the mask val.  See if
21183       // we can form a psignb/w/d.
21184       // psign = x.type == y.type == mask.type && y = sub(0, x);
21185       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21186           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21187           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21188         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21189                "Unsupported VT for PSIGN");
21190         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21191         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21192       }
21193       // PBLENDVB only available on SSE 4.1
21194       if (!Subtarget->hasSSE41())
21195         return SDValue();
21196
21197       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21198
21199       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21200       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21201       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21202       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21203       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21204     }
21205   }
21206
21207   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21208     return SDValue();
21209
21210   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21211   MachineFunction &MF = DAG.getMachineFunction();
21212   bool OptForSize = MF.getFunction()->getAttributes().
21213     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21214
21215   // SHLD/SHRD instructions have lower register pressure, but on some
21216   // platforms they have higher latency than the equivalent
21217   // series of shifts/or that would otherwise be generated.
21218   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21219   // have higher latencies and we are not optimizing for size.
21220   if (!OptForSize && Subtarget->isSHLDSlow())
21221     return SDValue();
21222
21223   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21224     std::swap(N0, N1);
21225   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21226     return SDValue();
21227   if (!N0.hasOneUse() || !N1.hasOneUse())
21228     return SDValue();
21229
21230   SDValue ShAmt0 = N0.getOperand(1);
21231   if (ShAmt0.getValueType() != MVT::i8)
21232     return SDValue();
21233   SDValue ShAmt1 = N1.getOperand(1);
21234   if (ShAmt1.getValueType() != MVT::i8)
21235     return SDValue();
21236   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21237     ShAmt0 = ShAmt0.getOperand(0);
21238   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21239     ShAmt1 = ShAmt1.getOperand(0);
21240
21241   SDLoc DL(N);
21242   unsigned Opc = X86ISD::SHLD;
21243   SDValue Op0 = N0.getOperand(0);
21244   SDValue Op1 = N1.getOperand(0);
21245   if (ShAmt0.getOpcode() == ISD::SUB) {
21246     Opc = X86ISD::SHRD;
21247     std::swap(Op0, Op1);
21248     std::swap(ShAmt0, ShAmt1);
21249   }
21250
21251   unsigned Bits = VT.getSizeInBits();
21252   if (ShAmt1.getOpcode() == ISD::SUB) {
21253     SDValue Sum = ShAmt1.getOperand(0);
21254     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21255       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21256       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21257         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21258       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21259         return DAG.getNode(Opc, DL, VT,
21260                            Op0, Op1,
21261                            DAG.getNode(ISD::TRUNCATE, DL,
21262                                        MVT::i8, ShAmt0));
21263     }
21264   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21265     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21266     if (ShAmt0C &&
21267         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21268       return DAG.getNode(Opc, DL, VT,
21269                          N0.getOperand(0), N1.getOperand(0),
21270                          DAG.getNode(ISD::TRUNCATE, DL,
21271                                        MVT::i8, ShAmt0));
21272   }
21273
21274   return SDValue();
21275 }
21276
21277 // Generate NEG and CMOV for integer abs.
21278 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21279   EVT VT = N->getValueType(0);
21280
21281   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21282   // 8-bit integer abs to NEG and CMOV.
21283   if (VT.isInteger() && VT.getSizeInBits() == 8)
21284     return SDValue();
21285
21286   SDValue N0 = N->getOperand(0);
21287   SDValue N1 = N->getOperand(1);
21288   SDLoc DL(N);
21289
21290   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21291   // and change it to SUB and CMOV.
21292   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21293       N0.getOpcode() == ISD::ADD &&
21294       N0.getOperand(1) == N1 &&
21295       N1.getOpcode() == ISD::SRA &&
21296       N1.getOperand(0) == N0.getOperand(0))
21297     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21298       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21299         // Generate SUB & CMOV.
21300         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21301                                   DAG.getConstant(0, VT), N0.getOperand(0));
21302
21303         SDValue Ops[] = { N0.getOperand(0), Neg,
21304                           DAG.getConstant(X86::COND_GE, MVT::i8),
21305                           SDValue(Neg.getNode(), 1) };
21306         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21307       }
21308   return SDValue();
21309 }
21310
21311 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21312 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21313                                  TargetLowering::DAGCombinerInfo &DCI,
21314                                  const X86Subtarget *Subtarget) {
21315   if (DCI.isBeforeLegalizeOps())
21316     return SDValue();
21317
21318   if (Subtarget->hasCMov()) {
21319     SDValue RV = performIntegerAbsCombine(N, DAG);
21320     if (RV.getNode())
21321       return RV;
21322   }
21323
21324   return SDValue();
21325 }
21326
21327 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21328 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21329                                   TargetLowering::DAGCombinerInfo &DCI,
21330                                   const X86Subtarget *Subtarget) {
21331   LoadSDNode *Ld = cast<LoadSDNode>(N);
21332   EVT RegVT = Ld->getValueType(0);
21333   EVT MemVT = Ld->getMemoryVT();
21334   SDLoc dl(Ld);
21335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21336
21337   // On Sandybridge unaligned 256bit loads are inefficient.
21338   ISD::LoadExtType Ext = Ld->getExtensionType();
21339   unsigned Alignment = Ld->getAlignment();
21340   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21341   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21342       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21343     unsigned NumElems = RegVT.getVectorNumElements();
21344     if (NumElems < 2)
21345       return SDValue();
21346
21347     SDValue Ptr = Ld->getBasePtr();
21348     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21349
21350     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21351                                   NumElems/2);
21352     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21353                                 Ld->getPointerInfo(), Ld->isVolatile(),
21354                                 Ld->isNonTemporal(), Ld->isInvariant(),
21355                                 Alignment);
21356     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21357     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21358                                 Ld->getPointerInfo(), Ld->isVolatile(),
21359                                 Ld->isNonTemporal(), Ld->isInvariant(),
21360                                 std::min(16U, Alignment));
21361     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21362                              Load1.getValue(1),
21363                              Load2.getValue(1));
21364
21365     SDValue NewVec = DAG.getUNDEF(RegVT);
21366     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21367     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21368     return DCI.CombineTo(N, NewVec, TF, true);
21369   }
21370
21371   return SDValue();
21372 }
21373
21374 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21375 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21376                                    const X86Subtarget *Subtarget) {
21377   StoreSDNode *St = cast<StoreSDNode>(N);
21378   EVT VT = St->getValue().getValueType();
21379   EVT StVT = St->getMemoryVT();
21380   SDLoc dl(St);
21381   SDValue StoredVal = St->getOperand(1);
21382   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21383
21384   // If we are saving a concatenation of two XMM registers, perform two stores.
21385   // On Sandy Bridge, 256-bit memory operations are executed by two
21386   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21387   // memory  operation.
21388   unsigned Alignment = St->getAlignment();
21389   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21390   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21391       StVT == VT && !IsAligned) {
21392     unsigned NumElems = VT.getVectorNumElements();
21393     if (NumElems < 2)
21394       return SDValue();
21395
21396     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21397     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21398
21399     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21400     SDValue Ptr0 = St->getBasePtr();
21401     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21402
21403     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21404                                 St->getPointerInfo(), St->isVolatile(),
21405                                 St->isNonTemporal(), Alignment);
21406     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21407                                 St->getPointerInfo(), St->isVolatile(),
21408                                 St->isNonTemporal(),
21409                                 std::min(16U, Alignment));
21410     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21411   }
21412
21413   // Optimize trunc store (of multiple scalars) to shuffle and store.
21414   // First, pack all of the elements in one place. Next, store to memory
21415   // in fewer chunks.
21416   if (St->isTruncatingStore() && VT.isVector()) {
21417     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21418     unsigned NumElems = VT.getVectorNumElements();
21419     assert(StVT != VT && "Cannot truncate to the same type");
21420     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21421     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21422
21423     // From, To sizes and ElemCount must be pow of two
21424     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21425     // We are going to use the original vector elt for storing.
21426     // Accumulated smaller vector elements must be a multiple of the store size.
21427     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21428
21429     unsigned SizeRatio  = FromSz / ToSz;
21430
21431     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21432
21433     // Create a type on which we perform the shuffle
21434     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21435             StVT.getScalarType(), NumElems*SizeRatio);
21436
21437     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21438
21439     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21440     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21441     for (unsigned i = 0; i != NumElems; ++i)
21442       ShuffleVec[i] = i * SizeRatio;
21443
21444     // Can't shuffle using an illegal type.
21445     if (!TLI.isTypeLegal(WideVecVT))
21446       return SDValue();
21447
21448     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21449                                          DAG.getUNDEF(WideVecVT),
21450                                          &ShuffleVec[0]);
21451     // At this point all of the data is stored at the bottom of the
21452     // register. We now need to save it to mem.
21453
21454     // Find the largest store unit
21455     MVT StoreType = MVT::i8;
21456     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21457          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21458       MVT Tp = (MVT::SimpleValueType)tp;
21459       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21460         StoreType = Tp;
21461     }
21462
21463     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21464     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21465         (64 <= NumElems * ToSz))
21466       StoreType = MVT::f64;
21467
21468     // Bitcast the original vector into a vector of store-size units
21469     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21470             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21471     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21472     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21473     SmallVector<SDValue, 8> Chains;
21474     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21475                                         TLI.getPointerTy());
21476     SDValue Ptr = St->getBasePtr();
21477
21478     // Perform one or more big stores into memory.
21479     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21480       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21481                                    StoreType, ShuffWide,
21482                                    DAG.getIntPtrConstant(i));
21483       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21484                                 St->getPointerInfo(), St->isVolatile(),
21485                                 St->isNonTemporal(), St->getAlignment());
21486       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21487       Chains.push_back(Ch);
21488     }
21489
21490     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21491   }
21492
21493   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21494   // the FP state in cases where an emms may be missing.
21495   // A preferable solution to the general problem is to figure out the right
21496   // places to insert EMMS.  This qualifies as a quick hack.
21497
21498   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21499   if (VT.getSizeInBits() != 64)
21500     return SDValue();
21501
21502   const Function *F = DAG.getMachineFunction().getFunction();
21503   bool NoImplicitFloatOps = F->getAttributes().
21504     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21505   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21506                      && Subtarget->hasSSE2();
21507   if ((VT.isVector() ||
21508        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21509       isa<LoadSDNode>(St->getValue()) &&
21510       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21511       St->getChain().hasOneUse() && !St->isVolatile()) {
21512     SDNode* LdVal = St->getValue().getNode();
21513     LoadSDNode *Ld = nullptr;
21514     int TokenFactorIndex = -1;
21515     SmallVector<SDValue, 8> Ops;
21516     SDNode* ChainVal = St->getChain().getNode();
21517     // Must be a store of a load.  We currently handle two cases:  the load
21518     // is a direct child, and it's under an intervening TokenFactor.  It is
21519     // possible to dig deeper under nested TokenFactors.
21520     if (ChainVal == LdVal)
21521       Ld = cast<LoadSDNode>(St->getChain());
21522     else if (St->getValue().hasOneUse() &&
21523              ChainVal->getOpcode() == ISD::TokenFactor) {
21524       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21525         if (ChainVal->getOperand(i).getNode() == LdVal) {
21526           TokenFactorIndex = i;
21527           Ld = cast<LoadSDNode>(St->getValue());
21528         } else
21529           Ops.push_back(ChainVal->getOperand(i));
21530       }
21531     }
21532
21533     if (!Ld || !ISD::isNormalLoad(Ld))
21534       return SDValue();
21535
21536     // If this is not the MMX case, i.e. we are just turning i64 load/store
21537     // into f64 load/store, avoid the transformation if there are multiple
21538     // uses of the loaded value.
21539     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21540       return SDValue();
21541
21542     SDLoc LdDL(Ld);
21543     SDLoc StDL(N);
21544     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21545     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21546     // pair instead.
21547     if (Subtarget->is64Bit() || F64IsLegal) {
21548       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21549       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21550                                   Ld->getPointerInfo(), Ld->isVolatile(),
21551                                   Ld->isNonTemporal(), Ld->isInvariant(),
21552                                   Ld->getAlignment());
21553       SDValue NewChain = NewLd.getValue(1);
21554       if (TokenFactorIndex != -1) {
21555         Ops.push_back(NewChain);
21556         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21557       }
21558       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21559                           St->getPointerInfo(),
21560                           St->isVolatile(), St->isNonTemporal(),
21561                           St->getAlignment());
21562     }
21563
21564     // Otherwise, lower to two pairs of 32-bit loads / stores.
21565     SDValue LoAddr = Ld->getBasePtr();
21566     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21567                                  DAG.getConstant(4, MVT::i32));
21568
21569     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21570                                Ld->getPointerInfo(),
21571                                Ld->isVolatile(), Ld->isNonTemporal(),
21572                                Ld->isInvariant(), Ld->getAlignment());
21573     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21574                                Ld->getPointerInfo().getWithOffset(4),
21575                                Ld->isVolatile(), Ld->isNonTemporal(),
21576                                Ld->isInvariant(),
21577                                MinAlign(Ld->getAlignment(), 4));
21578
21579     SDValue NewChain = LoLd.getValue(1);
21580     if (TokenFactorIndex != -1) {
21581       Ops.push_back(LoLd);
21582       Ops.push_back(HiLd);
21583       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21584     }
21585
21586     LoAddr = St->getBasePtr();
21587     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21588                          DAG.getConstant(4, MVT::i32));
21589
21590     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21591                                 St->getPointerInfo(),
21592                                 St->isVolatile(), St->isNonTemporal(),
21593                                 St->getAlignment());
21594     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21595                                 St->getPointerInfo().getWithOffset(4),
21596                                 St->isVolatile(),
21597                                 St->isNonTemporal(),
21598                                 MinAlign(St->getAlignment(), 4));
21599     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21600   }
21601   return SDValue();
21602 }
21603
21604 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21605 /// and return the operands for the horizontal operation in LHS and RHS.  A
21606 /// horizontal operation performs the binary operation on successive elements
21607 /// of its first operand, then on successive elements of its second operand,
21608 /// returning the resulting values in a vector.  For example, if
21609 ///   A = < float a0, float a1, float a2, float a3 >
21610 /// and
21611 ///   B = < float b0, float b1, float b2, float b3 >
21612 /// then the result of doing a horizontal operation on A and B is
21613 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21614 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21615 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21616 /// set to A, RHS to B, and the routine returns 'true'.
21617 /// Note that the binary operation should have the property that if one of the
21618 /// operands is UNDEF then the result is UNDEF.
21619 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21620   // Look for the following pattern: if
21621   //   A = < float a0, float a1, float a2, float a3 >
21622   //   B = < float b0, float b1, float b2, float b3 >
21623   // and
21624   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21625   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21626   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21627   // which is A horizontal-op B.
21628
21629   // At least one of the operands should be a vector shuffle.
21630   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21631       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21632     return false;
21633
21634   MVT VT = LHS.getSimpleValueType();
21635
21636   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21637          "Unsupported vector type for horizontal add/sub");
21638
21639   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21640   // operate independently on 128-bit lanes.
21641   unsigned NumElts = VT.getVectorNumElements();
21642   unsigned NumLanes = VT.getSizeInBits()/128;
21643   unsigned NumLaneElts = NumElts / NumLanes;
21644   assert((NumLaneElts % 2 == 0) &&
21645          "Vector type should have an even number of elements in each lane");
21646   unsigned HalfLaneElts = NumLaneElts/2;
21647
21648   // View LHS in the form
21649   //   LHS = VECTOR_SHUFFLE A, B, LMask
21650   // If LHS is not a shuffle then pretend it is the shuffle
21651   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21652   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21653   // type VT.
21654   SDValue A, B;
21655   SmallVector<int, 16> LMask(NumElts);
21656   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21657     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21658       A = LHS.getOperand(0);
21659     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21660       B = LHS.getOperand(1);
21661     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21662     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21663   } else {
21664     if (LHS.getOpcode() != ISD::UNDEF)
21665       A = LHS;
21666     for (unsigned i = 0; i != NumElts; ++i)
21667       LMask[i] = i;
21668   }
21669
21670   // Likewise, view RHS in the form
21671   //   RHS = VECTOR_SHUFFLE C, D, RMask
21672   SDValue C, D;
21673   SmallVector<int, 16> RMask(NumElts);
21674   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21675     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21676       C = RHS.getOperand(0);
21677     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21678       D = RHS.getOperand(1);
21679     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21680     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21681   } else {
21682     if (RHS.getOpcode() != ISD::UNDEF)
21683       C = RHS;
21684     for (unsigned i = 0; i != NumElts; ++i)
21685       RMask[i] = i;
21686   }
21687
21688   // Check that the shuffles are both shuffling the same vectors.
21689   if (!(A == C && B == D) && !(A == D && B == C))
21690     return false;
21691
21692   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21693   if (!A.getNode() && !B.getNode())
21694     return false;
21695
21696   // If A and B occur in reverse order in RHS, then "swap" them (which means
21697   // rewriting the mask).
21698   if (A != C)
21699     CommuteVectorShuffleMask(RMask, NumElts);
21700
21701   // At this point LHS and RHS are equivalent to
21702   //   LHS = VECTOR_SHUFFLE A, B, LMask
21703   //   RHS = VECTOR_SHUFFLE A, B, RMask
21704   // Check that the masks correspond to performing a horizontal operation.
21705   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21706     for (unsigned i = 0; i != NumLaneElts; ++i) {
21707       int LIdx = LMask[i+l], RIdx = RMask[i+l];
21708
21709       // Ignore any UNDEF components.
21710       if (LIdx < 0 || RIdx < 0 ||
21711           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21712           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21713         continue;
21714
21715       // Check that successive elements are being operated on.  If not, this is
21716       // not a horizontal operation.
21717       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21718       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21719       if (!(LIdx == Index && RIdx == Index + 1) &&
21720           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21721         return false;
21722     }
21723   }
21724
21725   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21726   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21727   return true;
21728 }
21729
21730 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21731 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21732                                   const X86Subtarget *Subtarget) {
21733   EVT VT = N->getValueType(0);
21734   SDValue LHS = N->getOperand(0);
21735   SDValue RHS = N->getOperand(1);
21736
21737   // Try to synthesize horizontal adds from adds of shuffles.
21738   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21739        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21740       isHorizontalBinOp(LHS, RHS, true))
21741     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21742   return SDValue();
21743 }
21744
21745 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21746 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21747                                   const X86Subtarget *Subtarget) {
21748   EVT VT = N->getValueType(0);
21749   SDValue LHS = N->getOperand(0);
21750   SDValue RHS = N->getOperand(1);
21751
21752   // Try to synthesize horizontal subs from subs of shuffles.
21753   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21754        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21755       isHorizontalBinOp(LHS, RHS, false))
21756     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21757   return SDValue();
21758 }
21759
21760 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21761 /// X86ISD::FXOR nodes.
21762 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21763   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21764   // F[X]OR(0.0, x) -> x
21765   // F[X]OR(x, 0.0) -> x
21766   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21767     if (C->getValueAPF().isPosZero())
21768       return N->getOperand(1);
21769   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21770     if (C->getValueAPF().isPosZero())
21771       return N->getOperand(0);
21772   return SDValue();
21773 }
21774
21775 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21776 /// X86ISD::FMAX nodes.
21777 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21778   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21779
21780   // Only perform optimizations if UnsafeMath is used.
21781   if (!DAG.getTarget().Options.UnsafeFPMath)
21782     return SDValue();
21783
21784   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21785   // into FMINC and FMAXC, which are Commutative operations.
21786   unsigned NewOp = 0;
21787   switch (N->getOpcode()) {
21788     default: llvm_unreachable("unknown opcode");
21789     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
21790     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
21791   }
21792
21793   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21794                      N->getOperand(0), N->getOperand(1));
21795 }
21796
21797 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21798 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21799   // FAND(0.0, x) -> 0.0
21800   // FAND(x, 0.0) -> 0.0
21801   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21802     if (C->getValueAPF().isPosZero())
21803       return N->getOperand(0);
21804   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21805     if (C->getValueAPF().isPosZero())
21806       return N->getOperand(1);
21807   return SDValue();
21808 }
21809
21810 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21811 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21812   // FANDN(x, 0.0) -> 0.0
21813   // FANDN(0.0, x) -> x
21814   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21815     if (C->getValueAPF().isPosZero())
21816       return N->getOperand(1);
21817   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21818     if (C->getValueAPF().isPosZero())
21819       return N->getOperand(1);
21820   return SDValue();
21821 }
21822
21823 static SDValue PerformBTCombine(SDNode *N,
21824                                 SelectionDAG &DAG,
21825                                 TargetLowering::DAGCombinerInfo &DCI) {
21826   // BT ignores high bits in the bit index operand.
21827   SDValue Op1 = N->getOperand(1);
21828   if (Op1.hasOneUse()) {
21829     unsigned BitWidth = Op1.getValueSizeInBits();
21830     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21831     APInt KnownZero, KnownOne;
21832     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21833                                           !DCI.isBeforeLegalizeOps());
21834     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21835     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21836         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21837       DCI.CommitTargetLoweringOpt(TLO);
21838   }
21839   return SDValue();
21840 }
21841
21842 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21843   SDValue Op = N->getOperand(0);
21844   if (Op.getOpcode() == ISD::BITCAST)
21845     Op = Op.getOperand(0);
21846   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21847   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21848       VT.getVectorElementType().getSizeInBits() ==
21849       OpVT.getVectorElementType().getSizeInBits()) {
21850     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21851   }
21852   return SDValue();
21853 }
21854
21855 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21856                                                const X86Subtarget *Subtarget) {
21857   EVT VT = N->getValueType(0);
21858   if (!VT.isVector())
21859     return SDValue();
21860
21861   SDValue N0 = N->getOperand(0);
21862   SDValue N1 = N->getOperand(1);
21863   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21864   SDLoc dl(N);
21865
21866   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21867   // both SSE and AVX2 since there is no sign-extended shift right
21868   // operation on a vector with 64-bit elements.
21869   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21870   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21871   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21872       N0.getOpcode() == ISD::SIGN_EXTEND)) {
21873     SDValue N00 = N0.getOperand(0);
21874
21875     // EXTLOAD has a better solution on AVX2,
21876     // it may be replaced with X86ISD::VSEXT node.
21877     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21878       if (!ISD::isNormalLoad(N00.getNode()))
21879         return SDValue();
21880
21881     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21882         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21883                                   N00, N1);
21884       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21885     }
21886   }
21887   return SDValue();
21888 }
21889
21890 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21891                                   TargetLowering::DAGCombinerInfo &DCI,
21892                                   const X86Subtarget *Subtarget) {
21893   if (!DCI.isBeforeLegalizeOps())
21894     return SDValue();
21895
21896   if (!Subtarget->hasFp256())
21897     return SDValue();
21898
21899   EVT VT = N->getValueType(0);
21900   if (VT.isVector() && VT.getSizeInBits() == 256) {
21901     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21902     if (R.getNode())
21903       return R;
21904   }
21905
21906   return SDValue();
21907 }
21908
21909 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21910                                  const X86Subtarget* Subtarget) {
21911   SDLoc dl(N);
21912   EVT VT = N->getValueType(0);
21913
21914   // Let legalize expand this if it isn't a legal type yet.
21915   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21916     return SDValue();
21917
21918   EVT ScalarVT = VT.getScalarType();
21919   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21920       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21921     return SDValue();
21922
21923   SDValue A = N->getOperand(0);
21924   SDValue B = N->getOperand(1);
21925   SDValue C = N->getOperand(2);
21926
21927   bool NegA = (A.getOpcode() == ISD::FNEG);
21928   bool NegB = (B.getOpcode() == ISD::FNEG);
21929   bool NegC = (C.getOpcode() == ISD::FNEG);
21930
21931   // Negative multiplication when NegA xor NegB
21932   bool NegMul = (NegA != NegB);
21933   if (NegA)
21934     A = A.getOperand(0);
21935   if (NegB)
21936     B = B.getOperand(0);
21937   if (NegC)
21938     C = C.getOperand(0);
21939
21940   unsigned Opcode;
21941   if (!NegMul)
21942     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21943   else
21944     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21945
21946   return DAG.getNode(Opcode, dl, VT, A, B, C);
21947 }
21948
21949 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21950                                   TargetLowering::DAGCombinerInfo &DCI,
21951                                   const X86Subtarget *Subtarget) {
21952   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
21953   //           (and (i32 x86isd::setcc_carry), 1)
21954   // This eliminates the zext. This transformation is necessary because
21955   // ISD::SETCC is always legalized to i8.
21956   SDLoc dl(N);
21957   SDValue N0 = N->getOperand(0);
21958   EVT VT = N->getValueType(0);
21959
21960   if (N0.getOpcode() == ISD::AND &&
21961       N0.hasOneUse() &&
21962       N0.getOperand(0).hasOneUse()) {
21963     SDValue N00 = N0.getOperand(0);
21964     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21965       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21966       if (!C || C->getZExtValue() != 1)
21967         return SDValue();
21968       return DAG.getNode(ISD::AND, dl, VT,
21969                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21970                                      N00.getOperand(0), N00.getOperand(1)),
21971                          DAG.getConstant(1, VT));
21972     }
21973   }
21974
21975   if (N0.getOpcode() == ISD::TRUNCATE &&
21976       N0.hasOneUse() &&
21977       N0.getOperand(0).hasOneUse()) {
21978     SDValue N00 = N0.getOperand(0);
21979     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21980       return DAG.getNode(ISD::AND, dl, VT,
21981                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21982                                      N00.getOperand(0), N00.getOperand(1)),
21983                          DAG.getConstant(1, VT));
21984     }
21985   }
21986   if (VT.is256BitVector()) {
21987     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21988     if (R.getNode())
21989       return R;
21990   }
21991
21992   return SDValue();
21993 }
21994
21995 // Optimize x == -y --> x+y == 0
21996 //          x != -y --> x+y != 0
21997 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21998                                       const X86Subtarget* Subtarget) {
21999   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22000   SDValue LHS = N->getOperand(0);
22001   SDValue RHS = N->getOperand(1);
22002   EVT VT = N->getValueType(0);
22003   SDLoc DL(N);
22004
22005   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22006     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22007       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22008         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22009                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22010         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22011                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22012       }
22013   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22014     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22015       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22016         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22017                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22018         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22019                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22020       }
22021
22022   if (VT.getScalarType() == MVT::i1) {
22023     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22024       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22025     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22026     if (!IsSEXT0 && !IsVZero0)
22027       return SDValue();
22028     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22029       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22030     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22031
22032     if (!IsSEXT1 && !IsVZero1)
22033       return SDValue();
22034
22035     if (IsSEXT0 && IsVZero1) {
22036       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22037       if (CC == ISD::SETEQ)
22038         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22039       return LHS.getOperand(0);
22040     }
22041     if (IsSEXT1 && IsVZero0) {
22042       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22043       if (CC == ISD::SETEQ)
22044         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22045       return RHS.getOperand(0);
22046     }
22047   }
22048
22049   return SDValue();
22050 }
22051
22052 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22053                                       const X86Subtarget *Subtarget) {
22054   SDLoc dl(N);
22055   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22056   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22057          "X86insertps is only defined for v4x32");
22058
22059   SDValue Ld = N->getOperand(1);
22060   if (MayFoldLoad(Ld)) {
22061     // Extract the countS bits from the immediate so we can get the proper
22062     // address when narrowing the vector load to a specific element.
22063     // When the second source op is a memory address, interps doesn't use
22064     // countS and just gets an f32 from that address.
22065     unsigned DestIndex =
22066         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22067     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22068   } else
22069     return SDValue();
22070
22071   // Create this as a scalar to vector to match the instruction pattern.
22072   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22073   // countS bits are ignored when loading from memory on insertps, which
22074   // means we don't need to explicitly set them to 0.
22075   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22076                      LoadScalarToVector, N->getOperand(2));
22077 }
22078
22079 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22080 // as "sbb reg,reg", since it can be extended without zext and produces
22081 // an all-ones bit which is more useful than 0/1 in some cases.
22082 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22083                                MVT VT) {
22084   if (VT == MVT::i8)
22085     return DAG.getNode(ISD::AND, DL, VT,
22086                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22087                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22088                        DAG.getConstant(1, VT));
22089   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22090   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22091                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22092                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22093 }
22094
22095 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22096 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22097                                    TargetLowering::DAGCombinerInfo &DCI,
22098                                    const X86Subtarget *Subtarget) {
22099   SDLoc DL(N);
22100   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22101   SDValue EFLAGS = N->getOperand(1);
22102
22103   if (CC == X86::COND_A) {
22104     // Try to convert COND_A into COND_B in an attempt to facilitate
22105     // materializing "setb reg".
22106     //
22107     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22108     // cannot take an immediate as its first operand.
22109     //
22110     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22111         EFLAGS.getValueType().isInteger() &&
22112         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22113       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22114                                    EFLAGS.getNode()->getVTList(),
22115                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22116       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22117       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22118     }
22119   }
22120
22121   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22122   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22123   // cases.
22124   if (CC == X86::COND_B)
22125     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22126
22127   SDValue Flags;
22128
22129   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22130   if (Flags.getNode()) {
22131     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22132     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22133   }
22134
22135   return SDValue();
22136 }
22137
22138 // Optimize branch condition evaluation.
22139 //
22140 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22141                                     TargetLowering::DAGCombinerInfo &DCI,
22142                                     const X86Subtarget *Subtarget) {
22143   SDLoc DL(N);
22144   SDValue Chain = N->getOperand(0);
22145   SDValue Dest = N->getOperand(1);
22146   SDValue EFLAGS = N->getOperand(3);
22147   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22148
22149   SDValue Flags;
22150
22151   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22152   if (Flags.getNode()) {
22153     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22154     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22155                        Flags);
22156   }
22157
22158   return SDValue();
22159 }
22160
22161 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22162                                                          SelectionDAG &DAG) {
22163   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22164   // optimize away operation when it's from a constant.
22165   //
22166   // The general transformation is:
22167   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22168   //       AND(VECTOR_CMP(x,y), constant2)
22169   //    constant2 = UNARYOP(constant)
22170
22171   // Early exit if this isn't a vector operation, the operand of the
22172   // unary operation isn't a bitwise AND, or if the sizes of the operations
22173   // aren't the same.
22174   EVT VT = N->getValueType(0);
22175   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22176       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22177       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22178     return SDValue();
22179
22180   // Now check that the other operand of the AND is a constant. We could
22181   // make the transformation for non-constant splats as well, but it's unclear
22182   // that would be a benefit as it would not eliminate any operations, just
22183   // perform one more step in scalar code before moving to the vector unit.
22184   if (BuildVectorSDNode *BV =
22185           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22186     // Bail out if the vector isn't a constant.
22187     if (!BV->isConstant())
22188       return SDValue();
22189
22190     // Everything checks out. Build up the new and improved node.
22191     SDLoc DL(N);
22192     EVT IntVT = BV->getValueType(0);
22193     // Create a new constant of the appropriate type for the transformed
22194     // DAG.
22195     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22196     // The AND node needs bitcasts to/from an integer vector type around it.
22197     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22198     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22199                                  N->getOperand(0)->getOperand(0), MaskConst);
22200     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22201     return Res;
22202   }
22203
22204   return SDValue();
22205 }
22206
22207 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22208                                         const X86TargetLowering *XTLI) {
22209   // First try to optimize away the conversion entirely when it's
22210   // conditionally from a constant. Vectors only.
22211   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22212   if (Res != SDValue())
22213     return Res;
22214
22215   // Now move on to more general possibilities.
22216   SDValue Op0 = N->getOperand(0);
22217   EVT InVT = Op0->getValueType(0);
22218
22219   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22220   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22221     SDLoc dl(N);
22222     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22223     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22224     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22225   }
22226
22227   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22228   // a 32-bit target where SSE doesn't support i64->FP operations.
22229   if (Op0.getOpcode() == ISD::LOAD) {
22230     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22231     EVT VT = Ld->getValueType(0);
22232     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22233         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22234         !XTLI->getSubtarget()->is64Bit() &&
22235         VT == MVT::i64) {
22236       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22237                                           Ld->getChain(), Op0, DAG);
22238       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22239       return FILDChain;
22240     }
22241   }
22242   return SDValue();
22243 }
22244
22245 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22246 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22247                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22248   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22249   // the result is either zero or one (depending on the input carry bit).
22250   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22251   if (X86::isZeroNode(N->getOperand(0)) &&
22252       X86::isZeroNode(N->getOperand(1)) &&
22253       // We don't have a good way to replace an EFLAGS use, so only do this when
22254       // dead right now.
22255       SDValue(N, 1).use_empty()) {
22256     SDLoc DL(N);
22257     EVT VT = N->getValueType(0);
22258     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22259     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22260                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22261                                            DAG.getConstant(X86::COND_B,MVT::i8),
22262                                            N->getOperand(2)),
22263                                DAG.getConstant(1, VT));
22264     return DCI.CombineTo(N, Res1, CarryOut);
22265   }
22266
22267   return SDValue();
22268 }
22269
22270 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22271 //      (add Y, (setne X, 0)) -> sbb -1, Y
22272 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22273 //      (sub (setne X, 0), Y) -> adc -1, Y
22274 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22275   SDLoc DL(N);
22276
22277   // Look through ZExts.
22278   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22279   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22280     return SDValue();
22281
22282   SDValue SetCC = Ext.getOperand(0);
22283   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22284     return SDValue();
22285
22286   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22287   if (CC != X86::COND_E && CC != X86::COND_NE)
22288     return SDValue();
22289
22290   SDValue Cmp = SetCC.getOperand(1);
22291   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22292       !X86::isZeroNode(Cmp.getOperand(1)) ||
22293       !Cmp.getOperand(0).getValueType().isInteger())
22294     return SDValue();
22295
22296   SDValue CmpOp0 = Cmp.getOperand(0);
22297   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22298                                DAG.getConstant(1, CmpOp0.getValueType()));
22299
22300   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22301   if (CC == X86::COND_NE)
22302     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22303                        DL, OtherVal.getValueType(), OtherVal,
22304                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22305   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22306                      DL, OtherVal.getValueType(), OtherVal,
22307                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22308 }
22309
22310 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22311 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22312                                  const X86Subtarget *Subtarget) {
22313   EVT VT = N->getValueType(0);
22314   SDValue Op0 = N->getOperand(0);
22315   SDValue Op1 = N->getOperand(1);
22316
22317   // Try to synthesize horizontal adds from adds of shuffles.
22318   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22319        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22320       isHorizontalBinOp(Op0, Op1, true))
22321     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22322
22323   return OptimizeConditionalInDecrement(N, DAG);
22324 }
22325
22326 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22327                                  const X86Subtarget *Subtarget) {
22328   SDValue Op0 = N->getOperand(0);
22329   SDValue Op1 = N->getOperand(1);
22330
22331   // X86 can't encode an immediate LHS of a sub. See if we can push the
22332   // negation into a preceding instruction.
22333   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22334     // If the RHS of the sub is a XOR with one use and a constant, invert the
22335     // immediate. Then add one to the LHS of the sub so we can turn
22336     // X-Y -> X+~Y+1, saving one register.
22337     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22338         isa<ConstantSDNode>(Op1.getOperand(1))) {
22339       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22340       EVT VT = Op0.getValueType();
22341       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22342                                    Op1.getOperand(0),
22343                                    DAG.getConstant(~XorC, VT));
22344       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22345                          DAG.getConstant(C->getAPIntValue()+1, VT));
22346     }
22347   }
22348
22349   // Try to synthesize horizontal adds from adds of shuffles.
22350   EVT VT = N->getValueType(0);
22351   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22352        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22353       isHorizontalBinOp(Op0, Op1, true))
22354     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22355
22356   return OptimizeConditionalInDecrement(N, DAG);
22357 }
22358
22359 /// performVZEXTCombine - Performs build vector combines
22360 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22361                                         TargetLowering::DAGCombinerInfo &DCI,
22362                                         const X86Subtarget *Subtarget) {
22363   // (vzext (bitcast (vzext (x)) -> (vzext x)
22364   SDValue In = N->getOperand(0);
22365   while (In.getOpcode() == ISD::BITCAST)
22366     In = In.getOperand(0);
22367
22368   if (In.getOpcode() != X86ISD::VZEXT)
22369     return SDValue();
22370
22371   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22372                      In.getOperand(0));
22373 }
22374
22375 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22376                                              DAGCombinerInfo &DCI) const {
22377   SelectionDAG &DAG = DCI.DAG;
22378   switch (N->getOpcode()) {
22379   default: break;
22380   case ISD::EXTRACT_VECTOR_ELT:
22381     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22382   case ISD::VSELECT:
22383   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22384   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22385   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22386   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22387   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22388   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22389   case ISD::SHL:
22390   case ISD::SRA:
22391   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22392   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22393   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22394   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22395   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22396   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22397   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22398   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22399   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22400   case X86ISD::FXOR:
22401   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22402   case X86ISD::FMIN:
22403   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22404   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22405   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22406   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22407   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22408   case ISD::ANY_EXTEND:
22409   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22410   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22411   case ISD::SIGN_EXTEND_INREG:
22412     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22413   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22414   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22415   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22416   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22417   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22418   case X86ISD::SHUFP:       // Handle all target specific shuffles
22419   case X86ISD::PALIGNR:
22420   case X86ISD::UNPCKH:
22421   case X86ISD::UNPCKL:
22422   case X86ISD::MOVHLPS:
22423   case X86ISD::MOVLHPS:
22424   case X86ISD::PSHUFD:
22425   case X86ISD::PSHUFHW:
22426   case X86ISD::PSHUFLW:
22427   case X86ISD::MOVSS:
22428   case X86ISD::MOVSD:
22429   case X86ISD::VPERMILP:
22430   case X86ISD::VPERM2X128:
22431   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22432   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22433   case ISD::INTRINSIC_WO_CHAIN:
22434     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22435   case X86ISD::INSERTPS:
22436     return PerformINSERTPSCombine(N, DAG, Subtarget);
22437   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22438   }
22439
22440   return SDValue();
22441 }
22442
22443 /// isTypeDesirableForOp - Return true if the target has native support for
22444 /// the specified value type and it is 'desirable' to use the type for the
22445 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22446 /// instruction encodings are longer and some i16 instructions are slow.
22447 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22448   if (!isTypeLegal(VT))
22449     return false;
22450   if (VT != MVT::i16)
22451     return true;
22452
22453   switch (Opc) {
22454   default:
22455     return true;
22456   case ISD::LOAD:
22457   case ISD::SIGN_EXTEND:
22458   case ISD::ZERO_EXTEND:
22459   case ISD::ANY_EXTEND:
22460   case ISD::SHL:
22461   case ISD::SRL:
22462   case ISD::SUB:
22463   case ISD::ADD:
22464   case ISD::MUL:
22465   case ISD::AND:
22466   case ISD::OR:
22467   case ISD::XOR:
22468     return false;
22469   }
22470 }
22471
22472 /// IsDesirableToPromoteOp - This method query the target whether it is
22473 /// beneficial for dag combiner to promote the specified node. If true, it
22474 /// should return the desired promotion type by reference.
22475 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22476   EVT VT = Op.getValueType();
22477   if (VT != MVT::i16)
22478     return false;
22479
22480   bool Promote = false;
22481   bool Commute = false;
22482   switch (Op.getOpcode()) {
22483   default: break;
22484   case ISD::LOAD: {
22485     LoadSDNode *LD = cast<LoadSDNode>(Op);
22486     // If the non-extending load has a single use and it's not live out, then it
22487     // might be folded.
22488     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22489                                                      Op.hasOneUse()*/) {
22490       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22491              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22492         // The only case where we'd want to promote LOAD (rather then it being
22493         // promoted as an operand is when it's only use is liveout.
22494         if (UI->getOpcode() != ISD::CopyToReg)
22495           return false;
22496       }
22497     }
22498     Promote = true;
22499     break;
22500   }
22501   case ISD::SIGN_EXTEND:
22502   case ISD::ZERO_EXTEND:
22503   case ISD::ANY_EXTEND:
22504     Promote = true;
22505     break;
22506   case ISD::SHL:
22507   case ISD::SRL: {
22508     SDValue N0 = Op.getOperand(0);
22509     // Look out for (store (shl (load), x)).
22510     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22511       return false;
22512     Promote = true;
22513     break;
22514   }
22515   case ISD::ADD:
22516   case ISD::MUL:
22517   case ISD::AND:
22518   case ISD::OR:
22519   case ISD::XOR:
22520     Commute = true;
22521     // fallthrough
22522   case ISD::SUB: {
22523     SDValue N0 = Op.getOperand(0);
22524     SDValue N1 = Op.getOperand(1);
22525     if (!Commute && MayFoldLoad(N1))
22526       return false;
22527     // Avoid disabling potential load folding opportunities.
22528     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22529       return false;
22530     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22531       return false;
22532     Promote = true;
22533   }
22534   }
22535
22536   PVT = MVT::i32;
22537   return Promote;
22538 }
22539
22540 //===----------------------------------------------------------------------===//
22541 //                           X86 Inline Assembly Support
22542 //===----------------------------------------------------------------------===//
22543
22544 namespace {
22545   // Helper to match a string separated by whitespace.
22546   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22547     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22548
22549     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22550       StringRef piece(*args[i]);
22551       if (!s.startswith(piece)) // Check if the piece matches.
22552         return false;
22553
22554       s = s.substr(piece.size());
22555       StringRef::size_type pos = s.find_first_not_of(" \t");
22556       if (pos == 0) // We matched a prefix.
22557         return false;
22558
22559       s = s.substr(pos);
22560     }
22561
22562     return s.empty();
22563   }
22564   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22565 }
22566
22567 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22568
22569   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22570     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22571         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22572         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22573
22574       if (AsmPieces.size() == 3)
22575         return true;
22576       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22577         return true;
22578     }
22579   }
22580   return false;
22581 }
22582
22583 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22584   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22585
22586   std::string AsmStr = IA->getAsmString();
22587
22588   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22589   if (!Ty || Ty->getBitWidth() % 16 != 0)
22590     return false;
22591
22592   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22593   SmallVector<StringRef, 4> AsmPieces;
22594   SplitString(AsmStr, AsmPieces, ";\n");
22595
22596   switch (AsmPieces.size()) {
22597   default: return false;
22598   case 1:
22599     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22600     // we will turn this bswap into something that will be lowered to logical
22601     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22602     // lower so don't worry about this.
22603     // bswap $0
22604     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22605         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22606         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22607         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22608         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22609         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22610       // No need to check constraints, nothing other than the equivalent of
22611       // "=r,0" would be valid here.
22612       return IntrinsicLowering::LowerToByteSwap(CI);
22613     }
22614
22615     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22616     if (CI->getType()->isIntegerTy(16) &&
22617         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22618         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22619          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22620       AsmPieces.clear();
22621       const std::string &ConstraintsStr = IA->getConstraintString();
22622       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22623       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22624       if (clobbersFlagRegisters(AsmPieces))
22625         return IntrinsicLowering::LowerToByteSwap(CI);
22626     }
22627     break;
22628   case 3:
22629     if (CI->getType()->isIntegerTy(32) &&
22630         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22631         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22632         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22633         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22634       AsmPieces.clear();
22635       const std::string &ConstraintsStr = IA->getConstraintString();
22636       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22637       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22638       if (clobbersFlagRegisters(AsmPieces))
22639         return IntrinsicLowering::LowerToByteSwap(CI);
22640     }
22641
22642     if (CI->getType()->isIntegerTy(64)) {
22643       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22644       if (Constraints.size() >= 2 &&
22645           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22646           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22647         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22648         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22649             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22650             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22651           return IntrinsicLowering::LowerToByteSwap(CI);
22652       }
22653     }
22654     break;
22655   }
22656   return false;
22657 }
22658
22659 /// getConstraintType - Given a constraint letter, return the type of
22660 /// constraint it is for this target.
22661 X86TargetLowering::ConstraintType
22662 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22663   if (Constraint.size() == 1) {
22664     switch (Constraint[0]) {
22665     case 'R':
22666     case 'q':
22667     case 'Q':
22668     case 'f':
22669     case 't':
22670     case 'u':
22671     case 'y':
22672     case 'x':
22673     case 'Y':
22674     case 'l':
22675       return C_RegisterClass;
22676     case 'a':
22677     case 'b':
22678     case 'c':
22679     case 'd':
22680     case 'S':
22681     case 'D':
22682     case 'A':
22683       return C_Register;
22684     case 'I':
22685     case 'J':
22686     case 'K':
22687     case 'L':
22688     case 'M':
22689     case 'N':
22690     case 'G':
22691     case 'C':
22692     case 'e':
22693     case 'Z':
22694       return C_Other;
22695     default:
22696       break;
22697     }
22698   }
22699   return TargetLowering::getConstraintType(Constraint);
22700 }
22701
22702 /// Examine constraint type and operand type and determine a weight value.
22703 /// This object must already have been set up with the operand type
22704 /// and the current alternative constraint selected.
22705 TargetLowering::ConstraintWeight
22706   X86TargetLowering::getSingleConstraintMatchWeight(
22707     AsmOperandInfo &info, const char *constraint) const {
22708   ConstraintWeight weight = CW_Invalid;
22709   Value *CallOperandVal = info.CallOperandVal;
22710     // If we don't have a value, we can't do a match,
22711     // but allow it at the lowest weight.
22712   if (!CallOperandVal)
22713     return CW_Default;
22714   Type *type = CallOperandVal->getType();
22715   // Look at the constraint type.
22716   switch (*constraint) {
22717   default:
22718     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22719   case 'R':
22720   case 'q':
22721   case 'Q':
22722   case 'a':
22723   case 'b':
22724   case 'c':
22725   case 'd':
22726   case 'S':
22727   case 'D':
22728   case 'A':
22729     if (CallOperandVal->getType()->isIntegerTy())
22730       weight = CW_SpecificReg;
22731     break;
22732   case 'f':
22733   case 't':
22734   case 'u':
22735     if (type->isFloatingPointTy())
22736       weight = CW_SpecificReg;
22737     break;
22738   case 'y':
22739     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22740       weight = CW_SpecificReg;
22741     break;
22742   case 'x':
22743   case 'Y':
22744     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22745         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22746       weight = CW_Register;
22747     break;
22748   case 'I':
22749     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22750       if (C->getZExtValue() <= 31)
22751         weight = CW_Constant;
22752     }
22753     break;
22754   case 'J':
22755     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22756       if (C->getZExtValue() <= 63)
22757         weight = CW_Constant;
22758     }
22759     break;
22760   case 'K':
22761     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22762       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22763         weight = CW_Constant;
22764     }
22765     break;
22766   case 'L':
22767     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22768       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22769         weight = CW_Constant;
22770     }
22771     break;
22772   case 'M':
22773     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22774       if (C->getZExtValue() <= 3)
22775         weight = CW_Constant;
22776     }
22777     break;
22778   case 'N':
22779     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22780       if (C->getZExtValue() <= 0xff)
22781         weight = CW_Constant;
22782     }
22783     break;
22784   case 'G':
22785   case 'C':
22786     if (dyn_cast<ConstantFP>(CallOperandVal)) {
22787       weight = CW_Constant;
22788     }
22789     break;
22790   case 'e':
22791     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22792       if ((C->getSExtValue() >= -0x80000000LL) &&
22793           (C->getSExtValue() <= 0x7fffffffLL))
22794         weight = CW_Constant;
22795     }
22796     break;
22797   case 'Z':
22798     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22799       if (C->getZExtValue() <= 0xffffffff)
22800         weight = CW_Constant;
22801     }
22802     break;
22803   }
22804   return weight;
22805 }
22806
22807 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22808 /// with another that has more specific requirements based on the type of the
22809 /// corresponding operand.
22810 const char *X86TargetLowering::
22811 LowerXConstraint(EVT ConstraintVT) const {
22812   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22813   // 'f' like normal targets.
22814   if (ConstraintVT.isFloatingPoint()) {
22815     if (Subtarget->hasSSE2())
22816       return "Y";
22817     if (Subtarget->hasSSE1())
22818       return "x";
22819   }
22820
22821   return TargetLowering::LowerXConstraint(ConstraintVT);
22822 }
22823
22824 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22825 /// vector.  If it is invalid, don't add anything to Ops.
22826 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22827                                                      std::string &Constraint,
22828                                                      std::vector<SDValue>&Ops,
22829                                                      SelectionDAG &DAG) const {
22830   SDValue Result;
22831
22832   // Only support length 1 constraints for now.
22833   if (Constraint.length() > 1) return;
22834
22835   char ConstraintLetter = Constraint[0];
22836   switch (ConstraintLetter) {
22837   default: break;
22838   case 'I':
22839     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22840       if (C->getZExtValue() <= 31) {
22841         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22842         break;
22843       }
22844     }
22845     return;
22846   case 'J':
22847     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22848       if (C->getZExtValue() <= 63) {
22849         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22850         break;
22851       }
22852     }
22853     return;
22854   case 'K':
22855     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22856       if (isInt<8>(C->getSExtValue())) {
22857         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22858         break;
22859       }
22860     }
22861     return;
22862   case 'N':
22863     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22864       if (C->getZExtValue() <= 255) {
22865         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22866         break;
22867       }
22868     }
22869     return;
22870   case 'e': {
22871     // 32-bit signed value
22872     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22873       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22874                                            C->getSExtValue())) {
22875         // Widen to 64 bits here to get it sign extended.
22876         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22877         break;
22878       }
22879     // FIXME gcc accepts some relocatable values here too, but only in certain
22880     // memory models; it's complicated.
22881     }
22882     return;
22883   }
22884   case 'Z': {
22885     // 32-bit unsigned value
22886     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22887       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22888                                            C->getZExtValue())) {
22889         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22890         break;
22891       }
22892     }
22893     // FIXME gcc accepts some relocatable values here too, but only in certain
22894     // memory models; it's complicated.
22895     return;
22896   }
22897   case 'i': {
22898     // Literal immediates are always ok.
22899     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22900       // Widen to 64 bits here to get it sign extended.
22901       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22902       break;
22903     }
22904
22905     // In any sort of PIC mode addresses need to be computed at runtime by
22906     // adding in a register or some sort of table lookup.  These can't
22907     // be used as immediates.
22908     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22909       return;
22910
22911     // If we are in non-pic codegen mode, we allow the address of a global (with
22912     // an optional displacement) to be used with 'i'.
22913     GlobalAddressSDNode *GA = nullptr;
22914     int64_t Offset = 0;
22915
22916     // Match either (GA), (GA+C), (GA+C1+C2), etc.
22917     while (1) {
22918       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22919         Offset += GA->getOffset();
22920         break;
22921       } else if (Op.getOpcode() == ISD::ADD) {
22922         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22923           Offset += C->getZExtValue();
22924           Op = Op.getOperand(0);
22925           continue;
22926         }
22927       } else if (Op.getOpcode() == ISD::SUB) {
22928         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22929           Offset += -C->getZExtValue();
22930           Op = Op.getOperand(0);
22931           continue;
22932         }
22933       }
22934
22935       // Otherwise, this isn't something we can handle, reject it.
22936       return;
22937     }
22938
22939     const GlobalValue *GV = GA->getGlobal();
22940     // If we require an extra load to get this address, as in PIC mode, we
22941     // can't accept it.
22942     if (isGlobalStubReference(
22943             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22944       return;
22945
22946     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22947                                         GA->getValueType(0), Offset);
22948     break;
22949   }
22950   }
22951
22952   if (Result.getNode()) {
22953     Ops.push_back(Result);
22954     return;
22955   }
22956   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22957 }
22958
22959 std::pair<unsigned, const TargetRegisterClass*>
22960 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22961                                                 MVT VT) const {
22962   // First, see if this is a constraint that directly corresponds to an LLVM
22963   // register class.
22964   if (Constraint.size() == 1) {
22965     // GCC Constraint Letters
22966     switch (Constraint[0]) {
22967     default: break;
22968       // TODO: Slight differences here in allocation order and leaving
22969       // RIP in the class. Do they matter any more here than they do
22970       // in the normal allocation?
22971     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22972       if (Subtarget->is64Bit()) {
22973         if (VT == MVT::i32 || VT == MVT::f32)
22974           return std::make_pair(0U, &X86::GR32RegClass);
22975         if (VT == MVT::i16)
22976           return std::make_pair(0U, &X86::GR16RegClass);
22977         if (VT == MVT::i8 || VT == MVT::i1)
22978           return std::make_pair(0U, &X86::GR8RegClass);
22979         if (VT == MVT::i64 || VT == MVT::f64)
22980           return std::make_pair(0U, &X86::GR64RegClass);
22981         break;
22982       }
22983       // 32-bit fallthrough
22984     case 'Q':   // Q_REGS
22985       if (VT == MVT::i32 || VT == MVT::f32)
22986         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22987       if (VT == MVT::i16)
22988         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22989       if (VT == MVT::i8 || VT == MVT::i1)
22990         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22991       if (VT == MVT::i64)
22992         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22993       break;
22994     case 'r':   // GENERAL_REGS
22995     case 'l':   // INDEX_REGS
22996       if (VT == MVT::i8 || VT == MVT::i1)
22997         return std::make_pair(0U, &X86::GR8RegClass);
22998       if (VT == MVT::i16)
22999         return std::make_pair(0U, &X86::GR16RegClass);
23000       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23001         return std::make_pair(0U, &X86::GR32RegClass);
23002       return std::make_pair(0U, &X86::GR64RegClass);
23003     case 'R':   // LEGACY_REGS
23004       if (VT == MVT::i8 || VT == MVT::i1)
23005         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23006       if (VT == MVT::i16)
23007         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23008       if (VT == MVT::i32 || !Subtarget->is64Bit())
23009         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23010       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23011     case 'f':  // FP Stack registers.
23012       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23013       // value to the correct fpstack register class.
23014       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23015         return std::make_pair(0U, &X86::RFP32RegClass);
23016       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23017         return std::make_pair(0U, &X86::RFP64RegClass);
23018       return std::make_pair(0U, &X86::RFP80RegClass);
23019     case 'y':   // MMX_REGS if MMX allowed.
23020       if (!Subtarget->hasMMX()) break;
23021       return std::make_pair(0U, &X86::VR64RegClass);
23022     case 'Y':   // SSE_REGS if SSE2 allowed
23023       if (!Subtarget->hasSSE2()) break;
23024       // FALL THROUGH.
23025     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23026       if (!Subtarget->hasSSE1()) break;
23027
23028       switch (VT.SimpleTy) {
23029       default: break;
23030       // Scalar SSE types.
23031       case MVT::f32:
23032       case MVT::i32:
23033         return std::make_pair(0U, &X86::FR32RegClass);
23034       case MVT::f64:
23035       case MVT::i64:
23036         return std::make_pair(0U, &X86::FR64RegClass);
23037       // Vector types.
23038       case MVT::v16i8:
23039       case MVT::v8i16:
23040       case MVT::v4i32:
23041       case MVT::v2i64:
23042       case MVT::v4f32:
23043       case MVT::v2f64:
23044         return std::make_pair(0U, &X86::VR128RegClass);
23045       // AVX types.
23046       case MVT::v32i8:
23047       case MVT::v16i16:
23048       case MVT::v8i32:
23049       case MVT::v4i64:
23050       case MVT::v8f32:
23051       case MVT::v4f64:
23052         return std::make_pair(0U, &X86::VR256RegClass);
23053       case MVT::v8f64:
23054       case MVT::v16f32:
23055       case MVT::v16i32:
23056       case MVT::v8i64:
23057         return std::make_pair(0U, &X86::VR512RegClass);
23058       }
23059       break;
23060     }
23061   }
23062
23063   // Use the default implementation in TargetLowering to convert the register
23064   // constraint into a member of a register class.
23065   std::pair<unsigned, const TargetRegisterClass*> Res;
23066   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23067
23068   // Not found as a standard register?
23069   if (!Res.second) {
23070     // Map st(0) -> st(7) -> ST0
23071     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23072         tolower(Constraint[1]) == 's' &&
23073         tolower(Constraint[2]) == 't' &&
23074         Constraint[3] == '(' &&
23075         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23076         Constraint[5] == ')' &&
23077         Constraint[6] == '}') {
23078
23079       Res.first = X86::ST0+Constraint[4]-'0';
23080       Res.second = &X86::RFP80RegClass;
23081       return Res;
23082     }
23083
23084     // GCC allows "st(0)" to be called just plain "st".
23085     if (StringRef("{st}").equals_lower(Constraint)) {
23086       Res.first = X86::ST0;
23087       Res.second = &X86::RFP80RegClass;
23088       return Res;
23089     }
23090
23091     // flags -> EFLAGS
23092     if (StringRef("{flags}").equals_lower(Constraint)) {
23093       Res.first = X86::EFLAGS;
23094       Res.second = &X86::CCRRegClass;
23095       return Res;
23096     }
23097
23098     // 'A' means EAX + EDX.
23099     if (Constraint == "A") {
23100       Res.first = X86::EAX;
23101       Res.second = &X86::GR32_ADRegClass;
23102       return Res;
23103     }
23104     return Res;
23105   }
23106
23107   // Otherwise, check to see if this is a register class of the wrong value
23108   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23109   // turn into {ax},{dx}.
23110   if (Res.second->hasType(VT))
23111     return Res;   // Correct type already, nothing to do.
23112
23113   // All of the single-register GCC register classes map their values onto
23114   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23115   // really want an 8-bit or 32-bit register, map to the appropriate register
23116   // class and return the appropriate register.
23117   if (Res.second == &X86::GR16RegClass) {
23118     if (VT == MVT::i8 || VT == MVT::i1) {
23119       unsigned DestReg = 0;
23120       switch (Res.first) {
23121       default: break;
23122       case X86::AX: DestReg = X86::AL; break;
23123       case X86::DX: DestReg = X86::DL; break;
23124       case X86::CX: DestReg = X86::CL; break;
23125       case X86::BX: DestReg = X86::BL; break;
23126       }
23127       if (DestReg) {
23128         Res.first = DestReg;
23129         Res.second = &X86::GR8RegClass;
23130       }
23131     } else if (VT == MVT::i32 || VT == MVT::f32) {
23132       unsigned DestReg = 0;
23133       switch (Res.first) {
23134       default: break;
23135       case X86::AX: DestReg = X86::EAX; break;
23136       case X86::DX: DestReg = X86::EDX; break;
23137       case X86::CX: DestReg = X86::ECX; break;
23138       case X86::BX: DestReg = X86::EBX; break;
23139       case X86::SI: DestReg = X86::ESI; break;
23140       case X86::DI: DestReg = X86::EDI; break;
23141       case X86::BP: DestReg = X86::EBP; break;
23142       case X86::SP: DestReg = X86::ESP; break;
23143       }
23144       if (DestReg) {
23145         Res.first = DestReg;
23146         Res.second = &X86::GR32RegClass;
23147       }
23148     } else if (VT == MVT::i64 || VT == MVT::f64) {
23149       unsigned DestReg = 0;
23150       switch (Res.first) {
23151       default: break;
23152       case X86::AX: DestReg = X86::RAX; break;
23153       case X86::DX: DestReg = X86::RDX; break;
23154       case X86::CX: DestReg = X86::RCX; break;
23155       case X86::BX: DestReg = X86::RBX; break;
23156       case X86::SI: DestReg = X86::RSI; break;
23157       case X86::DI: DestReg = X86::RDI; break;
23158       case X86::BP: DestReg = X86::RBP; break;
23159       case X86::SP: DestReg = X86::RSP; break;
23160       }
23161       if (DestReg) {
23162         Res.first = DestReg;
23163         Res.second = &X86::GR64RegClass;
23164       }
23165     }
23166   } else if (Res.second == &X86::FR32RegClass ||
23167              Res.second == &X86::FR64RegClass ||
23168              Res.second == &X86::VR128RegClass ||
23169              Res.second == &X86::VR256RegClass ||
23170              Res.second == &X86::FR32XRegClass ||
23171              Res.second == &X86::FR64XRegClass ||
23172              Res.second == &X86::VR128XRegClass ||
23173              Res.second == &X86::VR256XRegClass ||
23174              Res.second == &X86::VR512RegClass) {
23175     // Handle references to XMM physical registers that got mapped into the
23176     // wrong class.  This can happen with constraints like {xmm0} where the
23177     // target independent register mapper will just pick the first match it can
23178     // find, ignoring the required type.
23179
23180     if (VT == MVT::f32 || VT == MVT::i32)
23181       Res.second = &X86::FR32RegClass;
23182     else if (VT == MVT::f64 || VT == MVT::i64)
23183       Res.second = &X86::FR64RegClass;
23184     else if (X86::VR128RegClass.hasType(VT))
23185       Res.second = &X86::VR128RegClass;
23186     else if (X86::VR256RegClass.hasType(VT))
23187       Res.second = &X86::VR256RegClass;
23188     else if (X86::VR512RegClass.hasType(VT))
23189       Res.second = &X86::VR512RegClass;
23190   }
23191
23192   return Res;
23193 }
23194
23195 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23196                                             Type *Ty) const {
23197   // Scaling factors are not free at all.
23198   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23199   // will take 2 allocations in the out of order engine instead of 1
23200   // for plain addressing mode, i.e. inst (reg1).
23201   // E.g.,
23202   // vaddps (%rsi,%drx), %ymm0, %ymm1
23203   // Requires two allocations (one for the load, one for the computation)
23204   // whereas:
23205   // vaddps (%rsi), %ymm0, %ymm1
23206   // Requires just 1 allocation, i.e., freeing allocations for other operations
23207   // and having less micro operations to execute.
23208   //
23209   // For some X86 architectures, this is even worse because for instance for
23210   // stores, the complex addressing mode forces the instruction to use the
23211   // "load" ports instead of the dedicated "store" port.
23212   // E.g., on Haswell:
23213   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23214   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23215   if (isLegalAddressingMode(AM, Ty))
23216     // Scale represents reg2 * scale, thus account for 1
23217     // as soon as we use a second register.
23218     return AM.Scale != 0;
23219   return -1;
23220 }
23221
23222 bool X86TargetLowering::isTargetFTOL() const {
23223   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23224 }