5f72d5004fd10eb75d9bbe2022fc7dfcdd79e8bc
[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_FP32, MVT::f32, Expand);
523     setOperationAction(ISD::FP32_TO_FP16, MVT::i16, Expand);
524   }
525
526   if (Subtarget->hasPOPCNT()) {
527     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
528   } else {
529     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
530     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
531     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
532     if (Subtarget->is64Bit())
533       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
534   }
535
536   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
537
538   if (!Subtarget->hasMOVBE())
539     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
540
541   // These should be promoted to a larger select which is supported.
542   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
543   // X86 wants to expand cmov itself.
544   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
545   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
546   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
547   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
548   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
549   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
550   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
551   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
552   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
553   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
554   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
555   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
556   if (Subtarget->is64Bit()) {
557     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
558     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
559   }
560   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
561   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
562   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
563   // support continuation, user-level threading, and etc.. As a result, no
564   // other SjLj exception interfaces are implemented and please don't build
565   // your own exception handling based on them.
566   // LLVM/Clang supports zero-cost DWARF exception handling.
567   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
568   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
569
570   // Darwin ABI issue.
571   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
572   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
573   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
574   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
575   if (Subtarget->is64Bit())
576     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
577   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
578   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
579   if (Subtarget->is64Bit()) {
580     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
581     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
582     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
583     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
584     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
585   }
586   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
587   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
588   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
589   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
592     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
593     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
594   }
595
596   if (Subtarget->hasSSE1())
597     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
598
599   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
600
601   // Expand certain atomics
602   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
603     MVT VT = IntVTs[i];
604     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
605     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
606     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
607   }
608
609   if (Subtarget->hasCmpxchg16b()) {
610     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
611   }
612
613   // FIXME - use subtarget debug flags
614   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
615       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
616     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
617   }
618
619   if (Subtarget->is64Bit()) {
620     setExceptionPointerRegister(X86::RAX);
621     setExceptionSelectorRegister(X86::RDX);
622   } else {
623     setExceptionPointerRegister(X86::EAX);
624     setExceptionSelectorRegister(X86::EDX);
625   }
626   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
627   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
628
629   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
630   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
631
632   setOperationAction(ISD::TRAP, MVT::Other, Legal);
633   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
634
635   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
636   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
637   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
638   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
639     // TargetInfo::X86_64ABIBuiltinVaList
640     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
641     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
642   } else {
643     // TargetInfo::CharPtrBuiltinVaList
644     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
645     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
646   }
647
648   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
649   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
650
651   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
652                      MVT::i64 : MVT::i32, Custom);
653
654   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
655     // f32 and f64 use SSE.
656     // Set up the FP register classes.
657     addRegisterClass(MVT::f32, &X86::FR32RegClass);
658     addRegisterClass(MVT::f64, &X86::FR64RegClass);
659
660     // Use ANDPD to simulate FABS.
661     setOperationAction(ISD::FABS , MVT::f64, Custom);
662     setOperationAction(ISD::FABS , MVT::f32, Custom);
663
664     // Use XORP to simulate FNEG.
665     setOperationAction(ISD::FNEG , MVT::f64, Custom);
666     setOperationAction(ISD::FNEG , MVT::f32, Custom);
667
668     // Use ANDPD and ORPD to simulate FCOPYSIGN.
669     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
670     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
671
672     // Lower this to FGETSIGNx86 plus an AND.
673     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
674     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
675
676     // We don't support sin/cos/fmod
677     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
678     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
679     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
680     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
681     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
682     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
683
684     // Expand FP immediates into loads from the stack, except for the special
685     // cases we handle.
686     addLegalFPImmediate(APFloat(+0.0)); // xorpd
687     addLegalFPImmediate(APFloat(+0.0f)); // xorps
688   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
689     // Use SSE for f32, x87 for f64.
690     // Set up the FP register classes.
691     addRegisterClass(MVT::f32, &X86::FR32RegClass);
692     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
693
694     // Use ANDPS to simulate FABS.
695     setOperationAction(ISD::FABS , MVT::f32, Custom);
696
697     // Use XORP to simulate FNEG.
698     setOperationAction(ISD::FNEG , MVT::f32, Custom);
699
700     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
701
702     // Use ANDPS and ORPS to simulate FCOPYSIGN.
703     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
704     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
705
706     // We don't support sin/cos/fmod
707     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
708     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
709     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
710
711     // Special cases we handle for FP constants.
712     addLegalFPImmediate(APFloat(+0.0f)); // xorps
713     addLegalFPImmediate(APFloat(+0.0)); // FLD0
714     addLegalFPImmediate(APFloat(+1.0)); // FLD1
715     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
716     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
717
718     if (!TM.Options.UnsafeFPMath) {
719       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
720       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
721       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
722     }
723   } else if (!TM.Options.UseSoftFloat) {
724     // f32 and f64 in x87.
725     // Set up the FP register classes.
726     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
727     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
728
729     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
730     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
731     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
732     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
733
734     if (!TM.Options.UnsafeFPMath) {
735       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
736       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
737       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
738       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
739       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
740       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
741     }
742     addLegalFPImmediate(APFloat(+0.0)); // FLD0
743     addLegalFPImmediate(APFloat(+1.0)); // FLD1
744     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
745     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
746     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
747     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
748     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
749     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
750   }
751
752   // We don't support FMA.
753   setOperationAction(ISD::FMA, MVT::f64, Expand);
754   setOperationAction(ISD::FMA, MVT::f32, Expand);
755
756   // Long double always uses X87.
757   if (!TM.Options.UseSoftFloat) {
758     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
759     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
760     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
761     {
762       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
763       addLegalFPImmediate(TmpFlt);  // FLD0
764       TmpFlt.changeSign();
765       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
766
767       bool ignored;
768       APFloat TmpFlt2(+1.0);
769       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
770                       &ignored);
771       addLegalFPImmediate(TmpFlt2);  // FLD1
772       TmpFlt2.changeSign();
773       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
774     }
775
776     if (!TM.Options.UnsafeFPMath) {
777       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
778       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
779       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
780     }
781
782     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
783     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
784     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
785     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
786     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
787     setOperationAction(ISD::FMA, MVT::f80, Expand);
788   }
789
790   // Always use a library call for pow.
791   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
792   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
793   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
794
795   setOperationAction(ISD::FLOG, MVT::f80, Expand);
796   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
797   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
798   setOperationAction(ISD::FEXP, MVT::f80, Expand);
799   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
800
801   // First set operation action for all vector types to either promote
802   // (for widening) or expand (for scalarization). Then we will selectively
803   // turn on ones that can be effectively codegen'd.
804   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
805            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
806     MVT VT = (MVT::SimpleValueType)i;
807     setOperationAction(ISD::ADD , VT, Expand);
808     setOperationAction(ISD::SUB , VT, Expand);
809     setOperationAction(ISD::FADD, VT, Expand);
810     setOperationAction(ISD::FNEG, VT, Expand);
811     setOperationAction(ISD::FSUB, VT, Expand);
812     setOperationAction(ISD::MUL , VT, Expand);
813     setOperationAction(ISD::FMUL, VT, Expand);
814     setOperationAction(ISD::SDIV, VT, Expand);
815     setOperationAction(ISD::UDIV, VT, Expand);
816     setOperationAction(ISD::FDIV, VT, Expand);
817     setOperationAction(ISD::SREM, VT, Expand);
818     setOperationAction(ISD::UREM, VT, Expand);
819     setOperationAction(ISD::LOAD, VT, Expand);
820     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
821     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
822     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
823     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
824     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
825     setOperationAction(ISD::FABS, VT, Expand);
826     setOperationAction(ISD::FSIN, VT, Expand);
827     setOperationAction(ISD::FSINCOS, VT, Expand);
828     setOperationAction(ISD::FCOS, VT, Expand);
829     setOperationAction(ISD::FSINCOS, VT, Expand);
830     setOperationAction(ISD::FREM, VT, Expand);
831     setOperationAction(ISD::FMA,  VT, Expand);
832     setOperationAction(ISD::FPOWI, VT, Expand);
833     setOperationAction(ISD::FSQRT, VT, Expand);
834     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
835     setOperationAction(ISD::FFLOOR, VT, Expand);
836     setOperationAction(ISD::FCEIL, VT, Expand);
837     setOperationAction(ISD::FTRUNC, VT, Expand);
838     setOperationAction(ISD::FRINT, VT, Expand);
839     setOperationAction(ISD::FNEARBYINT, VT, Expand);
840     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
841     setOperationAction(ISD::MULHS, VT, Expand);
842     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
843     setOperationAction(ISD::MULHU, VT, Expand);
844     setOperationAction(ISD::SDIVREM, VT, Expand);
845     setOperationAction(ISD::UDIVREM, VT, Expand);
846     setOperationAction(ISD::FPOW, VT, Expand);
847     setOperationAction(ISD::CTPOP, VT, Expand);
848     setOperationAction(ISD::CTTZ, VT, Expand);
849     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
850     setOperationAction(ISD::CTLZ, VT, Expand);
851     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
852     setOperationAction(ISD::SHL, VT, Expand);
853     setOperationAction(ISD::SRA, VT, Expand);
854     setOperationAction(ISD::SRL, VT, Expand);
855     setOperationAction(ISD::ROTL, VT, Expand);
856     setOperationAction(ISD::ROTR, VT, Expand);
857     setOperationAction(ISD::BSWAP, VT, Expand);
858     setOperationAction(ISD::SETCC, VT, Expand);
859     setOperationAction(ISD::FLOG, VT, Expand);
860     setOperationAction(ISD::FLOG2, VT, Expand);
861     setOperationAction(ISD::FLOG10, VT, Expand);
862     setOperationAction(ISD::FEXP, VT, Expand);
863     setOperationAction(ISD::FEXP2, VT, Expand);
864     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
865     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
866     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
867     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
868     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
869     setOperationAction(ISD::TRUNCATE, VT, Expand);
870     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
871     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
872     setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Expand);
873     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
874     setOperationAction(ISD::VSELECT, VT, Expand);
875     setOperationAction(ISD::SELECT_CC, VT, Expand);
876     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
877              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
878       setTruncStoreAction(VT,
879                           (MVT::SimpleValueType)InnerVT, Expand);
880     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
881     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
882     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
883   }
884
885   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
886   // with -msoft-float, disable use of MMX as well.
887   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
888     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
889     // No operations on x86mmx supported, everything uses intrinsics.
890   }
891
892   // MMX-sized vectors (other than x86mmx) are expected to be expanded
893   // into smaller operations.
894   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
895   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
896   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
897   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
898   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
899   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
900   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
901   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
902   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
903   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
904   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
905   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
906   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
907   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
908   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
909   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
910   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
911   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
912   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
913   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
914   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
915   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
916   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
917   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
918   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
919   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
920   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
921   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
922   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
923
924   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
925     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
926
927     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
928     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
929     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
930     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
931     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
932     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
933     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
934     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
935     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
936     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
937     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
938     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
939   }
940
941   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
942     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
943
944     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
945     // registers cannot be used even for integer operations.
946     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
947     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
948     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
949     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
950
951     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
952     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
953     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
954     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
955     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
956     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
957     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
958     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
959     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
960     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
961     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
962     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
963     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
964     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
965     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
966     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
967     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
968     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
969     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
970     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
971     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
972     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
973
974     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
975     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
976     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
977     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
978
979     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
980     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
981     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
982     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
983     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
984
985     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
986     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
987       MVT VT = (MVT::SimpleValueType)i;
988       // Do not attempt to custom lower non-power-of-2 vectors
989       if (!isPowerOf2_32(VT.getVectorNumElements()))
990         continue;
991       // Do not attempt to custom lower non-128-bit vectors
992       if (!VT.is128BitVector())
993         continue;
994       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
995       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
996       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
997     }
998
999     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1000     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1001     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1002     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1003     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1004     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1005
1006     if (Subtarget->is64Bit()) {
1007       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1008       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1009     }
1010
1011     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1012     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1013       MVT VT = (MVT::SimpleValueType)i;
1014
1015       // Do not attempt to promote non-128-bit vectors
1016       if (!VT.is128BitVector())
1017         continue;
1018
1019       setOperationAction(ISD::AND,    VT, Promote);
1020       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1021       setOperationAction(ISD::OR,     VT, Promote);
1022       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1023       setOperationAction(ISD::XOR,    VT, Promote);
1024       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1025       setOperationAction(ISD::LOAD,   VT, Promote);
1026       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1027       setOperationAction(ISD::SELECT, VT, Promote);
1028       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1029     }
1030
1031     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1032
1033     // Custom lower v2i64 and v2f64 selects.
1034     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1035     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1036     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1037     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1038
1039     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1040     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1041
1042     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1043     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1044     // As there is no 64-bit GPR available, we need build a special custom
1045     // sequence to convert from v2i32 to v2f32.
1046     if (!Subtarget->is64Bit())
1047       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1048
1049     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1050     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1051
1052     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1053
1054     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1055     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1056     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1057   }
1058
1059   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1060     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1061     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1062     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1063     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1064     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1065     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1066     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1067     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1068     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1069     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1070
1071     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1072     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1073     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1074     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1075     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1076     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1077     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1078     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1079     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1080     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1081
1082     // FIXME: Do we need to handle scalar-to-vector here?
1083     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1084
1085     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1086     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1087     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1088     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1089     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1090     // There is no BLENDI for byte vectors. We don't need to custom lower
1091     // some vselects for now.
1092     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1093
1094     // i8 and i16 vectors are custom , because the source register and source
1095     // source memory operand types are not the same width.  f32 vectors are
1096     // custom since the immediate controlling the insert encodes additional
1097     // information.
1098     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1099     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1100     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1101     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1102
1103     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1104     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1105     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1106     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1107
1108     // FIXME: these should be Legal but thats only for the case where
1109     // the index is constant.  For now custom expand to deal with that.
1110     if (Subtarget->is64Bit()) {
1111       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1112       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1113     }
1114   }
1115
1116   if (Subtarget->hasSSE2()) {
1117     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1118     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1119
1120     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1121     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1122
1123     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1124     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1125
1126     // In the customized shift lowering, the legal cases in AVX2 will be
1127     // recognized.
1128     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1129     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1130
1131     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1132     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1133
1134     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1135   }
1136
1137   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1138     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1139     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1140     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1141     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1142     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1143     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1144
1145     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1146     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1147     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1148
1149     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1150     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1151     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1152     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1153     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1154     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1155     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1156     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1157     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1158     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1159     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1160     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1161
1162     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1163     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1164     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1165     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1166     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1167     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1168     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1169     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1170     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1171     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1172     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1173     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1174
1175     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1176     // even though v8i16 is a legal type.
1177     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1178     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1179     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1180
1181     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1182     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1183     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1184
1185     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1186     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1187
1188     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1189
1190     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1191     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1192
1193     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1194     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1195
1196     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1197     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1198
1199     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1200     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1201     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1202     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1203
1204     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1205     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1206     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1207
1208     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1209     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1210     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1211     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1212
1213     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1214     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1215     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1216     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1217     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1218     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1219     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1220     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1221     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1222     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1223     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1224     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1225
1226     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1227       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1228       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1229       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1230       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1231       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1232       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1233     }
1234
1235     if (Subtarget->hasInt256()) {
1236       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1237       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1238       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1239       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1240
1241       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1242       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1243       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1244       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1245
1246       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1247       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1248       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1249       // Don't lower v32i8 because there is no 128-bit byte mul
1250
1251       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1252       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1253       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1254       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1255
1256       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1257       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1258     } else {
1259       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1260       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1261       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1262       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1263
1264       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1265       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1266       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1267       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1268
1269       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1270       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1271       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1272       // Don't lower v32i8 because there is no 128-bit byte mul
1273     }
1274
1275     // In the customized shift lowering, the legal cases in AVX2 will be
1276     // recognized.
1277     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1278     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1279
1280     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1281     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1282
1283     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1284
1285     // Custom lower several nodes for 256-bit types.
1286     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1287              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1288       MVT VT = (MVT::SimpleValueType)i;
1289
1290       // Extract subvector is special because the value type
1291       // (result) is 128-bit but the source is 256-bit wide.
1292       if (VT.is128BitVector())
1293         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1294
1295       // Do not attempt to custom lower other non-256-bit vectors
1296       if (!VT.is256BitVector())
1297         continue;
1298
1299       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1300       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1301       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1302       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1303       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1304       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1305       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1306     }
1307
1308     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1309     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1310       MVT VT = (MVT::SimpleValueType)i;
1311
1312       // Do not attempt to promote non-256-bit vectors
1313       if (!VT.is256BitVector())
1314         continue;
1315
1316       setOperationAction(ISD::AND,    VT, Promote);
1317       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1318       setOperationAction(ISD::OR,     VT, Promote);
1319       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1320       setOperationAction(ISD::XOR,    VT, Promote);
1321       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1322       setOperationAction(ISD::LOAD,   VT, Promote);
1323       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1324       setOperationAction(ISD::SELECT, VT, Promote);
1325       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1326     }
1327   }
1328
1329   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1330     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1331     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1332     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1333     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1334
1335     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1336     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1337     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1338
1339     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1340     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1341     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1342     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1343     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1344     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1345     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1346     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1347     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1348     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1349     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1350
1351     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1352     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1353     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1354     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1355     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1356     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1357
1358     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1359     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1360     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1361     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1362     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1363     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1364     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1365     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1366
1367     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1368     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1369     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1370     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1371     if (Subtarget->is64Bit()) {
1372       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1373       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1374       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1375       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1376     }
1377     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1378     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1379     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1380     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1381     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1382     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1383     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1384     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1385     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1386     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1387
1388     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1389     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1390     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1391     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1392     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1393     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1394     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1395     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1396     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1397     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1398     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1399     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1400     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1401
1402     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1403     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1404     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1405     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1406     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1407     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1408
1409     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1410     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1411
1412     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1413
1414     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1415     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1416     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1417     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1418     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1419     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1420     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1421     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1422     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1423
1424     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1425     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1426
1427     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1428     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1429
1430     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1431
1432     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1433     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1434
1435     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1436     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1437
1438     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1439     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1440
1441     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1442     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1443     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1444     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1445     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1446     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1447
1448     if (Subtarget->hasCDI()) {
1449       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1450       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1451     }
1452
1453     // Custom lower several nodes.
1454     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1455              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1456       MVT VT = (MVT::SimpleValueType)i;
1457
1458       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1459       // Extract subvector is special because the value type
1460       // (result) is 256/128-bit but the source is 512-bit wide.
1461       if (VT.is128BitVector() || VT.is256BitVector())
1462         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1463
1464       if (VT.getVectorElementType() == MVT::i1)
1465         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1466
1467       // Do not attempt to custom lower other non-512-bit vectors
1468       if (!VT.is512BitVector())
1469         continue;
1470
1471       if ( EltSize >= 32) {
1472         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1473         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1474         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1475         setOperationAction(ISD::VSELECT,             VT, Legal);
1476         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1477         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1478         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1479       }
1480     }
1481     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1482       MVT VT = (MVT::SimpleValueType)i;
1483
1484       // Do not attempt to promote non-256-bit vectors
1485       if (!VT.is512BitVector())
1486         continue;
1487
1488       setOperationAction(ISD::SELECT, VT, Promote);
1489       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1490     }
1491   }// has  AVX-512
1492
1493   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1494   // of this type with custom code.
1495   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1496            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1497     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1498                        Custom);
1499   }
1500
1501   // We want to custom lower some of our intrinsics.
1502   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1503   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1504   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1505   if (!Subtarget->is64Bit())
1506     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1507
1508   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1509   // handle type legalization for these operations here.
1510   //
1511   // FIXME: We really should do custom legalization for addition and
1512   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1513   // than generic legalization for 64-bit multiplication-with-overflow, though.
1514   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1515     // Add/Sub/Mul with overflow operations are custom lowered.
1516     MVT VT = IntVTs[i];
1517     setOperationAction(ISD::SADDO, VT, Custom);
1518     setOperationAction(ISD::UADDO, VT, Custom);
1519     setOperationAction(ISD::SSUBO, VT, Custom);
1520     setOperationAction(ISD::USUBO, VT, Custom);
1521     setOperationAction(ISD::SMULO, VT, Custom);
1522     setOperationAction(ISD::UMULO, VT, Custom);
1523   }
1524
1525   // There are no 8-bit 3-address imul/mul instructions
1526   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1527   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1528
1529   if (!Subtarget->is64Bit()) {
1530     // These libcalls are not available in 32-bit.
1531     setLibcallName(RTLIB::SHL_I128, nullptr);
1532     setLibcallName(RTLIB::SRL_I128, nullptr);
1533     setLibcallName(RTLIB::SRA_I128, nullptr);
1534   }
1535
1536   // Combine sin / cos into one node or libcall if possible.
1537   if (Subtarget->hasSinCos()) {
1538     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1539     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1540     if (Subtarget->isTargetDarwin()) {
1541       // For MacOSX, we don't want to the normal expansion of a libcall to
1542       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1543       // traffic.
1544       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1545       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1546     }
1547   }
1548
1549   if (Subtarget->isTargetWin64()) {
1550     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1551     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1552     setOperationAction(ISD::SREM, MVT::i128, Custom);
1553     setOperationAction(ISD::UREM, MVT::i128, Custom);
1554     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1555     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1556   }
1557
1558   // We have target-specific dag combine patterns for the following nodes:
1559   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1560   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1561   setTargetDAGCombine(ISD::VSELECT);
1562   setTargetDAGCombine(ISD::SELECT);
1563   setTargetDAGCombine(ISD::SHL);
1564   setTargetDAGCombine(ISD::SRA);
1565   setTargetDAGCombine(ISD::SRL);
1566   setTargetDAGCombine(ISD::OR);
1567   setTargetDAGCombine(ISD::AND);
1568   setTargetDAGCombine(ISD::ADD);
1569   setTargetDAGCombine(ISD::FADD);
1570   setTargetDAGCombine(ISD::FSUB);
1571   setTargetDAGCombine(ISD::FMA);
1572   setTargetDAGCombine(ISD::SUB);
1573   setTargetDAGCombine(ISD::LOAD);
1574   setTargetDAGCombine(ISD::STORE);
1575   setTargetDAGCombine(ISD::ZERO_EXTEND);
1576   setTargetDAGCombine(ISD::ANY_EXTEND);
1577   setTargetDAGCombine(ISD::SIGN_EXTEND);
1578   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1579   setTargetDAGCombine(ISD::TRUNCATE);
1580   setTargetDAGCombine(ISD::SINT_TO_FP);
1581   setTargetDAGCombine(ISD::SETCC);
1582   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1583   setTargetDAGCombine(ISD::BUILD_VECTOR);
1584   if (Subtarget->is64Bit())
1585     setTargetDAGCombine(ISD::MUL);
1586   setTargetDAGCombine(ISD::XOR);
1587
1588   computeRegisterProperties();
1589
1590   // On Darwin, -Os means optimize for size without hurting performance,
1591   // do not reduce the limit.
1592   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1593   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1594   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1595   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1596   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1597   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1598   setPrefLoopAlignment(4); // 2^4 bytes.
1599
1600   // Predictable cmov don't hurt on atom because it's in-order.
1601   PredictableSelectIsExpensive = !Subtarget->isAtom();
1602
1603   setPrefFunctionAlignment(4); // 2^4 bytes.
1604 }
1605
1606 TargetLoweringBase::LegalizeTypeAction
1607 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1608   if (ExperimentalVectorWideningLegalization &&
1609       VT.getVectorNumElements() != 1 &&
1610       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1611     return TypeWidenVector;
1612
1613   return TargetLoweringBase::getPreferredVectorAction(VT);
1614 }
1615
1616 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1617   if (!VT.isVector())
1618     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1619
1620   if (Subtarget->hasAVX512())
1621     switch(VT.getVectorNumElements()) {
1622     case  8: return MVT::v8i1;
1623     case 16: return MVT::v16i1;
1624   }
1625
1626   return VT.changeVectorElementTypeToInteger();
1627 }
1628
1629 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1630 /// the desired ByVal argument alignment.
1631 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1632   if (MaxAlign == 16)
1633     return;
1634   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1635     if (VTy->getBitWidth() == 128)
1636       MaxAlign = 16;
1637   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1638     unsigned EltAlign = 0;
1639     getMaxByValAlign(ATy->getElementType(), EltAlign);
1640     if (EltAlign > MaxAlign)
1641       MaxAlign = EltAlign;
1642   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1643     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1644       unsigned EltAlign = 0;
1645       getMaxByValAlign(STy->getElementType(i), EltAlign);
1646       if (EltAlign > MaxAlign)
1647         MaxAlign = EltAlign;
1648       if (MaxAlign == 16)
1649         break;
1650     }
1651   }
1652 }
1653
1654 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1655 /// function arguments in the caller parameter area. For X86, aggregates
1656 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1657 /// are at 4-byte boundaries.
1658 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1659   if (Subtarget->is64Bit()) {
1660     // Max of 8 and alignment of type.
1661     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1662     if (TyAlign > 8)
1663       return TyAlign;
1664     return 8;
1665   }
1666
1667   unsigned Align = 4;
1668   if (Subtarget->hasSSE1())
1669     getMaxByValAlign(Ty, Align);
1670   return Align;
1671 }
1672
1673 /// getOptimalMemOpType - Returns the target specific optimal type for load
1674 /// and store operations as a result of memset, memcpy, and memmove
1675 /// lowering. If DstAlign is zero that means it's safe to destination
1676 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1677 /// means there isn't a need to check it against alignment requirement,
1678 /// probably because the source does not need to be loaded. If 'IsMemset' is
1679 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1680 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1681 /// source is constant so it does not need to be loaded.
1682 /// It returns EVT::Other if the type should be determined using generic
1683 /// target-independent logic.
1684 EVT
1685 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1686                                        unsigned DstAlign, unsigned SrcAlign,
1687                                        bool IsMemset, bool ZeroMemset,
1688                                        bool MemcpyStrSrc,
1689                                        MachineFunction &MF) const {
1690   const Function *F = MF.getFunction();
1691   if ((!IsMemset || ZeroMemset) &&
1692       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1693                                        Attribute::NoImplicitFloat)) {
1694     if (Size >= 16 &&
1695         (Subtarget->isUnalignedMemAccessFast() ||
1696          ((DstAlign == 0 || DstAlign >= 16) &&
1697           (SrcAlign == 0 || SrcAlign >= 16)))) {
1698       if (Size >= 32) {
1699         if (Subtarget->hasInt256())
1700           return MVT::v8i32;
1701         if (Subtarget->hasFp256())
1702           return MVT::v8f32;
1703       }
1704       if (Subtarget->hasSSE2())
1705         return MVT::v4i32;
1706       if (Subtarget->hasSSE1())
1707         return MVT::v4f32;
1708     } else if (!MemcpyStrSrc && Size >= 8 &&
1709                !Subtarget->is64Bit() &&
1710                Subtarget->hasSSE2()) {
1711       // Do not use f64 to lower memcpy if source is string constant. It's
1712       // better to use i32 to avoid the loads.
1713       return MVT::f64;
1714     }
1715   }
1716   if (Subtarget->is64Bit() && Size >= 8)
1717     return MVT::i64;
1718   return MVT::i32;
1719 }
1720
1721 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1722   if (VT == MVT::f32)
1723     return X86ScalarSSEf32;
1724   else if (VT == MVT::f64)
1725     return X86ScalarSSEf64;
1726   return true;
1727 }
1728
1729 bool
1730 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1731                                                  unsigned,
1732                                                  bool *Fast) const {
1733   if (Fast)
1734     *Fast = Subtarget->isUnalignedMemAccessFast();
1735   return true;
1736 }
1737
1738 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1739 /// current function.  The returned value is a member of the
1740 /// MachineJumpTableInfo::JTEntryKind enum.
1741 unsigned X86TargetLowering::getJumpTableEncoding() const {
1742   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1743   // symbol.
1744   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1745       Subtarget->isPICStyleGOT())
1746     return MachineJumpTableInfo::EK_Custom32;
1747
1748   // Otherwise, use the normal jump table encoding heuristics.
1749   return TargetLowering::getJumpTableEncoding();
1750 }
1751
1752 const MCExpr *
1753 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1754                                              const MachineBasicBlock *MBB,
1755                                              unsigned uid,MCContext &Ctx) const{
1756   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1757          Subtarget->isPICStyleGOT());
1758   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1759   // entries.
1760   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1761                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1762 }
1763
1764 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1765 /// jumptable.
1766 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1767                                                     SelectionDAG &DAG) const {
1768   if (!Subtarget->is64Bit())
1769     // This doesn't have SDLoc associated with it, but is not really the
1770     // same as a Register.
1771     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1772   return Table;
1773 }
1774
1775 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1776 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1777 /// MCExpr.
1778 const MCExpr *X86TargetLowering::
1779 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1780                              MCContext &Ctx) const {
1781   // X86-64 uses RIP relative addressing based on the jump table label.
1782   if (Subtarget->isPICStyleRIPRel())
1783     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1784
1785   // Otherwise, the reference is relative to the PIC base.
1786   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1787 }
1788
1789 // FIXME: Why this routine is here? Move to RegInfo!
1790 std::pair<const TargetRegisterClass*, uint8_t>
1791 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1792   const TargetRegisterClass *RRC = nullptr;
1793   uint8_t Cost = 1;
1794   switch (VT.SimpleTy) {
1795   default:
1796     return TargetLowering::findRepresentativeClass(VT);
1797   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1798     RRC = Subtarget->is64Bit() ?
1799       (const TargetRegisterClass*)&X86::GR64RegClass :
1800       (const TargetRegisterClass*)&X86::GR32RegClass;
1801     break;
1802   case MVT::x86mmx:
1803     RRC = &X86::VR64RegClass;
1804     break;
1805   case MVT::f32: case MVT::f64:
1806   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1807   case MVT::v4f32: case MVT::v2f64:
1808   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1809   case MVT::v4f64:
1810     RRC = &X86::VR128RegClass;
1811     break;
1812   }
1813   return std::make_pair(RRC, Cost);
1814 }
1815
1816 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1817                                                unsigned &Offset) const {
1818   if (!Subtarget->isTargetLinux())
1819     return false;
1820
1821   if (Subtarget->is64Bit()) {
1822     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1823     Offset = 0x28;
1824     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1825       AddressSpace = 256;
1826     else
1827       AddressSpace = 257;
1828   } else {
1829     // %gs:0x14 on i386
1830     Offset = 0x14;
1831     AddressSpace = 256;
1832   }
1833   return true;
1834 }
1835
1836 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1837                                             unsigned DestAS) const {
1838   assert(SrcAS != DestAS && "Expected different address spaces!");
1839
1840   return SrcAS < 256 && DestAS < 256;
1841 }
1842
1843 //===----------------------------------------------------------------------===//
1844 //               Return Value Calling Convention Implementation
1845 //===----------------------------------------------------------------------===//
1846
1847 #include "X86GenCallingConv.inc"
1848
1849 bool
1850 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1851                                   MachineFunction &MF, bool isVarArg,
1852                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1853                         LLVMContext &Context) const {
1854   SmallVector<CCValAssign, 16> RVLocs;
1855   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1856                  RVLocs, Context);
1857   return CCInfo.CheckReturn(Outs, RetCC_X86);
1858 }
1859
1860 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1861   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1862   return ScratchRegs;
1863 }
1864
1865 SDValue
1866 X86TargetLowering::LowerReturn(SDValue Chain,
1867                                CallingConv::ID CallConv, bool isVarArg,
1868                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1869                                const SmallVectorImpl<SDValue> &OutVals,
1870                                SDLoc dl, SelectionDAG &DAG) const {
1871   MachineFunction &MF = DAG.getMachineFunction();
1872   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1873
1874   SmallVector<CCValAssign, 16> RVLocs;
1875   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1876                  RVLocs, *DAG.getContext());
1877   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1878
1879   SDValue Flag;
1880   SmallVector<SDValue, 6> RetOps;
1881   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1882   // Operand #1 = Bytes To Pop
1883   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1884                    MVT::i16));
1885
1886   // Copy the result values into the output registers.
1887   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1888     CCValAssign &VA = RVLocs[i];
1889     assert(VA.isRegLoc() && "Can only return in registers!");
1890     SDValue ValToCopy = OutVals[i];
1891     EVT ValVT = ValToCopy.getValueType();
1892
1893     // Promote values to the appropriate types
1894     if (VA.getLocInfo() == CCValAssign::SExt)
1895       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1896     else if (VA.getLocInfo() == CCValAssign::ZExt)
1897       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1898     else if (VA.getLocInfo() == CCValAssign::AExt)
1899       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1900     else if (VA.getLocInfo() == CCValAssign::BCvt)
1901       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1902
1903     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1904            "Unexpected FP-extend for return value.");  
1905
1906     // If this is x86-64, and we disabled SSE, we can't return FP values,
1907     // or SSE or MMX vectors.
1908     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1909          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1910           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1911       report_fatal_error("SSE register return with SSE disabled");
1912     }
1913     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1914     // llvm-gcc has never done it right and no one has noticed, so this
1915     // should be OK for now.
1916     if (ValVT == MVT::f64 &&
1917         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1918       report_fatal_error("SSE2 register return with SSE2 disabled");
1919
1920     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1921     // the RET instruction and handled by the FP Stackifier.
1922     if (VA.getLocReg() == X86::ST0 ||
1923         VA.getLocReg() == X86::ST1) {
1924       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1925       // change the value to the FP stack register class.
1926       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1927         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1928       RetOps.push_back(ValToCopy);
1929       // Don't emit a copytoreg.
1930       continue;
1931     }
1932
1933     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1934     // which is returned in RAX / RDX.
1935     if (Subtarget->is64Bit()) {
1936       if (ValVT == MVT::x86mmx) {
1937         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1938           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1939           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1940                                   ValToCopy);
1941           // If we don't have SSE2 available, convert to v4f32 so the generated
1942           // register is legal.
1943           if (!Subtarget->hasSSE2())
1944             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1945         }
1946       }
1947     }
1948
1949     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1950     Flag = Chain.getValue(1);
1951     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1952   }
1953
1954   // The x86-64 ABIs require that for returning structs by value we copy
1955   // the sret argument into %rax/%eax (depending on ABI) for the return.
1956   // Win32 requires us to put the sret argument to %eax as well.
1957   // We saved the argument into a virtual register in the entry block,
1958   // so now we copy the value out and into %rax/%eax.
1959   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1960       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1961     MachineFunction &MF = DAG.getMachineFunction();
1962     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1963     unsigned Reg = FuncInfo->getSRetReturnReg();
1964     assert(Reg &&
1965            "SRetReturnReg should have been set in LowerFormalArguments().");
1966     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1967
1968     unsigned RetValReg
1969         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1970           X86::RAX : X86::EAX;
1971     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1972     Flag = Chain.getValue(1);
1973
1974     // RAX/EAX now acts like a return value.
1975     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1976   }
1977
1978   RetOps[0] = Chain;  // Update chain.
1979
1980   // Add the flag if we have it.
1981   if (Flag.getNode())
1982     RetOps.push_back(Flag);
1983
1984   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1985 }
1986
1987 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1988   if (N->getNumValues() != 1)
1989     return false;
1990   if (!N->hasNUsesOfValue(1, 0))
1991     return false;
1992
1993   SDValue TCChain = Chain;
1994   SDNode *Copy = *N->use_begin();
1995   if (Copy->getOpcode() == ISD::CopyToReg) {
1996     // If the copy has a glue operand, we conservatively assume it isn't safe to
1997     // perform a tail call.
1998     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1999       return false;
2000     TCChain = Copy->getOperand(0);
2001   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2002     return false;
2003
2004   bool HasRet = false;
2005   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2006        UI != UE; ++UI) {
2007     if (UI->getOpcode() != X86ISD::RET_FLAG)
2008       return false;
2009     HasRet = true;
2010   }
2011
2012   if (!HasRet)
2013     return false;
2014
2015   Chain = TCChain;
2016   return true;
2017 }
2018
2019 MVT
2020 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2021                                             ISD::NodeType ExtendKind) const {
2022   MVT ReturnMVT;
2023   // TODO: Is this also valid on 32-bit?
2024   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2025     ReturnMVT = MVT::i8;
2026   else
2027     ReturnMVT = MVT::i32;
2028
2029   MVT MinVT = getRegisterType(ReturnMVT);
2030   return VT.bitsLT(MinVT) ? MinVT : VT;
2031 }
2032
2033 /// LowerCallResult - Lower the result values of a call into the
2034 /// appropriate copies out of appropriate physical registers.
2035 ///
2036 SDValue
2037 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2038                                    CallingConv::ID CallConv, bool isVarArg,
2039                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2040                                    SDLoc dl, SelectionDAG &DAG,
2041                                    SmallVectorImpl<SDValue> &InVals) const {
2042
2043   // Assign locations to each value returned by this call.
2044   SmallVector<CCValAssign, 16> RVLocs;
2045   bool Is64Bit = Subtarget->is64Bit();
2046   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2047                  DAG.getTarget(), RVLocs, *DAG.getContext());
2048   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2049
2050   // Copy all of the result registers out of their specified physreg.
2051   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2052     CCValAssign &VA = RVLocs[i];
2053     EVT CopyVT = VA.getValVT();
2054
2055     // If this is x86-64, and we disabled SSE, we can't return FP values
2056     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2057         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2058       report_fatal_error("SSE register return with SSE disabled");
2059     }
2060
2061     SDValue Val;
2062
2063     // If this is a call to a function that returns an fp value on the floating
2064     // point stack, we must guarantee the value is popped from the stack, so
2065     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2066     // if the return value is not used. We use the FpPOP_RETVAL instruction
2067     // instead.
2068     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2069       // If we prefer to use the value in xmm registers, copy it out as f80 and
2070       // use a truncate to move it from fp stack reg to xmm reg.
2071       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2072       SDValue Ops[] = { Chain, InFlag };
2073       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2074                                          MVT::Other, MVT::Glue, Ops), 1);
2075       Val = Chain.getValue(0);
2076
2077       // Round the f80 to the right size, which also moves it to the appropriate
2078       // xmm register.
2079       if (CopyVT != VA.getValVT())
2080         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2081                           // This truncation won't change the value.
2082                           DAG.getIntPtrConstant(1));
2083     } else {
2084       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2085                                  CopyVT, InFlag).getValue(1);
2086       Val = Chain.getValue(0);
2087     }
2088     InFlag = Chain.getValue(2);
2089     InVals.push_back(Val);
2090   }
2091
2092   return Chain;
2093 }
2094
2095 //===----------------------------------------------------------------------===//
2096 //                C & StdCall & Fast Calling Convention implementation
2097 //===----------------------------------------------------------------------===//
2098 //  StdCall calling convention seems to be standard for many Windows' API
2099 //  routines and around. It differs from C calling convention just a little:
2100 //  callee should clean up the stack, not caller. Symbols should be also
2101 //  decorated in some fancy way :) It doesn't support any vector arguments.
2102 //  For info on fast calling convention see Fast Calling Convention (tail call)
2103 //  implementation LowerX86_32FastCCCallTo.
2104
2105 /// CallIsStructReturn - Determines whether a call uses struct return
2106 /// semantics.
2107 enum StructReturnType {
2108   NotStructReturn,
2109   RegStructReturn,
2110   StackStructReturn
2111 };
2112 static StructReturnType
2113 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2114   if (Outs.empty())
2115     return NotStructReturn;
2116
2117   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2118   if (!Flags.isSRet())
2119     return NotStructReturn;
2120   if (Flags.isInReg())
2121     return RegStructReturn;
2122   return StackStructReturn;
2123 }
2124
2125 /// ArgsAreStructReturn - Determines whether a function uses struct
2126 /// return semantics.
2127 static StructReturnType
2128 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2129   if (Ins.empty())
2130     return NotStructReturn;
2131
2132   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2133   if (!Flags.isSRet())
2134     return NotStructReturn;
2135   if (Flags.isInReg())
2136     return RegStructReturn;
2137   return StackStructReturn;
2138 }
2139
2140 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2141 /// by "Src" to address "Dst" with size and alignment information specified by
2142 /// the specific parameter attribute. The copy will be passed as a byval
2143 /// function parameter.
2144 static SDValue
2145 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2146                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2147                           SDLoc dl) {
2148   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2149
2150   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2151                        /*isVolatile*/false, /*AlwaysInline=*/true,
2152                        MachinePointerInfo(), MachinePointerInfo());
2153 }
2154
2155 /// IsTailCallConvention - Return true if the calling convention is one that
2156 /// supports tail call optimization.
2157 static bool IsTailCallConvention(CallingConv::ID CC) {
2158   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2159           CC == CallingConv::HiPE);
2160 }
2161
2162 /// \brief Return true if the calling convention is a C calling convention.
2163 static bool IsCCallConvention(CallingConv::ID CC) {
2164   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2165           CC == CallingConv::X86_64_SysV);
2166 }
2167
2168 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2169   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2170     return false;
2171
2172   CallSite CS(CI);
2173   CallingConv::ID CalleeCC = CS.getCallingConv();
2174   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2175     return false;
2176
2177   return true;
2178 }
2179
2180 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2181 /// a tailcall target by changing its ABI.
2182 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2183                                    bool GuaranteedTailCallOpt) {
2184   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2185 }
2186
2187 SDValue
2188 X86TargetLowering::LowerMemArgument(SDValue Chain,
2189                                     CallingConv::ID CallConv,
2190                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2191                                     SDLoc dl, SelectionDAG &DAG,
2192                                     const CCValAssign &VA,
2193                                     MachineFrameInfo *MFI,
2194                                     unsigned i) const {
2195   // Create the nodes corresponding to a load from this parameter slot.
2196   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2197   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2198       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2199   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2200   EVT ValVT;
2201
2202   // If value is passed by pointer we have address passed instead of the value
2203   // itself.
2204   if (VA.getLocInfo() == CCValAssign::Indirect)
2205     ValVT = VA.getLocVT();
2206   else
2207     ValVT = VA.getValVT();
2208
2209   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2210   // changed with more analysis.
2211   // In case of tail call optimization mark all arguments mutable. Since they
2212   // could be overwritten by lowering of arguments in case of a tail call.
2213   if (Flags.isByVal()) {
2214     unsigned Bytes = Flags.getByValSize();
2215     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2216     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2217     return DAG.getFrameIndex(FI, getPointerTy());
2218   } else {
2219     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2220                                     VA.getLocMemOffset(), isImmutable);
2221     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2222     return DAG.getLoad(ValVT, dl, Chain, FIN,
2223                        MachinePointerInfo::getFixedStack(FI),
2224                        false, false, false, 0);
2225   }
2226 }
2227
2228 SDValue
2229 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2230                                         CallingConv::ID CallConv,
2231                                         bool isVarArg,
2232                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2233                                         SDLoc dl,
2234                                         SelectionDAG &DAG,
2235                                         SmallVectorImpl<SDValue> &InVals)
2236                                           const {
2237   MachineFunction &MF = DAG.getMachineFunction();
2238   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2239
2240   const Function* Fn = MF.getFunction();
2241   if (Fn->hasExternalLinkage() &&
2242       Subtarget->isTargetCygMing() &&
2243       Fn->getName() == "main")
2244     FuncInfo->setForceFramePointer(true);
2245
2246   MachineFrameInfo *MFI = MF.getFrameInfo();
2247   bool Is64Bit = Subtarget->is64Bit();
2248   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2249
2250   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2251          "Var args not supported with calling convention fastcc, ghc or hipe");
2252
2253   // Assign locations to all of the incoming arguments.
2254   SmallVector<CCValAssign, 16> ArgLocs;
2255   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2256                  ArgLocs, *DAG.getContext());
2257
2258   // Allocate shadow area for Win64
2259   if (IsWin64)
2260     CCInfo.AllocateStack(32, 8);
2261
2262   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2263
2264   unsigned LastVal = ~0U;
2265   SDValue ArgValue;
2266   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2267     CCValAssign &VA = ArgLocs[i];
2268     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2269     // places.
2270     assert(VA.getValNo() != LastVal &&
2271            "Don't support value assigned to multiple locs yet");
2272     (void)LastVal;
2273     LastVal = VA.getValNo();
2274
2275     if (VA.isRegLoc()) {
2276       EVT RegVT = VA.getLocVT();
2277       const TargetRegisterClass *RC;
2278       if (RegVT == MVT::i32)
2279         RC = &X86::GR32RegClass;
2280       else if (Is64Bit && RegVT == MVT::i64)
2281         RC = &X86::GR64RegClass;
2282       else if (RegVT == MVT::f32)
2283         RC = &X86::FR32RegClass;
2284       else if (RegVT == MVT::f64)
2285         RC = &X86::FR64RegClass;
2286       else if (RegVT.is512BitVector())
2287         RC = &X86::VR512RegClass;
2288       else if (RegVT.is256BitVector())
2289         RC = &X86::VR256RegClass;
2290       else if (RegVT.is128BitVector())
2291         RC = &X86::VR128RegClass;
2292       else if (RegVT == MVT::x86mmx)
2293         RC = &X86::VR64RegClass;
2294       else if (RegVT == MVT::i1)
2295         RC = &X86::VK1RegClass;
2296       else if (RegVT == MVT::v8i1)
2297         RC = &X86::VK8RegClass;
2298       else if (RegVT == MVT::v16i1)
2299         RC = &X86::VK16RegClass;
2300       else
2301         llvm_unreachable("Unknown argument type!");
2302
2303       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2304       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2305
2306       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2307       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2308       // right size.
2309       if (VA.getLocInfo() == CCValAssign::SExt)
2310         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2311                                DAG.getValueType(VA.getValVT()));
2312       else if (VA.getLocInfo() == CCValAssign::ZExt)
2313         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2314                                DAG.getValueType(VA.getValVT()));
2315       else if (VA.getLocInfo() == CCValAssign::BCvt)
2316         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2317
2318       if (VA.isExtInLoc()) {
2319         // Handle MMX values passed in XMM regs.
2320         if (RegVT.isVector())
2321           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2322         else
2323           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2324       }
2325     } else {
2326       assert(VA.isMemLoc());
2327       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2328     }
2329
2330     // If value is passed via pointer - do a load.
2331     if (VA.getLocInfo() == CCValAssign::Indirect)
2332       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2333                              MachinePointerInfo(), false, false, false, 0);
2334
2335     InVals.push_back(ArgValue);
2336   }
2337
2338   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2339     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2340       // The x86-64 ABIs require that for returning structs by value we copy
2341       // the sret argument into %rax/%eax (depending on ABI) for the return.
2342       // Win32 requires us to put the sret argument to %eax as well.
2343       // Save the argument into a virtual register so that we can access it
2344       // from the return points.
2345       if (Ins[i].Flags.isSRet()) {
2346         unsigned Reg = FuncInfo->getSRetReturnReg();
2347         if (!Reg) {
2348           MVT PtrTy = getPointerTy();
2349           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2350           FuncInfo->setSRetReturnReg(Reg);
2351         }
2352         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2353         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2354         break;
2355       }
2356     }
2357   }
2358
2359   unsigned StackSize = CCInfo.getNextStackOffset();
2360   // Align stack specially for tail calls.
2361   if (FuncIsMadeTailCallSafe(CallConv,
2362                              MF.getTarget().Options.GuaranteedTailCallOpt))
2363     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2364
2365   // If the function takes variable number of arguments, make a frame index for
2366   // the start of the first vararg value... for expansion of llvm.va_start.
2367   if (isVarArg) {
2368     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2369                     CallConv != CallingConv::X86_ThisCall)) {
2370       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2371     }
2372     if (Is64Bit) {
2373       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2374
2375       // FIXME: We should really autogenerate these arrays
2376       static const MCPhysReg GPR64ArgRegsWin64[] = {
2377         X86::RCX, X86::RDX, X86::R8,  X86::R9
2378       };
2379       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2380         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2381       };
2382       static const MCPhysReg XMMArgRegs64Bit[] = {
2383         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2384         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2385       };
2386       const MCPhysReg *GPR64ArgRegs;
2387       unsigned NumXMMRegs = 0;
2388
2389       if (IsWin64) {
2390         // The XMM registers which might contain var arg parameters are shadowed
2391         // in their paired GPR.  So we only need to save the GPR to their home
2392         // slots.
2393         TotalNumIntRegs = 4;
2394         GPR64ArgRegs = GPR64ArgRegsWin64;
2395       } else {
2396         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2397         GPR64ArgRegs = GPR64ArgRegs64Bit;
2398
2399         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2400                                                 TotalNumXMMRegs);
2401       }
2402       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2403                                                        TotalNumIntRegs);
2404
2405       bool NoImplicitFloatOps = Fn->getAttributes().
2406         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2407       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2408              "SSE register cannot be used when SSE is disabled!");
2409       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2410                NoImplicitFloatOps) &&
2411              "SSE register cannot be used when SSE is disabled!");
2412       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2413           !Subtarget->hasSSE1())
2414         // Kernel mode asks for SSE to be disabled, so don't push them
2415         // on the stack.
2416         TotalNumXMMRegs = 0;
2417
2418       if (IsWin64) {
2419         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2420         // Get to the caller-allocated home save location.  Add 8 to account
2421         // for the return address.
2422         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2423         FuncInfo->setRegSaveFrameIndex(
2424           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2425         // Fixup to set vararg frame on shadow area (4 x i64).
2426         if (NumIntRegs < 4)
2427           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2428       } else {
2429         // For X86-64, if there are vararg parameters that are passed via
2430         // registers, then we must store them to their spots on the stack so
2431         // they may be loaded by deferencing the result of va_next.
2432         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2433         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2434         FuncInfo->setRegSaveFrameIndex(
2435           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2436                                false));
2437       }
2438
2439       // Store the integer parameter registers.
2440       SmallVector<SDValue, 8> MemOps;
2441       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2442                                         getPointerTy());
2443       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2444       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2445         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2446                                   DAG.getIntPtrConstant(Offset));
2447         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2448                                      &X86::GR64RegClass);
2449         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2450         SDValue Store =
2451           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2452                        MachinePointerInfo::getFixedStack(
2453                          FuncInfo->getRegSaveFrameIndex(), Offset),
2454                        false, false, 0);
2455         MemOps.push_back(Store);
2456         Offset += 8;
2457       }
2458
2459       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2460         // Now store the XMM (fp + vector) parameter registers.
2461         SmallVector<SDValue, 11> SaveXMMOps;
2462         SaveXMMOps.push_back(Chain);
2463
2464         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2465         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2466         SaveXMMOps.push_back(ALVal);
2467
2468         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2469                                FuncInfo->getRegSaveFrameIndex()));
2470         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2471                                FuncInfo->getVarArgsFPOffset()));
2472
2473         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2474           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2475                                        &X86::VR128RegClass);
2476           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2477           SaveXMMOps.push_back(Val);
2478         }
2479         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2480                                      MVT::Other, SaveXMMOps));
2481       }
2482
2483       if (!MemOps.empty())
2484         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2485     }
2486   }
2487
2488   // Some CCs need callee pop.
2489   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2490                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2491     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2492   } else {
2493     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2494     // If this is an sret function, the return should pop the hidden pointer.
2495     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2496         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2497         argsAreStructReturn(Ins) == StackStructReturn)
2498       FuncInfo->setBytesToPopOnReturn(4);
2499   }
2500
2501   if (!Is64Bit) {
2502     // RegSaveFrameIndex is X86-64 only.
2503     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2504     if (CallConv == CallingConv::X86_FastCall ||
2505         CallConv == CallingConv::X86_ThisCall)
2506       // fastcc functions can't have varargs.
2507       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2508   }
2509
2510   FuncInfo->setArgumentStackSize(StackSize);
2511
2512   return Chain;
2513 }
2514
2515 SDValue
2516 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2517                                     SDValue StackPtr, SDValue Arg,
2518                                     SDLoc dl, SelectionDAG &DAG,
2519                                     const CCValAssign &VA,
2520                                     ISD::ArgFlagsTy Flags) const {
2521   unsigned LocMemOffset = VA.getLocMemOffset();
2522   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2523   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2524   if (Flags.isByVal())
2525     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2526
2527   return DAG.getStore(Chain, dl, Arg, PtrOff,
2528                       MachinePointerInfo::getStack(LocMemOffset),
2529                       false, false, 0);
2530 }
2531
2532 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2533 /// optimization is performed and it is required.
2534 SDValue
2535 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2536                                            SDValue &OutRetAddr, SDValue Chain,
2537                                            bool IsTailCall, bool Is64Bit,
2538                                            int FPDiff, SDLoc dl) const {
2539   // Adjust the Return address stack slot.
2540   EVT VT = getPointerTy();
2541   OutRetAddr = getReturnAddressFrameIndex(DAG);
2542
2543   // Load the "old" Return address.
2544   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2545                            false, false, false, 0);
2546   return SDValue(OutRetAddr.getNode(), 1);
2547 }
2548
2549 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2550 /// optimization is performed and it is required (FPDiff!=0).
2551 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2552                                         SDValue Chain, SDValue RetAddrFrIdx,
2553                                         EVT PtrVT, unsigned SlotSize,
2554                                         int FPDiff, SDLoc dl) {
2555   // Store the return address to the appropriate stack slot.
2556   if (!FPDiff) return Chain;
2557   // Calculate the new stack slot for the return address.
2558   int NewReturnAddrFI =
2559     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2560                                          false);
2561   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2562   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2563                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2564                        false, false, 0);
2565   return Chain;
2566 }
2567
2568 SDValue
2569 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2570                              SmallVectorImpl<SDValue> &InVals) const {
2571   SelectionDAG &DAG                     = CLI.DAG;
2572   SDLoc &dl                             = CLI.DL;
2573   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2574   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2575   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2576   SDValue Chain                         = CLI.Chain;
2577   SDValue Callee                        = CLI.Callee;
2578   CallingConv::ID CallConv              = CLI.CallConv;
2579   bool &isTailCall                      = CLI.IsTailCall;
2580   bool isVarArg                         = CLI.IsVarArg;
2581
2582   MachineFunction &MF = DAG.getMachineFunction();
2583   bool Is64Bit        = Subtarget->is64Bit();
2584   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2585   StructReturnType SR = callIsStructReturn(Outs);
2586   bool IsSibcall      = false;
2587
2588   if (MF.getTarget().Options.DisableTailCalls)
2589     isTailCall = false;
2590
2591   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2592   if (IsMustTail) {
2593     // Force this to be a tail call.  The verifier rules are enough to ensure
2594     // that we can lower this successfully without moving the return address
2595     // around.
2596     isTailCall = true;
2597   } else if (isTailCall) {
2598     // Check if it's really possible to do a tail call.
2599     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2600                     isVarArg, SR != NotStructReturn,
2601                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2602                     Outs, OutVals, Ins, DAG);
2603
2604     // Sibcalls are automatically detected tailcalls which do not require
2605     // ABI changes.
2606     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2607       IsSibcall = true;
2608
2609     if (isTailCall)
2610       ++NumTailCalls;
2611   }
2612
2613   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2614          "Var args not supported with calling convention fastcc, ghc or hipe");
2615
2616   // Analyze operands of the call, assigning locations to each operand.
2617   SmallVector<CCValAssign, 16> ArgLocs;
2618   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2619                  ArgLocs, *DAG.getContext());
2620
2621   // Allocate shadow area for Win64
2622   if (IsWin64)
2623     CCInfo.AllocateStack(32, 8);
2624
2625   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2626
2627   // Get a count of how many bytes are to be pushed on the stack.
2628   unsigned NumBytes = CCInfo.getNextStackOffset();
2629   if (IsSibcall)
2630     // This is a sibcall. The memory operands are available in caller's
2631     // own caller's stack.
2632     NumBytes = 0;
2633   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2634            IsTailCallConvention(CallConv))
2635     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2636
2637   int FPDiff = 0;
2638   if (isTailCall && !IsSibcall && !IsMustTail) {
2639     // Lower arguments at fp - stackoffset + fpdiff.
2640     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2641     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2642
2643     FPDiff = NumBytesCallerPushed - NumBytes;
2644
2645     // Set the delta of movement of the returnaddr stackslot.
2646     // But only set if delta is greater than previous delta.
2647     if (FPDiff < X86Info->getTCReturnAddrDelta())
2648       X86Info->setTCReturnAddrDelta(FPDiff);
2649   }
2650
2651   unsigned NumBytesToPush = NumBytes;
2652   unsigned NumBytesToPop = NumBytes;
2653
2654   // If we have an inalloca argument, all stack space has already been allocated
2655   // for us and be right at the top of the stack.  We don't support multiple
2656   // arguments passed in memory when using inalloca.
2657   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2658     NumBytesToPush = 0;
2659     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2660            "an inalloca argument must be the only memory argument");
2661   }
2662
2663   if (!IsSibcall)
2664     Chain = DAG.getCALLSEQ_START(
2665         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2666
2667   SDValue RetAddrFrIdx;
2668   // Load return address for tail calls.
2669   if (isTailCall && FPDiff)
2670     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2671                                     Is64Bit, FPDiff, dl);
2672
2673   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2674   SmallVector<SDValue, 8> MemOpChains;
2675   SDValue StackPtr;
2676
2677   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2678   // of tail call optimization arguments are handle later.
2679   const X86RegisterInfo *RegInfo =
2680     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2681   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2682     // Skip inalloca arguments, they have already been written.
2683     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2684     if (Flags.isInAlloca())
2685       continue;
2686
2687     CCValAssign &VA = ArgLocs[i];
2688     EVT RegVT = VA.getLocVT();
2689     SDValue Arg = OutVals[i];
2690     bool isByVal = Flags.isByVal();
2691
2692     // Promote the value if needed.
2693     switch (VA.getLocInfo()) {
2694     default: llvm_unreachable("Unknown loc info!");
2695     case CCValAssign::Full: break;
2696     case CCValAssign::SExt:
2697       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2698       break;
2699     case CCValAssign::ZExt:
2700       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2701       break;
2702     case CCValAssign::AExt:
2703       if (RegVT.is128BitVector()) {
2704         // Special case: passing MMX values in XMM registers.
2705         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2706         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2707         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2708       } else
2709         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2710       break;
2711     case CCValAssign::BCvt:
2712       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2713       break;
2714     case CCValAssign::Indirect: {
2715       // Store the argument.
2716       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2717       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2718       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2719                            MachinePointerInfo::getFixedStack(FI),
2720                            false, false, 0);
2721       Arg = SpillSlot;
2722       break;
2723     }
2724     }
2725
2726     if (VA.isRegLoc()) {
2727       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2728       if (isVarArg && IsWin64) {
2729         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2730         // shadow reg if callee is a varargs function.
2731         unsigned ShadowReg = 0;
2732         switch (VA.getLocReg()) {
2733         case X86::XMM0: ShadowReg = X86::RCX; break;
2734         case X86::XMM1: ShadowReg = X86::RDX; break;
2735         case X86::XMM2: ShadowReg = X86::R8; break;
2736         case X86::XMM3: ShadowReg = X86::R9; break;
2737         }
2738         if (ShadowReg)
2739           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2740       }
2741     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2742       assert(VA.isMemLoc());
2743       if (!StackPtr.getNode())
2744         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2745                                       getPointerTy());
2746       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2747                                              dl, DAG, VA, Flags));
2748     }
2749   }
2750
2751   if (!MemOpChains.empty())
2752     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2753
2754   if (Subtarget->isPICStyleGOT()) {
2755     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2756     // GOT pointer.
2757     if (!isTailCall) {
2758       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2759                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2760     } else {
2761       // If we are tail calling and generating PIC/GOT style code load the
2762       // address of the callee into ECX. The value in ecx is used as target of
2763       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2764       // for tail calls on PIC/GOT architectures. Normally we would just put the
2765       // address of GOT into ebx and then call target@PLT. But for tail calls
2766       // ebx would be restored (since ebx is callee saved) before jumping to the
2767       // target@PLT.
2768
2769       // Note: The actual moving to ECX is done further down.
2770       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2771       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2772           !G->getGlobal()->hasProtectedVisibility())
2773         Callee = LowerGlobalAddress(Callee, DAG);
2774       else if (isa<ExternalSymbolSDNode>(Callee))
2775         Callee = LowerExternalSymbol(Callee, DAG);
2776     }
2777   }
2778
2779   if (Is64Bit && isVarArg && !IsWin64) {
2780     // From AMD64 ABI document:
2781     // For calls that may call functions that use varargs or stdargs
2782     // (prototype-less calls or calls to functions containing ellipsis (...) in
2783     // the declaration) %al is used as hidden argument to specify the number
2784     // of SSE registers used. The contents of %al do not need to match exactly
2785     // the number of registers, but must be an ubound on the number of SSE
2786     // registers used and is in the range 0 - 8 inclusive.
2787
2788     // Count the number of XMM registers allocated.
2789     static const MCPhysReg XMMArgRegs[] = {
2790       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2791       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2792     };
2793     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2794     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2795            && "SSE registers cannot be used when SSE is disabled");
2796
2797     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2798                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2799   }
2800
2801   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2802   // don't need this because the eligibility check rejects calls that require
2803   // shuffling arguments passed in memory.
2804   if (!IsSibcall && isTailCall) {
2805     // Force all the incoming stack arguments to be loaded from the stack
2806     // before any new outgoing arguments are stored to the stack, because the
2807     // outgoing stack slots may alias the incoming argument stack slots, and
2808     // the alias isn't otherwise explicit. This is slightly more conservative
2809     // than necessary, because it means that each store effectively depends
2810     // on every argument instead of just those arguments it would clobber.
2811     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2812
2813     SmallVector<SDValue, 8> MemOpChains2;
2814     SDValue FIN;
2815     int FI = 0;
2816     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2817       CCValAssign &VA = ArgLocs[i];
2818       if (VA.isRegLoc())
2819         continue;
2820       assert(VA.isMemLoc());
2821       SDValue Arg = OutVals[i];
2822       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2823       // Skip inalloca arguments.  They don't require any work.
2824       if (Flags.isInAlloca())
2825         continue;
2826       // Create frame index.
2827       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2828       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2829       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2830       FIN = DAG.getFrameIndex(FI, getPointerTy());
2831
2832       if (Flags.isByVal()) {
2833         // Copy relative to framepointer.
2834         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2835         if (!StackPtr.getNode())
2836           StackPtr = DAG.getCopyFromReg(Chain, dl,
2837                                         RegInfo->getStackRegister(),
2838                                         getPointerTy());
2839         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2840
2841         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2842                                                          ArgChain,
2843                                                          Flags, DAG, dl));
2844       } else {
2845         // Store relative to framepointer.
2846         MemOpChains2.push_back(
2847           DAG.getStore(ArgChain, dl, Arg, FIN,
2848                        MachinePointerInfo::getFixedStack(FI),
2849                        false, false, 0));
2850       }
2851     }
2852
2853     if (!MemOpChains2.empty())
2854       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2855
2856     // Store the return address to the appropriate stack slot.
2857     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2858                                      getPointerTy(), RegInfo->getSlotSize(),
2859                                      FPDiff, dl);
2860   }
2861
2862   // Build a sequence of copy-to-reg nodes chained together with token chain
2863   // and flag operands which copy the outgoing args into registers.
2864   SDValue InFlag;
2865   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2866     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2867                              RegsToPass[i].second, InFlag);
2868     InFlag = Chain.getValue(1);
2869   }
2870
2871   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2872     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2873     // In the 64-bit large code model, we have to make all calls
2874     // through a register, since the call instruction's 32-bit
2875     // pc-relative offset may not be large enough to hold the whole
2876     // address.
2877   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2878     // If the callee is a GlobalAddress node (quite common, every direct call
2879     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2880     // it.
2881
2882     // We should use extra load for direct calls to dllimported functions in
2883     // non-JIT mode.
2884     const GlobalValue *GV = G->getGlobal();
2885     if (!GV->hasDLLImportStorageClass()) {
2886       unsigned char OpFlags = 0;
2887       bool ExtraLoad = false;
2888       unsigned WrapperKind = ISD::DELETED_NODE;
2889
2890       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2891       // external symbols most go through the PLT in PIC mode.  If the symbol
2892       // has hidden or protected visibility, or if it is static or local, then
2893       // we don't need to use the PLT - we can directly call it.
2894       if (Subtarget->isTargetELF() &&
2895           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2896           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2897         OpFlags = X86II::MO_PLT;
2898       } else if (Subtarget->isPICStyleStubAny() &&
2899                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2900                  (!Subtarget->getTargetTriple().isMacOSX() ||
2901                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2902         // PC-relative references to external symbols should go through $stub,
2903         // unless we're building with the leopard linker or later, which
2904         // automatically synthesizes these stubs.
2905         OpFlags = X86II::MO_DARWIN_STUB;
2906       } else if (Subtarget->isPICStyleRIPRel() &&
2907                  isa<Function>(GV) &&
2908                  cast<Function>(GV)->getAttributes().
2909                    hasAttribute(AttributeSet::FunctionIndex,
2910                                 Attribute::NonLazyBind)) {
2911         // If the function is marked as non-lazy, generate an indirect call
2912         // which loads from the GOT directly. This avoids runtime overhead
2913         // at the cost of eager binding (and one extra byte of encoding).
2914         OpFlags = X86II::MO_GOTPCREL;
2915         WrapperKind = X86ISD::WrapperRIP;
2916         ExtraLoad = true;
2917       }
2918
2919       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2920                                           G->getOffset(), OpFlags);
2921
2922       // Add a wrapper if needed.
2923       if (WrapperKind != ISD::DELETED_NODE)
2924         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2925       // Add extra indirection if needed.
2926       if (ExtraLoad)
2927         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2928                              MachinePointerInfo::getGOT(),
2929                              false, false, false, 0);
2930     }
2931   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2932     unsigned char OpFlags = 0;
2933
2934     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2935     // external symbols should go through the PLT.
2936     if (Subtarget->isTargetELF() &&
2937         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2938       OpFlags = X86II::MO_PLT;
2939     } else if (Subtarget->isPICStyleStubAny() &&
2940                (!Subtarget->getTargetTriple().isMacOSX() ||
2941                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2942       // PC-relative references to external symbols should go through $stub,
2943       // unless we're building with the leopard linker or later, which
2944       // automatically synthesizes these stubs.
2945       OpFlags = X86II::MO_DARWIN_STUB;
2946     }
2947
2948     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2949                                          OpFlags);
2950   }
2951
2952   // Returns a chain & a flag for retval copy to use.
2953   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2954   SmallVector<SDValue, 8> Ops;
2955
2956   if (!IsSibcall && isTailCall) {
2957     Chain = DAG.getCALLSEQ_END(Chain,
2958                                DAG.getIntPtrConstant(NumBytesToPop, true),
2959                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2960     InFlag = Chain.getValue(1);
2961   }
2962
2963   Ops.push_back(Chain);
2964   Ops.push_back(Callee);
2965
2966   if (isTailCall)
2967     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2968
2969   // Add argument registers to the end of the list so that they are known live
2970   // into the call.
2971   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2972     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2973                                   RegsToPass[i].second.getValueType()));
2974
2975   // Add a register mask operand representing the call-preserved registers.
2976   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2977   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2978   assert(Mask && "Missing call preserved mask for calling convention");
2979   Ops.push_back(DAG.getRegisterMask(Mask));
2980
2981   if (InFlag.getNode())
2982     Ops.push_back(InFlag);
2983
2984   if (isTailCall) {
2985     // We used to do:
2986     //// If this is the first return lowered for this function, add the regs
2987     //// to the liveout set for the function.
2988     // This isn't right, although it's probably harmless on x86; liveouts
2989     // should be computed from returns not tail calls.  Consider a void
2990     // function making a tail call to a function returning int.
2991     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2992   }
2993
2994   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2995   InFlag = Chain.getValue(1);
2996
2997   // Create the CALLSEQ_END node.
2998   unsigned NumBytesForCalleeToPop;
2999   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3000                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3001     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3002   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3003            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3004            SR == StackStructReturn)
3005     // If this is a call to a struct-return function, the callee
3006     // pops the hidden struct pointer, so we have to push it back.
3007     // This is common for Darwin/X86, Linux & Mingw32 targets.
3008     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3009     NumBytesForCalleeToPop = 4;
3010   else
3011     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3012
3013   // Returns a flag for retval copy to use.
3014   if (!IsSibcall) {
3015     Chain = DAG.getCALLSEQ_END(Chain,
3016                                DAG.getIntPtrConstant(NumBytesToPop, true),
3017                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3018                                                      true),
3019                                InFlag, dl);
3020     InFlag = Chain.getValue(1);
3021   }
3022
3023   // Handle result values, copying them out of physregs into vregs that we
3024   // return.
3025   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3026                          Ins, dl, DAG, InVals);
3027 }
3028
3029 //===----------------------------------------------------------------------===//
3030 //                Fast Calling Convention (tail call) implementation
3031 //===----------------------------------------------------------------------===//
3032
3033 //  Like std call, callee cleans arguments, convention except that ECX is
3034 //  reserved for storing the tail called function address. Only 2 registers are
3035 //  free for argument passing (inreg). Tail call optimization is performed
3036 //  provided:
3037 //                * tailcallopt is enabled
3038 //                * caller/callee are fastcc
3039 //  On X86_64 architecture with GOT-style position independent code only local
3040 //  (within module) calls are supported at the moment.
3041 //  To keep the stack aligned according to platform abi the function
3042 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3043 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3044 //  If a tail called function callee has more arguments than the caller the
3045 //  caller needs to make sure that there is room to move the RETADDR to. This is
3046 //  achieved by reserving an area the size of the argument delta right after the
3047 //  original REtADDR, but before the saved framepointer or the spilled registers
3048 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3049 //  stack layout:
3050 //    arg1
3051 //    arg2
3052 //    RETADDR
3053 //    [ new RETADDR
3054 //      move area ]
3055 //    (possible EBP)
3056 //    ESI
3057 //    EDI
3058 //    local1 ..
3059
3060 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3061 /// for a 16 byte align requirement.
3062 unsigned
3063 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3064                                                SelectionDAG& DAG) const {
3065   MachineFunction &MF = DAG.getMachineFunction();
3066   const TargetMachine &TM = MF.getTarget();
3067   const X86RegisterInfo *RegInfo =
3068     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3069   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3070   unsigned StackAlignment = TFI.getStackAlignment();
3071   uint64_t AlignMask = StackAlignment - 1;
3072   int64_t Offset = StackSize;
3073   unsigned SlotSize = RegInfo->getSlotSize();
3074   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3075     // Number smaller than 12 so just add the difference.
3076     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3077   } else {
3078     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3079     Offset = ((~AlignMask) & Offset) + StackAlignment +
3080       (StackAlignment-SlotSize);
3081   }
3082   return Offset;
3083 }
3084
3085 /// MatchingStackOffset - Return true if the given stack call argument is
3086 /// already available in the same position (relatively) of the caller's
3087 /// incoming argument stack.
3088 static
3089 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3090                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3091                          const X86InstrInfo *TII) {
3092   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3093   int FI = INT_MAX;
3094   if (Arg.getOpcode() == ISD::CopyFromReg) {
3095     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3096     if (!TargetRegisterInfo::isVirtualRegister(VR))
3097       return false;
3098     MachineInstr *Def = MRI->getVRegDef(VR);
3099     if (!Def)
3100       return false;
3101     if (!Flags.isByVal()) {
3102       if (!TII->isLoadFromStackSlot(Def, FI))
3103         return false;
3104     } else {
3105       unsigned Opcode = Def->getOpcode();
3106       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3107           Def->getOperand(1).isFI()) {
3108         FI = Def->getOperand(1).getIndex();
3109         Bytes = Flags.getByValSize();
3110       } else
3111         return false;
3112     }
3113   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3114     if (Flags.isByVal())
3115       // ByVal argument is passed in as a pointer but it's now being
3116       // dereferenced. e.g.
3117       // define @foo(%struct.X* %A) {
3118       //   tail call @bar(%struct.X* byval %A)
3119       // }
3120       return false;
3121     SDValue Ptr = Ld->getBasePtr();
3122     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3123     if (!FINode)
3124       return false;
3125     FI = FINode->getIndex();
3126   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3127     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3128     FI = FINode->getIndex();
3129     Bytes = Flags.getByValSize();
3130   } else
3131     return false;
3132
3133   assert(FI != INT_MAX);
3134   if (!MFI->isFixedObjectIndex(FI))
3135     return false;
3136   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3137 }
3138
3139 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3140 /// for tail call optimization. Targets which want to do tail call
3141 /// optimization should implement this function.
3142 bool
3143 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3144                                                      CallingConv::ID CalleeCC,
3145                                                      bool isVarArg,
3146                                                      bool isCalleeStructRet,
3147                                                      bool isCallerStructRet,
3148                                                      Type *RetTy,
3149                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3150                                     const SmallVectorImpl<SDValue> &OutVals,
3151                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3152                                                      SelectionDAG &DAG) const {
3153   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3154     return false;
3155
3156   // If -tailcallopt is specified, make fastcc functions tail-callable.
3157   const MachineFunction &MF = DAG.getMachineFunction();
3158   const Function *CallerF = MF.getFunction();
3159
3160   // If the function return type is x86_fp80 and the callee return type is not,
3161   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3162   // perform a tailcall optimization here.
3163   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3164     return false;
3165
3166   CallingConv::ID CallerCC = CallerF->getCallingConv();
3167   bool CCMatch = CallerCC == CalleeCC;
3168   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3169   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3170
3171   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3172     if (IsTailCallConvention(CalleeCC) && CCMatch)
3173       return true;
3174     return false;
3175   }
3176
3177   // Look for obvious safe cases to perform tail call optimization that do not
3178   // require ABI changes. This is what gcc calls sibcall.
3179
3180   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3181   // emit a special epilogue.
3182   const X86RegisterInfo *RegInfo =
3183     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3184   if (RegInfo->needsStackRealignment(MF))
3185     return false;
3186
3187   // Also avoid sibcall optimization if either caller or callee uses struct
3188   // return semantics.
3189   if (isCalleeStructRet || isCallerStructRet)
3190     return false;
3191
3192   // An stdcall/thiscall caller is expected to clean up its arguments; the
3193   // callee isn't going to do that.
3194   // FIXME: this is more restrictive than needed. We could produce a tailcall
3195   // when the stack adjustment matches. For example, with a thiscall that takes
3196   // only one argument.
3197   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3198                    CallerCC == CallingConv::X86_ThisCall))
3199     return false;
3200
3201   // Do not sibcall optimize vararg calls unless all arguments are passed via
3202   // registers.
3203   if (isVarArg && !Outs.empty()) {
3204
3205     // Optimizing for varargs on Win64 is unlikely to be safe without
3206     // additional testing.
3207     if (IsCalleeWin64 || IsCallerWin64)
3208       return false;
3209
3210     SmallVector<CCValAssign, 16> ArgLocs;
3211     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3212                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3213
3214     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3215     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3216       if (!ArgLocs[i].isRegLoc())
3217         return false;
3218   }
3219
3220   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3221   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3222   // this into a sibcall.
3223   bool Unused = false;
3224   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3225     if (!Ins[i].Used) {
3226       Unused = true;
3227       break;
3228     }
3229   }
3230   if (Unused) {
3231     SmallVector<CCValAssign, 16> RVLocs;
3232     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3233                    DAG.getTarget(), RVLocs, *DAG.getContext());
3234     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3235     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3236       CCValAssign &VA = RVLocs[i];
3237       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3238         return false;
3239     }
3240   }
3241
3242   // If the calling conventions do not match, then we'd better make sure the
3243   // results are returned in the same way as what the caller expects.
3244   if (!CCMatch) {
3245     SmallVector<CCValAssign, 16> RVLocs1;
3246     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3247                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3248     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3249
3250     SmallVector<CCValAssign, 16> RVLocs2;
3251     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3252                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3253     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3254
3255     if (RVLocs1.size() != RVLocs2.size())
3256       return false;
3257     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3258       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3259         return false;
3260       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3261         return false;
3262       if (RVLocs1[i].isRegLoc()) {
3263         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3264           return false;
3265       } else {
3266         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3267           return false;
3268       }
3269     }
3270   }
3271
3272   // If the callee takes no arguments then go on to check the results of the
3273   // call.
3274   if (!Outs.empty()) {
3275     // Check if stack adjustment is needed. For now, do not do this if any
3276     // argument is passed on the stack.
3277     SmallVector<CCValAssign, 16> ArgLocs;
3278     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3279                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3280
3281     // Allocate shadow area for Win64
3282     if (IsCalleeWin64)
3283       CCInfo.AllocateStack(32, 8);
3284
3285     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3286     if (CCInfo.getNextStackOffset()) {
3287       MachineFunction &MF = DAG.getMachineFunction();
3288       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3289         return false;
3290
3291       // Check if the arguments are already laid out in the right way as
3292       // the caller's fixed stack objects.
3293       MachineFrameInfo *MFI = MF.getFrameInfo();
3294       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3295       const X86InstrInfo *TII =
3296           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3297       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3298         CCValAssign &VA = ArgLocs[i];
3299         SDValue Arg = OutVals[i];
3300         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3301         if (VA.getLocInfo() == CCValAssign::Indirect)
3302           return false;
3303         if (!VA.isRegLoc()) {
3304           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3305                                    MFI, MRI, TII))
3306             return false;
3307         }
3308       }
3309     }
3310
3311     // If the tailcall address may be in a register, then make sure it's
3312     // possible to register allocate for it. In 32-bit, the call address can
3313     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3314     // callee-saved registers are restored. These happen to be the same
3315     // registers used to pass 'inreg' arguments so watch out for those.
3316     if (!Subtarget->is64Bit() &&
3317         ((!isa<GlobalAddressSDNode>(Callee) &&
3318           !isa<ExternalSymbolSDNode>(Callee)) ||
3319          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3320       unsigned NumInRegs = 0;
3321       // In PIC we need an extra register to formulate the address computation
3322       // for the callee.
3323       unsigned MaxInRegs =
3324         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3325
3326       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3327         CCValAssign &VA = ArgLocs[i];
3328         if (!VA.isRegLoc())
3329           continue;
3330         unsigned Reg = VA.getLocReg();
3331         switch (Reg) {
3332         default: break;
3333         case X86::EAX: case X86::EDX: case X86::ECX:
3334           if (++NumInRegs == MaxInRegs)
3335             return false;
3336           break;
3337         }
3338       }
3339     }
3340   }
3341
3342   return true;
3343 }
3344
3345 FastISel *
3346 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3347                                   const TargetLibraryInfo *libInfo) const {
3348   return X86::createFastISel(funcInfo, libInfo);
3349 }
3350
3351 //===----------------------------------------------------------------------===//
3352 //                           Other Lowering Hooks
3353 //===----------------------------------------------------------------------===//
3354
3355 static bool MayFoldLoad(SDValue Op) {
3356   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3357 }
3358
3359 static bool MayFoldIntoStore(SDValue Op) {
3360   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3361 }
3362
3363 static bool isTargetShuffle(unsigned Opcode) {
3364   switch(Opcode) {
3365   default: return false;
3366   case X86ISD::PSHUFD:
3367   case X86ISD::PSHUFHW:
3368   case X86ISD::PSHUFLW:
3369   case X86ISD::SHUFP:
3370   case X86ISD::PALIGNR:
3371   case X86ISD::MOVLHPS:
3372   case X86ISD::MOVLHPD:
3373   case X86ISD::MOVHLPS:
3374   case X86ISD::MOVLPS:
3375   case X86ISD::MOVLPD:
3376   case X86ISD::MOVSHDUP:
3377   case X86ISD::MOVSLDUP:
3378   case X86ISD::MOVDDUP:
3379   case X86ISD::MOVSS:
3380   case X86ISD::MOVSD:
3381   case X86ISD::UNPCKL:
3382   case X86ISD::UNPCKH:
3383   case X86ISD::VPERMILP:
3384   case X86ISD::VPERM2X128:
3385   case X86ISD::VPERMI:
3386     return true;
3387   }
3388 }
3389
3390 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3391                                     SDValue V1, SelectionDAG &DAG) {
3392   switch(Opc) {
3393   default: llvm_unreachable("Unknown x86 shuffle node");
3394   case X86ISD::MOVSHDUP:
3395   case X86ISD::MOVSLDUP:
3396   case X86ISD::MOVDDUP:
3397     return DAG.getNode(Opc, dl, VT, V1);
3398   }
3399 }
3400
3401 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3402                                     SDValue V1, unsigned TargetMask,
3403                                     SelectionDAG &DAG) {
3404   switch(Opc) {
3405   default: llvm_unreachable("Unknown x86 shuffle node");
3406   case X86ISD::PSHUFD:
3407   case X86ISD::PSHUFHW:
3408   case X86ISD::PSHUFLW:
3409   case X86ISD::VPERMILP:
3410   case X86ISD::VPERMI:
3411     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3412   }
3413 }
3414
3415 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3416                                     SDValue V1, SDValue V2, unsigned TargetMask,
3417                                     SelectionDAG &DAG) {
3418   switch(Opc) {
3419   default: llvm_unreachable("Unknown x86 shuffle node");
3420   case X86ISD::PALIGNR:
3421   case X86ISD::SHUFP:
3422   case X86ISD::VPERM2X128:
3423     return DAG.getNode(Opc, dl, VT, V1, V2,
3424                        DAG.getConstant(TargetMask, MVT::i8));
3425   }
3426 }
3427
3428 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3429                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3430   switch(Opc) {
3431   default: llvm_unreachable("Unknown x86 shuffle node");
3432   case X86ISD::MOVLHPS:
3433   case X86ISD::MOVLHPD:
3434   case X86ISD::MOVHLPS:
3435   case X86ISD::MOVLPS:
3436   case X86ISD::MOVLPD:
3437   case X86ISD::MOVSS:
3438   case X86ISD::MOVSD:
3439   case X86ISD::UNPCKL:
3440   case X86ISD::UNPCKH:
3441     return DAG.getNode(Opc, dl, VT, V1, V2);
3442   }
3443 }
3444
3445 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3446   MachineFunction &MF = DAG.getMachineFunction();
3447   const X86RegisterInfo *RegInfo =
3448     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3449   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3450   int ReturnAddrIndex = FuncInfo->getRAIndex();
3451
3452   if (ReturnAddrIndex == 0) {
3453     // Set up a frame object for the return address.
3454     unsigned SlotSize = RegInfo->getSlotSize();
3455     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3456                                                            -(int64_t)SlotSize,
3457                                                            false);
3458     FuncInfo->setRAIndex(ReturnAddrIndex);
3459   }
3460
3461   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3462 }
3463
3464 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3465                                        bool hasSymbolicDisplacement) {
3466   // Offset should fit into 32 bit immediate field.
3467   if (!isInt<32>(Offset))
3468     return false;
3469
3470   // If we don't have a symbolic displacement - we don't have any extra
3471   // restrictions.
3472   if (!hasSymbolicDisplacement)
3473     return true;
3474
3475   // FIXME: Some tweaks might be needed for medium code model.
3476   if (M != CodeModel::Small && M != CodeModel::Kernel)
3477     return false;
3478
3479   // For small code model we assume that latest object is 16MB before end of 31
3480   // bits boundary. We may also accept pretty large negative constants knowing
3481   // that all objects are in the positive half of address space.
3482   if (M == CodeModel::Small && Offset < 16*1024*1024)
3483     return true;
3484
3485   // For kernel code model we know that all object resist in the negative half
3486   // of 32bits address space. We may not accept negative offsets, since they may
3487   // be just off and we may accept pretty large positive ones.
3488   if (M == CodeModel::Kernel && Offset > 0)
3489     return true;
3490
3491   return false;
3492 }
3493
3494 /// isCalleePop - Determines whether the callee is required to pop its
3495 /// own arguments. Callee pop is necessary to support tail calls.
3496 bool X86::isCalleePop(CallingConv::ID CallingConv,
3497                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3498   if (IsVarArg)
3499     return false;
3500
3501   switch (CallingConv) {
3502   default:
3503     return false;
3504   case CallingConv::X86_StdCall:
3505     return !is64Bit;
3506   case CallingConv::X86_FastCall:
3507     return !is64Bit;
3508   case CallingConv::X86_ThisCall:
3509     return !is64Bit;
3510   case CallingConv::Fast:
3511     return TailCallOpt;
3512   case CallingConv::GHC:
3513     return TailCallOpt;
3514   case CallingConv::HiPE:
3515     return TailCallOpt;
3516   }
3517 }
3518
3519 /// \brief Return true if the condition is an unsigned comparison operation.
3520 static bool isX86CCUnsigned(unsigned X86CC) {
3521   switch (X86CC) {
3522   default: llvm_unreachable("Invalid integer condition!");
3523   case X86::COND_E:     return true;
3524   case X86::COND_G:     return false;
3525   case X86::COND_GE:    return false;
3526   case X86::COND_L:     return false;
3527   case X86::COND_LE:    return false;
3528   case X86::COND_NE:    return true;
3529   case X86::COND_B:     return true;
3530   case X86::COND_A:     return true;
3531   case X86::COND_BE:    return true;
3532   case X86::COND_AE:    return true;
3533   }
3534   llvm_unreachable("covered switch fell through?!");
3535 }
3536
3537 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3538 /// specific condition code, returning the condition code and the LHS/RHS of the
3539 /// comparison to make.
3540 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3541                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3542   if (!isFP) {
3543     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3544       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3545         // X > -1   -> X == 0, jump !sign.
3546         RHS = DAG.getConstant(0, RHS.getValueType());
3547         return X86::COND_NS;
3548       }
3549       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3550         // X < 0   -> X == 0, jump on sign.
3551         return X86::COND_S;
3552       }
3553       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3554         // X < 1   -> X <= 0
3555         RHS = DAG.getConstant(0, RHS.getValueType());
3556         return X86::COND_LE;
3557       }
3558     }
3559
3560     switch (SetCCOpcode) {
3561     default: llvm_unreachable("Invalid integer condition!");
3562     case ISD::SETEQ:  return X86::COND_E;
3563     case ISD::SETGT:  return X86::COND_G;
3564     case ISD::SETGE:  return X86::COND_GE;
3565     case ISD::SETLT:  return X86::COND_L;
3566     case ISD::SETLE:  return X86::COND_LE;
3567     case ISD::SETNE:  return X86::COND_NE;
3568     case ISD::SETULT: return X86::COND_B;
3569     case ISD::SETUGT: return X86::COND_A;
3570     case ISD::SETULE: return X86::COND_BE;
3571     case ISD::SETUGE: return X86::COND_AE;
3572     }
3573   }
3574
3575   // First determine if it is required or is profitable to flip the operands.
3576
3577   // If LHS is a foldable load, but RHS is not, flip the condition.
3578   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3579       !ISD::isNON_EXTLoad(RHS.getNode())) {
3580     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3581     std::swap(LHS, RHS);
3582   }
3583
3584   switch (SetCCOpcode) {
3585   default: break;
3586   case ISD::SETOLT:
3587   case ISD::SETOLE:
3588   case ISD::SETUGT:
3589   case ISD::SETUGE:
3590     std::swap(LHS, RHS);
3591     break;
3592   }
3593
3594   // On a floating point condition, the flags are set as follows:
3595   // ZF  PF  CF   op
3596   //  0 | 0 | 0 | X > Y
3597   //  0 | 0 | 1 | X < Y
3598   //  1 | 0 | 0 | X == Y
3599   //  1 | 1 | 1 | unordered
3600   switch (SetCCOpcode) {
3601   default: llvm_unreachable("Condcode should be pre-legalized away");
3602   case ISD::SETUEQ:
3603   case ISD::SETEQ:   return X86::COND_E;
3604   case ISD::SETOLT:              // flipped
3605   case ISD::SETOGT:
3606   case ISD::SETGT:   return X86::COND_A;
3607   case ISD::SETOLE:              // flipped
3608   case ISD::SETOGE:
3609   case ISD::SETGE:   return X86::COND_AE;
3610   case ISD::SETUGT:              // flipped
3611   case ISD::SETULT:
3612   case ISD::SETLT:   return X86::COND_B;
3613   case ISD::SETUGE:              // flipped
3614   case ISD::SETULE:
3615   case ISD::SETLE:   return X86::COND_BE;
3616   case ISD::SETONE:
3617   case ISD::SETNE:   return X86::COND_NE;
3618   case ISD::SETUO:   return X86::COND_P;
3619   case ISD::SETO:    return X86::COND_NP;
3620   case ISD::SETOEQ:
3621   case ISD::SETUNE:  return X86::COND_INVALID;
3622   }
3623 }
3624
3625 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3626 /// code. Current x86 isa includes the following FP cmov instructions:
3627 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3628 static bool hasFPCMov(unsigned X86CC) {
3629   switch (X86CC) {
3630   default:
3631     return false;
3632   case X86::COND_B:
3633   case X86::COND_BE:
3634   case X86::COND_E:
3635   case X86::COND_P:
3636   case X86::COND_A:
3637   case X86::COND_AE:
3638   case X86::COND_NE:
3639   case X86::COND_NP:
3640     return true;
3641   }
3642 }
3643
3644 /// isFPImmLegal - Returns true if the target can instruction select the
3645 /// specified FP immediate natively. If false, the legalizer will
3646 /// materialize the FP immediate as a load from a constant pool.
3647 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3648   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3649     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3650       return true;
3651   }
3652   return false;
3653 }
3654
3655 /// \brief Returns true if it is beneficial to convert a load of a constant
3656 /// to just the constant itself.
3657 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3658                                                           Type *Ty) const {
3659   assert(Ty->isIntegerTy());
3660
3661   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3662   if (BitSize == 0 || BitSize > 64)
3663     return false;
3664   return true;
3665 }
3666
3667 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3668 /// the specified range (L, H].
3669 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3670   return (Val < 0) || (Val >= Low && Val < Hi);
3671 }
3672
3673 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3674 /// specified value.
3675 static bool isUndefOrEqual(int Val, int CmpVal) {
3676   return (Val < 0 || Val == CmpVal);
3677 }
3678
3679 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3680 /// from position Pos and ending in Pos+Size, falls within the specified
3681 /// sequential range (L, L+Pos]. or is undef.
3682 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3683                                        unsigned Pos, unsigned Size, int Low) {
3684   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3685     if (!isUndefOrEqual(Mask[i], Low))
3686       return false;
3687   return true;
3688 }
3689
3690 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3691 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3692 /// the second operand.
3693 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3694   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3695     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3696   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3697     return (Mask[0] < 2 && Mask[1] < 2);
3698   return false;
3699 }
3700
3701 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3702 /// is suitable for input to PSHUFHW.
3703 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3704   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3705     return false;
3706
3707   // Lower quadword copied in order or undef.
3708   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3709     return false;
3710
3711   // Upper quadword shuffled.
3712   for (unsigned i = 4; i != 8; ++i)
3713     if (!isUndefOrInRange(Mask[i], 4, 8))
3714       return false;
3715
3716   if (VT == MVT::v16i16) {
3717     // Lower quadword copied in order or undef.
3718     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3719       return false;
3720
3721     // Upper quadword shuffled.
3722     for (unsigned i = 12; i != 16; ++i)
3723       if (!isUndefOrInRange(Mask[i], 12, 16))
3724         return false;
3725   }
3726
3727   return true;
3728 }
3729
3730 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3731 /// is suitable for input to PSHUFLW.
3732 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3733   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3734     return false;
3735
3736   // Upper quadword copied in order.
3737   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3738     return false;
3739
3740   // Lower quadword shuffled.
3741   for (unsigned i = 0; i != 4; ++i)
3742     if (!isUndefOrInRange(Mask[i], 0, 4))
3743       return false;
3744
3745   if (VT == MVT::v16i16) {
3746     // Upper quadword copied in order.
3747     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3748       return false;
3749
3750     // Lower quadword shuffled.
3751     for (unsigned i = 8; i != 12; ++i)
3752       if (!isUndefOrInRange(Mask[i], 8, 12))
3753         return false;
3754   }
3755
3756   return true;
3757 }
3758
3759 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3760 /// is suitable for input to PALIGNR.
3761 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3762                           const X86Subtarget *Subtarget) {
3763   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3764       (VT.is256BitVector() && !Subtarget->hasInt256()))
3765     return false;
3766
3767   unsigned NumElts = VT.getVectorNumElements();
3768   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3769   unsigned NumLaneElts = NumElts/NumLanes;
3770
3771   // Do not handle 64-bit element shuffles with palignr.
3772   if (NumLaneElts == 2)
3773     return false;
3774
3775   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3776     unsigned i;
3777     for (i = 0; i != NumLaneElts; ++i) {
3778       if (Mask[i+l] >= 0)
3779         break;
3780     }
3781
3782     // Lane is all undef, go to next lane
3783     if (i == NumLaneElts)
3784       continue;
3785
3786     int Start = Mask[i+l];
3787
3788     // Make sure its in this lane in one of the sources
3789     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3790         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3791       return false;
3792
3793     // If not lane 0, then we must match lane 0
3794     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3795       return false;
3796
3797     // Correct second source to be contiguous with first source
3798     if (Start >= (int)NumElts)
3799       Start -= NumElts - NumLaneElts;
3800
3801     // Make sure we're shifting in the right direction.
3802     if (Start <= (int)(i+l))
3803       return false;
3804
3805     Start -= i;
3806
3807     // Check the rest of the elements to see if they are consecutive.
3808     for (++i; i != NumLaneElts; ++i) {
3809       int Idx = Mask[i+l];
3810
3811       // Make sure its in this lane
3812       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3813           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3814         return false;
3815
3816       // If not lane 0, then we must match lane 0
3817       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3818         return false;
3819
3820       if (Idx >= (int)NumElts)
3821         Idx -= NumElts - NumLaneElts;
3822
3823       if (!isUndefOrEqual(Idx, Start+i))
3824         return false;
3825
3826     }
3827   }
3828
3829   return true;
3830 }
3831
3832 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3833 /// the two vector operands have swapped position.
3834 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3835                                      unsigned NumElems) {
3836   for (unsigned i = 0; i != NumElems; ++i) {
3837     int idx = Mask[i];
3838     if (idx < 0)
3839       continue;
3840     else if (idx < (int)NumElems)
3841       Mask[i] = idx + NumElems;
3842     else
3843       Mask[i] = idx - NumElems;
3844   }
3845 }
3846
3847 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3848 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3849 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3850 /// reverse of what x86 shuffles want.
3851 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3852
3853   unsigned NumElems = VT.getVectorNumElements();
3854   unsigned NumLanes = VT.getSizeInBits()/128;
3855   unsigned NumLaneElems = NumElems/NumLanes;
3856
3857   if (NumLaneElems != 2 && NumLaneElems != 4)
3858     return false;
3859
3860   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3861   bool symetricMaskRequired =
3862     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3863
3864   // VSHUFPSY divides the resulting vector into 4 chunks.
3865   // The sources are also splitted into 4 chunks, and each destination
3866   // chunk must come from a different source chunk.
3867   //
3868   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3869   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3870   //
3871   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3872   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3873   //
3874   // VSHUFPDY divides the resulting vector into 4 chunks.
3875   // The sources are also splitted into 4 chunks, and each destination
3876   // chunk must come from a different source chunk.
3877   //
3878   //  SRC1 =>      X3       X2       X1       X0
3879   //  SRC2 =>      Y3       Y2       Y1       Y0
3880   //
3881   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3882   //
3883   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3884   unsigned HalfLaneElems = NumLaneElems/2;
3885   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3886     for (unsigned i = 0; i != NumLaneElems; ++i) {
3887       int Idx = Mask[i+l];
3888       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3889       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3890         return false;
3891       // For VSHUFPSY, the mask of the second half must be the same as the
3892       // first but with the appropriate offsets. This works in the same way as
3893       // VPERMILPS works with masks.
3894       if (!symetricMaskRequired || Idx < 0)
3895         continue;
3896       if (MaskVal[i] < 0) {
3897         MaskVal[i] = Idx - l;
3898         continue;
3899       }
3900       if ((signed)(Idx - l) != MaskVal[i])
3901         return false;
3902     }
3903   }
3904
3905   return true;
3906 }
3907
3908 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3909 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3910 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3911   if (!VT.is128BitVector())
3912     return false;
3913
3914   unsigned NumElems = VT.getVectorNumElements();
3915
3916   if (NumElems != 4)
3917     return false;
3918
3919   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3920   return isUndefOrEqual(Mask[0], 6) &&
3921          isUndefOrEqual(Mask[1], 7) &&
3922          isUndefOrEqual(Mask[2], 2) &&
3923          isUndefOrEqual(Mask[3], 3);
3924 }
3925
3926 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3927 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3928 /// <2, 3, 2, 3>
3929 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3930   if (!VT.is128BitVector())
3931     return false;
3932
3933   unsigned NumElems = VT.getVectorNumElements();
3934
3935   if (NumElems != 4)
3936     return false;
3937
3938   return isUndefOrEqual(Mask[0], 2) &&
3939          isUndefOrEqual(Mask[1], 3) &&
3940          isUndefOrEqual(Mask[2], 2) &&
3941          isUndefOrEqual(Mask[3], 3);
3942 }
3943
3944 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3945 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3946 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3947   if (!VT.is128BitVector())
3948     return false;
3949
3950   unsigned NumElems = VT.getVectorNumElements();
3951
3952   if (NumElems != 2 && NumElems != 4)
3953     return false;
3954
3955   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3956     if (!isUndefOrEqual(Mask[i], i + NumElems))
3957       return false;
3958
3959   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3960     if (!isUndefOrEqual(Mask[i], i))
3961       return false;
3962
3963   return true;
3964 }
3965
3966 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3967 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3968 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3969   if (!VT.is128BitVector())
3970     return false;
3971
3972   unsigned NumElems = VT.getVectorNumElements();
3973
3974   if (NumElems != 2 && NumElems != 4)
3975     return false;
3976
3977   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3978     if (!isUndefOrEqual(Mask[i], i))
3979       return false;
3980
3981   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3982     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3983       return false;
3984
3985   return true;
3986 }
3987
3988 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3989 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3990 /// i. e: If all but one element come from the same vector.
3991 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3992   // TODO: Deal with AVX's VINSERTPS
3993   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3994     return false;
3995
3996   unsigned CorrectPosV1 = 0;
3997   unsigned CorrectPosV2 = 0;
3998   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3999     if (Mask[i] == -1) {
4000       ++CorrectPosV1;
4001       ++CorrectPosV2;
4002       continue;
4003     }
4004
4005     if (Mask[i] == i)
4006       ++CorrectPosV1;
4007     else if (Mask[i] == i + 4)
4008       ++CorrectPosV2;
4009   }
4010
4011   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4012     // We have 3 elements (undefs count as elements from any vector) from one
4013     // vector, and one from another.
4014     return true;
4015
4016   return false;
4017 }
4018
4019 //
4020 // Some special combinations that can be optimized.
4021 //
4022 static
4023 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4024                                SelectionDAG &DAG) {
4025   MVT VT = SVOp->getSimpleValueType(0);
4026   SDLoc dl(SVOp);
4027
4028   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4029     return SDValue();
4030
4031   ArrayRef<int> Mask = SVOp->getMask();
4032
4033   // These are the special masks that may be optimized.
4034   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4035   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4036   bool MatchEvenMask = true;
4037   bool MatchOddMask  = true;
4038   for (int i=0; i<8; ++i) {
4039     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4040       MatchEvenMask = false;
4041     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4042       MatchOddMask = false;
4043   }
4044
4045   if (!MatchEvenMask && !MatchOddMask)
4046     return SDValue();
4047
4048   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4049
4050   SDValue Op0 = SVOp->getOperand(0);
4051   SDValue Op1 = SVOp->getOperand(1);
4052
4053   if (MatchEvenMask) {
4054     // Shift the second operand right to 32 bits.
4055     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4056     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4057   } else {
4058     // Shift the first operand left to 32 bits.
4059     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4060     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4061   }
4062   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4063   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4064 }
4065
4066 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4067 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4068 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4069                          bool HasInt256, bool V2IsSplat = false) {
4070
4071   assert(VT.getSizeInBits() >= 128 &&
4072          "Unsupported vector type for unpckl");
4073
4074   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4075   unsigned NumLanes;
4076   unsigned NumOf256BitLanes;
4077   unsigned NumElts = VT.getVectorNumElements();
4078   if (VT.is256BitVector()) {
4079     if (NumElts != 4 && NumElts != 8 &&
4080         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4081     return false;
4082     NumLanes = 2;
4083     NumOf256BitLanes = 1;
4084   } else if (VT.is512BitVector()) {
4085     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4086            "Unsupported vector type for unpckh");
4087     NumLanes = 2;
4088     NumOf256BitLanes = 2;
4089   } else {
4090     NumLanes = 1;
4091     NumOf256BitLanes = 1;
4092   }
4093
4094   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4095   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4096
4097   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4098     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4099       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4100         int BitI  = Mask[l256*NumEltsInStride+l+i];
4101         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4102         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4103           return false;
4104         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4105           return false;
4106         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4107           return false;
4108       }
4109     }
4110   }
4111   return true;
4112 }
4113
4114 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4115 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4116 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4117                          bool HasInt256, bool V2IsSplat = false) {
4118   assert(VT.getSizeInBits() >= 128 &&
4119          "Unsupported vector type for unpckh");
4120
4121   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4122   unsigned NumLanes;
4123   unsigned NumOf256BitLanes;
4124   unsigned NumElts = VT.getVectorNumElements();
4125   if (VT.is256BitVector()) {
4126     if (NumElts != 4 && NumElts != 8 &&
4127         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4128     return false;
4129     NumLanes = 2;
4130     NumOf256BitLanes = 1;
4131   } else if (VT.is512BitVector()) {
4132     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4133            "Unsupported vector type for unpckh");
4134     NumLanes = 2;
4135     NumOf256BitLanes = 2;
4136   } else {
4137     NumLanes = 1;
4138     NumOf256BitLanes = 1;
4139   }
4140
4141   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4142   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4143
4144   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4145     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4146       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4147         int BitI  = Mask[l256*NumEltsInStride+l+i];
4148         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4149         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4150           return false;
4151         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4152           return false;
4153         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4154           return false;
4155       }
4156     }
4157   }
4158   return true;
4159 }
4160
4161 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4162 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4163 /// <0, 0, 1, 1>
4164 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4165   unsigned NumElts = VT.getVectorNumElements();
4166   bool Is256BitVec = VT.is256BitVector();
4167
4168   if (VT.is512BitVector())
4169     return false;
4170   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4171          "Unsupported vector type for unpckh");
4172
4173   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4174       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4175     return false;
4176
4177   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4178   // FIXME: Need a better way to get rid of this, there's no latency difference
4179   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4180   // the former later. We should also remove the "_undef" special mask.
4181   if (NumElts == 4 && Is256BitVec)
4182     return false;
4183
4184   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4185   // independently on 128-bit lanes.
4186   unsigned NumLanes = VT.getSizeInBits()/128;
4187   unsigned NumLaneElts = NumElts/NumLanes;
4188
4189   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4190     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4191       int BitI  = Mask[l+i];
4192       int BitI1 = Mask[l+i+1];
4193
4194       if (!isUndefOrEqual(BitI, j))
4195         return false;
4196       if (!isUndefOrEqual(BitI1, j))
4197         return false;
4198     }
4199   }
4200
4201   return true;
4202 }
4203
4204 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4205 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4206 /// <2, 2, 3, 3>
4207 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4208   unsigned NumElts = VT.getVectorNumElements();
4209
4210   if (VT.is512BitVector())
4211     return false;
4212
4213   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4214          "Unsupported vector type for unpckh");
4215
4216   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4217       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4218     return false;
4219
4220   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4221   // independently on 128-bit lanes.
4222   unsigned NumLanes = VT.getSizeInBits()/128;
4223   unsigned NumLaneElts = NumElts/NumLanes;
4224
4225   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4226     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4227       int BitI  = Mask[l+i];
4228       int BitI1 = Mask[l+i+1];
4229       if (!isUndefOrEqual(BitI, j))
4230         return false;
4231       if (!isUndefOrEqual(BitI1, j))
4232         return false;
4233     }
4234   }
4235   return true;
4236 }
4237
4238 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4239 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4240 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4241   if (!VT.is512BitVector())
4242     return false;
4243
4244   unsigned NumElts = VT.getVectorNumElements();
4245   unsigned HalfSize = NumElts/2;
4246   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4247     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4248       *Imm = 1;
4249       return true;
4250     }
4251   }
4252   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4253     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4254       *Imm = 0;
4255       return true;
4256     }
4257   }
4258   return false;
4259 }
4260
4261 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4262 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4263 /// MOVSD, and MOVD, i.e. setting the lowest element.
4264 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4265   if (VT.getVectorElementType().getSizeInBits() < 32)
4266     return false;
4267   if (!VT.is128BitVector())
4268     return false;
4269
4270   unsigned NumElts = VT.getVectorNumElements();
4271
4272   if (!isUndefOrEqual(Mask[0], NumElts))
4273     return false;
4274
4275   for (unsigned i = 1; i != NumElts; ++i)
4276     if (!isUndefOrEqual(Mask[i], i))
4277       return false;
4278
4279   return true;
4280 }
4281
4282 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4283 /// as permutations between 128-bit chunks or halves. As an example: this
4284 /// shuffle bellow:
4285 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4286 /// The first half comes from the second half of V1 and the second half from the
4287 /// the second half of V2.
4288 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4289   if (!HasFp256 || !VT.is256BitVector())
4290     return false;
4291
4292   // The shuffle result is divided into half A and half B. In total the two
4293   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4294   // B must come from C, D, E or F.
4295   unsigned HalfSize = VT.getVectorNumElements()/2;
4296   bool MatchA = false, MatchB = false;
4297
4298   // Check if A comes from one of C, D, E, F.
4299   for (unsigned Half = 0; Half != 4; ++Half) {
4300     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4301       MatchA = true;
4302       break;
4303     }
4304   }
4305
4306   // Check if B comes from one of C, D, E, F.
4307   for (unsigned Half = 0; Half != 4; ++Half) {
4308     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4309       MatchB = true;
4310       break;
4311     }
4312   }
4313
4314   return MatchA && MatchB;
4315 }
4316
4317 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4318 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4319 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4320   MVT VT = SVOp->getSimpleValueType(0);
4321
4322   unsigned HalfSize = VT.getVectorNumElements()/2;
4323
4324   unsigned FstHalf = 0, SndHalf = 0;
4325   for (unsigned i = 0; i < HalfSize; ++i) {
4326     if (SVOp->getMaskElt(i) > 0) {
4327       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4328       break;
4329     }
4330   }
4331   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4332     if (SVOp->getMaskElt(i) > 0) {
4333       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4334       break;
4335     }
4336   }
4337
4338   return (FstHalf | (SndHalf << 4));
4339 }
4340
4341 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4342 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4343   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4344   if (EltSize < 32)
4345     return false;
4346
4347   unsigned NumElts = VT.getVectorNumElements();
4348   Imm8 = 0;
4349   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4350     for (unsigned i = 0; i != NumElts; ++i) {
4351       if (Mask[i] < 0)
4352         continue;
4353       Imm8 |= Mask[i] << (i*2);
4354     }
4355     return true;
4356   }
4357
4358   unsigned LaneSize = 4;
4359   SmallVector<int, 4> MaskVal(LaneSize, -1);
4360
4361   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4362     for (unsigned i = 0; i != LaneSize; ++i) {
4363       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4364         return false;
4365       if (Mask[i+l] < 0)
4366         continue;
4367       if (MaskVal[i] < 0) {
4368         MaskVal[i] = Mask[i+l] - l;
4369         Imm8 |= MaskVal[i] << (i*2);
4370         continue;
4371       }
4372       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4373         return false;
4374     }
4375   }
4376   return true;
4377 }
4378
4379 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4380 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4381 /// Note that VPERMIL mask matching is different depending whether theunderlying
4382 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4383 /// to the same elements of the low, but to the higher half of the source.
4384 /// In VPERMILPD the two lanes could be shuffled independently of each other
4385 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4386 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4387   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4388   if (VT.getSizeInBits() < 256 || EltSize < 32)
4389     return false;
4390   bool symetricMaskRequired = (EltSize == 32);
4391   unsigned NumElts = VT.getVectorNumElements();
4392
4393   unsigned NumLanes = VT.getSizeInBits()/128;
4394   unsigned LaneSize = NumElts/NumLanes;
4395   // 2 or 4 elements in one lane
4396
4397   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4398   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4399     for (unsigned i = 0; i != LaneSize; ++i) {
4400       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4401         return false;
4402       if (symetricMaskRequired) {
4403         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4404           ExpectedMaskVal[i] = Mask[i+l] - l;
4405           continue;
4406         }
4407         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4408           return false;
4409       }
4410     }
4411   }
4412   return true;
4413 }
4414
4415 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4416 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4417 /// element of vector 2 and the other elements to come from vector 1 in order.
4418 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4419                                bool V2IsSplat = false, bool V2IsUndef = false) {
4420   if (!VT.is128BitVector())
4421     return false;
4422
4423   unsigned NumOps = VT.getVectorNumElements();
4424   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4425     return false;
4426
4427   if (!isUndefOrEqual(Mask[0], 0))
4428     return false;
4429
4430   for (unsigned i = 1; i != NumOps; ++i)
4431     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4432           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4433           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4434       return false;
4435
4436   return true;
4437 }
4438
4439 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4440 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4441 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4442 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4443                            const X86Subtarget *Subtarget) {
4444   if (!Subtarget->hasSSE3())
4445     return false;
4446
4447   unsigned NumElems = VT.getVectorNumElements();
4448
4449   if ((VT.is128BitVector() && NumElems != 4) ||
4450       (VT.is256BitVector() && NumElems != 8) ||
4451       (VT.is512BitVector() && NumElems != 16))
4452     return false;
4453
4454   // "i+1" is the value the indexed mask element must have
4455   for (unsigned i = 0; i != NumElems; i += 2)
4456     if (!isUndefOrEqual(Mask[i], i+1) ||
4457         !isUndefOrEqual(Mask[i+1], i+1))
4458       return false;
4459
4460   return true;
4461 }
4462
4463 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4464 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4465 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4466 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4467                            const X86Subtarget *Subtarget) {
4468   if (!Subtarget->hasSSE3())
4469     return false;
4470
4471   unsigned NumElems = VT.getVectorNumElements();
4472
4473   if ((VT.is128BitVector() && NumElems != 4) ||
4474       (VT.is256BitVector() && NumElems != 8) ||
4475       (VT.is512BitVector() && NumElems != 16))
4476     return false;
4477
4478   // "i" is the value the indexed mask element must have
4479   for (unsigned i = 0; i != NumElems; i += 2)
4480     if (!isUndefOrEqual(Mask[i], i) ||
4481         !isUndefOrEqual(Mask[i+1], i))
4482       return false;
4483
4484   return true;
4485 }
4486
4487 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4488 /// specifies a shuffle of elements that is suitable for input to 256-bit
4489 /// version of MOVDDUP.
4490 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4491   if (!HasFp256 || !VT.is256BitVector())
4492     return false;
4493
4494   unsigned NumElts = VT.getVectorNumElements();
4495   if (NumElts != 4)
4496     return false;
4497
4498   for (unsigned i = 0; i != NumElts/2; ++i)
4499     if (!isUndefOrEqual(Mask[i], 0))
4500       return false;
4501   for (unsigned i = NumElts/2; i != NumElts; ++i)
4502     if (!isUndefOrEqual(Mask[i], NumElts/2))
4503       return false;
4504   return true;
4505 }
4506
4507 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4508 /// specifies a shuffle of elements that is suitable for input to 128-bit
4509 /// version of MOVDDUP.
4510 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4511   if (!VT.is128BitVector())
4512     return false;
4513
4514   unsigned e = VT.getVectorNumElements() / 2;
4515   for (unsigned i = 0; i != e; ++i)
4516     if (!isUndefOrEqual(Mask[i], i))
4517       return false;
4518   for (unsigned i = 0; i != e; ++i)
4519     if (!isUndefOrEqual(Mask[e+i], i))
4520       return false;
4521   return true;
4522 }
4523
4524 /// isVEXTRACTIndex - Return true if the specified
4525 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4526 /// suitable for instruction that extract 128 or 256 bit vectors
4527 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4528   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4529   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4530     return false;
4531
4532   // The index should be aligned on a vecWidth-bit boundary.
4533   uint64_t Index =
4534     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4535
4536   MVT VT = N->getSimpleValueType(0);
4537   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4538   bool Result = (Index * ElSize) % vecWidth == 0;
4539
4540   return Result;
4541 }
4542
4543 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4544 /// operand specifies a subvector insert that is suitable for input to
4545 /// insertion of 128 or 256-bit subvectors
4546 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4547   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4548   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4549     return false;
4550   // The index should be aligned on a vecWidth-bit boundary.
4551   uint64_t Index =
4552     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4553
4554   MVT VT = N->getSimpleValueType(0);
4555   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4556   bool Result = (Index * ElSize) % vecWidth == 0;
4557
4558   return Result;
4559 }
4560
4561 bool X86::isVINSERT128Index(SDNode *N) {
4562   return isVINSERTIndex(N, 128);
4563 }
4564
4565 bool X86::isVINSERT256Index(SDNode *N) {
4566   return isVINSERTIndex(N, 256);
4567 }
4568
4569 bool X86::isVEXTRACT128Index(SDNode *N) {
4570   return isVEXTRACTIndex(N, 128);
4571 }
4572
4573 bool X86::isVEXTRACT256Index(SDNode *N) {
4574   return isVEXTRACTIndex(N, 256);
4575 }
4576
4577 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4578 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4579 /// Handles 128-bit and 256-bit.
4580 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4581   MVT VT = N->getSimpleValueType(0);
4582
4583   assert((VT.getSizeInBits() >= 128) &&
4584          "Unsupported vector type for PSHUF/SHUFP");
4585
4586   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4587   // independently on 128-bit lanes.
4588   unsigned NumElts = VT.getVectorNumElements();
4589   unsigned NumLanes = VT.getSizeInBits()/128;
4590   unsigned NumLaneElts = NumElts/NumLanes;
4591
4592   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4593          "Only supports 2, 4 or 8 elements per lane");
4594
4595   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4596   unsigned Mask = 0;
4597   for (unsigned i = 0; i != NumElts; ++i) {
4598     int Elt = N->getMaskElt(i);
4599     if (Elt < 0) continue;
4600     Elt &= NumLaneElts - 1;
4601     unsigned ShAmt = (i << Shift) % 8;
4602     Mask |= Elt << ShAmt;
4603   }
4604
4605   return Mask;
4606 }
4607
4608 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4609 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4610 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4611   MVT VT = N->getSimpleValueType(0);
4612
4613   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4614          "Unsupported vector type for PSHUFHW");
4615
4616   unsigned NumElts = VT.getVectorNumElements();
4617
4618   unsigned Mask = 0;
4619   for (unsigned l = 0; l != NumElts; l += 8) {
4620     // 8 nodes per lane, but we only care about the last 4.
4621     for (unsigned i = 0; i < 4; ++i) {
4622       int Elt = N->getMaskElt(l+i+4);
4623       if (Elt < 0) continue;
4624       Elt &= 0x3; // only 2-bits.
4625       Mask |= Elt << (i * 2);
4626     }
4627   }
4628
4629   return Mask;
4630 }
4631
4632 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4633 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4634 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4635   MVT VT = N->getSimpleValueType(0);
4636
4637   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4638          "Unsupported vector type for PSHUFHW");
4639
4640   unsigned NumElts = VT.getVectorNumElements();
4641
4642   unsigned Mask = 0;
4643   for (unsigned l = 0; l != NumElts; l += 8) {
4644     // 8 nodes per lane, but we only care about the first 4.
4645     for (unsigned i = 0; i < 4; ++i) {
4646       int Elt = N->getMaskElt(l+i);
4647       if (Elt < 0) continue;
4648       Elt &= 0x3; // only 2-bits
4649       Mask |= Elt << (i * 2);
4650     }
4651   }
4652
4653   return Mask;
4654 }
4655
4656 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4657 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4658 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4659   MVT VT = SVOp->getSimpleValueType(0);
4660   unsigned EltSize = VT.is512BitVector() ? 1 :
4661     VT.getVectorElementType().getSizeInBits() >> 3;
4662
4663   unsigned NumElts = VT.getVectorNumElements();
4664   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4665   unsigned NumLaneElts = NumElts/NumLanes;
4666
4667   int Val = 0;
4668   unsigned i;
4669   for (i = 0; i != NumElts; ++i) {
4670     Val = SVOp->getMaskElt(i);
4671     if (Val >= 0)
4672       break;
4673   }
4674   if (Val >= (int)NumElts)
4675     Val -= NumElts - NumLaneElts;
4676
4677   assert(Val - i > 0 && "PALIGNR imm should be positive");
4678   return (Val - i) * EltSize;
4679 }
4680
4681 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4682   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4683   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4684     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4685
4686   uint64_t Index =
4687     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4688
4689   MVT VecVT = N->getOperand(0).getSimpleValueType();
4690   MVT ElVT = VecVT.getVectorElementType();
4691
4692   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4693   return Index / NumElemsPerChunk;
4694 }
4695
4696 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4697   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4698   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4699     llvm_unreachable("Illegal insert subvector for VINSERT");
4700
4701   uint64_t Index =
4702     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4703
4704   MVT VecVT = N->getSimpleValueType(0);
4705   MVT ElVT = VecVT.getVectorElementType();
4706
4707   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4708   return Index / NumElemsPerChunk;
4709 }
4710
4711 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4712 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4713 /// and VINSERTI128 instructions.
4714 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4715   return getExtractVEXTRACTImmediate(N, 128);
4716 }
4717
4718 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4719 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4720 /// and VINSERTI64x4 instructions.
4721 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4722   return getExtractVEXTRACTImmediate(N, 256);
4723 }
4724
4725 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4726 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4727 /// and VINSERTI128 instructions.
4728 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4729   return getInsertVINSERTImmediate(N, 128);
4730 }
4731
4732 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4733 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4734 /// and VINSERTI64x4 instructions.
4735 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4736   return getInsertVINSERTImmediate(N, 256);
4737 }
4738
4739 /// isZero - Returns true if Elt is a constant integer zero
4740 static bool isZero(SDValue V) {
4741   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4742   return C && C->isNullValue();
4743 }
4744
4745 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4746 /// constant +0.0.
4747 bool X86::isZeroNode(SDValue Elt) {
4748   if (isZero(Elt))
4749     return true;
4750   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4751     return CFP->getValueAPF().isPosZero();
4752   return false;
4753 }
4754
4755 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4756 /// their permute mask.
4757 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4758                                     SelectionDAG &DAG) {
4759   MVT VT = SVOp->getSimpleValueType(0);
4760   unsigned NumElems = VT.getVectorNumElements();
4761   SmallVector<int, 8> MaskVec;
4762
4763   for (unsigned i = 0; i != NumElems; ++i) {
4764     int Idx = SVOp->getMaskElt(i);
4765     if (Idx >= 0) {
4766       if (Idx < (int)NumElems)
4767         Idx += NumElems;
4768       else
4769         Idx -= NumElems;
4770     }
4771     MaskVec.push_back(Idx);
4772   }
4773   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4774                               SVOp->getOperand(0), &MaskVec[0]);
4775 }
4776
4777 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4778 /// match movhlps. The lower half elements should come from upper half of
4779 /// V1 (and in order), and the upper half elements should come from the upper
4780 /// half of V2 (and in order).
4781 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4782   if (!VT.is128BitVector())
4783     return false;
4784   if (VT.getVectorNumElements() != 4)
4785     return false;
4786   for (unsigned i = 0, e = 2; i != e; ++i)
4787     if (!isUndefOrEqual(Mask[i], i+2))
4788       return false;
4789   for (unsigned i = 2; i != 4; ++i)
4790     if (!isUndefOrEqual(Mask[i], i+4))
4791       return false;
4792   return true;
4793 }
4794
4795 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4796 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4797 /// required.
4798 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4799   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4800     return false;
4801   N = N->getOperand(0).getNode();
4802   if (!ISD::isNON_EXTLoad(N))
4803     return false;
4804   if (LD)
4805     *LD = cast<LoadSDNode>(N);
4806   return true;
4807 }
4808
4809 // Test whether the given value is a vector value which will be legalized
4810 // into a load.
4811 static bool WillBeConstantPoolLoad(SDNode *N) {
4812   if (N->getOpcode() != ISD::BUILD_VECTOR)
4813     return false;
4814
4815   // Check for any non-constant elements.
4816   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4817     switch (N->getOperand(i).getNode()->getOpcode()) {
4818     case ISD::UNDEF:
4819     case ISD::ConstantFP:
4820     case ISD::Constant:
4821       break;
4822     default:
4823       return false;
4824     }
4825
4826   // Vectors of all-zeros and all-ones are materialized with special
4827   // instructions rather than being loaded.
4828   return !ISD::isBuildVectorAllZeros(N) &&
4829          !ISD::isBuildVectorAllOnes(N);
4830 }
4831
4832 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4833 /// match movlp{s|d}. The lower half elements should come from lower half of
4834 /// V1 (and in order), and the upper half elements should come from the upper
4835 /// half of V2 (and in order). And since V1 will become the source of the
4836 /// MOVLP, it must be either a vector load or a scalar load to vector.
4837 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4838                                ArrayRef<int> Mask, MVT VT) {
4839   if (!VT.is128BitVector())
4840     return false;
4841
4842   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4843     return false;
4844   // Is V2 is a vector load, don't do this transformation. We will try to use
4845   // load folding shufps op.
4846   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4847     return false;
4848
4849   unsigned NumElems = VT.getVectorNumElements();
4850
4851   if (NumElems != 2 && NumElems != 4)
4852     return false;
4853   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4854     if (!isUndefOrEqual(Mask[i], i))
4855       return false;
4856   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4857     if (!isUndefOrEqual(Mask[i], i+NumElems))
4858       return false;
4859   return true;
4860 }
4861
4862 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4863 /// to an zero vector.
4864 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4865 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4866   SDValue V1 = N->getOperand(0);
4867   SDValue V2 = N->getOperand(1);
4868   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4869   for (unsigned i = 0; i != NumElems; ++i) {
4870     int Idx = N->getMaskElt(i);
4871     if (Idx >= (int)NumElems) {
4872       unsigned Opc = V2.getOpcode();
4873       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4874         continue;
4875       if (Opc != ISD::BUILD_VECTOR ||
4876           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4877         return false;
4878     } else if (Idx >= 0) {
4879       unsigned Opc = V1.getOpcode();
4880       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4881         continue;
4882       if (Opc != ISD::BUILD_VECTOR ||
4883           !X86::isZeroNode(V1.getOperand(Idx)))
4884         return false;
4885     }
4886   }
4887   return true;
4888 }
4889
4890 /// getZeroVector - Returns a vector of specified type with all zero elements.
4891 ///
4892 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4893                              SelectionDAG &DAG, SDLoc dl) {
4894   assert(VT.isVector() && "Expected a vector type");
4895
4896   // Always build SSE zero vectors as <4 x i32> bitcasted
4897   // to their dest type. This ensures they get CSE'd.
4898   SDValue Vec;
4899   if (VT.is128BitVector()) {  // SSE
4900     if (Subtarget->hasSSE2()) {  // SSE2
4901       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4902       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4903     } else { // SSE1
4904       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4905       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4906     }
4907   } else if (VT.is256BitVector()) { // AVX
4908     if (Subtarget->hasInt256()) { // AVX2
4909       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4910       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4911       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4912     } else {
4913       // 256-bit logic and arithmetic instructions in AVX are all
4914       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4915       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4916       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4917       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4918     }
4919   } else if (VT.is512BitVector()) { // AVX-512
4920       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4921       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4922                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4923       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4924   } else if (VT.getScalarType() == MVT::i1) {
4925     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4926     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4927     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4928     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4929   } else
4930     llvm_unreachable("Unexpected vector type");
4931
4932   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4933 }
4934
4935 /// getOnesVector - Returns a vector of specified type with all bits set.
4936 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4937 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4938 /// Then bitcast to their original type, ensuring they get CSE'd.
4939 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4940                              SDLoc dl) {
4941   assert(VT.isVector() && "Expected a vector type");
4942
4943   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4944   SDValue Vec;
4945   if (VT.is256BitVector()) {
4946     if (HasInt256) { // AVX2
4947       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4948       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4949     } else { // AVX
4950       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4951       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4952     }
4953   } else if (VT.is128BitVector()) {
4954     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4955   } else
4956     llvm_unreachable("Unexpected vector type");
4957
4958   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4959 }
4960
4961 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4962 /// that point to V2 points to its first element.
4963 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4964   for (unsigned i = 0; i != NumElems; ++i) {
4965     if (Mask[i] > (int)NumElems) {
4966       Mask[i] = NumElems;
4967     }
4968   }
4969 }
4970
4971 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4972 /// operation of specified width.
4973 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4974                        SDValue V2) {
4975   unsigned NumElems = VT.getVectorNumElements();
4976   SmallVector<int, 8> Mask;
4977   Mask.push_back(NumElems);
4978   for (unsigned i = 1; i != NumElems; ++i)
4979     Mask.push_back(i);
4980   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4981 }
4982
4983 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4984 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4985                           SDValue V2) {
4986   unsigned NumElems = VT.getVectorNumElements();
4987   SmallVector<int, 8> Mask;
4988   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4989     Mask.push_back(i);
4990     Mask.push_back(i + NumElems);
4991   }
4992   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4993 }
4994
4995 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4996 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4997                           SDValue V2) {
4998   unsigned NumElems = VT.getVectorNumElements();
4999   SmallVector<int, 8> Mask;
5000   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5001     Mask.push_back(i + Half);
5002     Mask.push_back(i + NumElems + Half);
5003   }
5004   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5005 }
5006
5007 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5008 // a generic shuffle instruction because the target has no such instructions.
5009 // Generate shuffles which repeat i16 and i8 several times until they can be
5010 // represented by v4f32 and then be manipulated by target suported shuffles.
5011 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5012   MVT VT = V.getSimpleValueType();
5013   int NumElems = VT.getVectorNumElements();
5014   SDLoc dl(V);
5015
5016   while (NumElems > 4) {
5017     if (EltNo < NumElems/2) {
5018       V = getUnpackl(DAG, dl, VT, V, V);
5019     } else {
5020       V = getUnpackh(DAG, dl, VT, V, V);
5021       EltNo -= NumElems/2;
5022     }
5023     NumElems >>= 1;
5024   }
5025   return V;
5026 }
5027
5028 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5029 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5030   MVT VT = V.getSimpleValueType();
5031   SDLoc dl(V);
5032
5033   if (VT.is128BitVector()) {
5034     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5035     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5036     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5037                              &SplatMask[0]);
5038   } else if (VT.is256BitVector()) {
5039     // To use VPERMILPS to splat scalars, the second half of indicies must
5040     // refer to the higher part, which is a duplication of the lower one,
5041     // because VPERMILPS can only handle in-lane permutations.
5042     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5043                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5044
5045     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5046     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5047                              &SplatMask[0]);
5048   } else
5049     llvm_unreachable("Vector size not supported");
5050
5051   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5052 }
5053
5054 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5055 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5056   MVT SrcVT = SV->getSimpleValueType(0);
5057   SDValue V1 = SV->getOperand(0);
5058   SDLoc dl(SV);
5059
5060   int EltNo = SV->getSplatIndex();
5061   int NumElems = SrcVT.getVectorNumElements();
5062   bool Is256BitVec = SrcVT.is256BitVector();
5063
5064   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5065          "Unknown how to promote splat for type");
5066
5067   // Extract the 128-bit part containing the splat element and update
5068   // the splat element index when it refers to the higher register.
5069   if (Is256BitVec) {
5070     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5071     if (EltNo >= NumElems/2)
5072       EltNo -= NumElems/2;
5073   }
5074
5075   // All i16 and i8 vector types can't be used directly by a generic shuffle
5076   // instruction because the target has no such instruction. Generate shuffles
5077   // which repeat i16 and i8 several times until they fit in i32, and then can
5078   // be manipulated by target suported shuffles.
5079   MVT EltVT = SrcVT.getVectorElementType();
5080   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5081     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5082
5083   // Recreate the 256-bit vector and place the same 128-bit vector
5084   // into the low and high part. This is necessary because we want
5085   // to use VPERM* to shuffle the vectors
5086   if (Is256BitVec) {
5087     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5088   }
5089
5090   return getLegalSplat(DAG, V1, EltNo);
5091 }
5092
5093 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5094 /// vector of zero or undef vector.  This produces a shuffle where the low
5095 /// element of V2 is swizzled into the zero/undef vector, landing at element
5096 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5097 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5098                                            bool IsZero,
5099                                            const X86Subtarget *Subtarget,
5100                                            SelectionDAG &DAG) {
5101   MVT VT = V2.getSimpleValueType();
5102   SDValue V1 = IsZero
5103     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5104   unsigned NumElems = VT.getVectorNumElements();
5105   SmallVector<int, 16> MaskVec;
5106   for (unsigned i = 0; i != NumElems; ++i)
5107     // If this is the insertion idx, put the low elt of V2 here.
5108     MaskVec.push_back(i == Idx ? NumElems : i);
5109   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5110 }
5111
5112 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5113 /// target specific opcode. Returns true if the Mask could be calculated.
5114 /// Sets IsUnary to true if only uses one source.
5115 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5116                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5117   unsigned NumElems = VT.getVectorNumElements();
5118   SDValue ImmN;
5119
5120   IsUnary = false;
5121   switch(N->getOpcode()) {
5122   case X86ISD::SHUFP:
5123     ImmN = N->getOperand(N->getNumOperands()-1);
5124     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5125     break;
5126   case X86ISD::UNPCKH:
5127     DecodeUNPCKHMask(VT, Mask);
5128     break;
5129   case X86ISD::UNPCKL:
5130     DecodeUNPCKLMask(VT, Mask);
5131     break;
5132   case X86ISD::MOVHLPS:
5133     DecodeMOVHLPSMask(NumElems, Mask);
5134     break;
5135   case X86ISD::MOVLHPS:
5136     DecodeMOVLHPSMask(NumElems, Mask);
5137     break;
5138   case X86ISD::PALIGNR:
5139     ImmN = N->getOperand(N->getNumOperands()-1);
5140     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5141     break;
5142   case X86ISD::PSHUFD:
5143   case X86ISD::VPERMILP:
5144     ImmN = N->getOperand(N->getNumOperands()-1);
5145     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5146     IsUnary = true;
5147     break;
5148   case X86ISD::PSHUFHW:
5149     ImmN = N->getOperand(N->getNumOperands()-1);
5150     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5151     IsUnary = true;
5152     break;
5153   case X86ISD::PSHUFLW:
5154     ImmN = N->getOperand(N->getNumOperands()-1);
5155     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5156     IsUnary = true;
5157     break;
5158   case X86ISD::VPERMI:
5159     ImmN = N->getOperand(N->getNumOperands()-1);
5160     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5161     IsUnary = true;
5162     break;
5163   case X86ISD::MOVSS:
5164   case X86ISD::MOVSD: {
5165     // The index 0 always comes from the first element of the second source,
5166     // this is why MOVSS and MOVSD are used in the first place. The other
5167     // elements come from the other positions of the first source vector
5168     Mask.push_back(NumElems);
5169     for (unsigned i = 1; i != NumElems; ++i) {
5170       Mask.push_back(i);
5171     }
5172     break;
5173   }
5174   case X86ISD::VPERM2X128:
5175     ImmN = N->getOperand(N->getNumOperands()-1);
5176     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5177     if (Mask.empty()) return false;
5178     break;
5179   case X86ISD::MOVDDUP:
5180   case X86ISD::MOVLHPD:
5181   case X86ISD::MOVLPD:
5182   case X86ISD::MOVLPS:
5183   case X86ISD::MOVSHDUP:
5184   case X86ISD::MOVSLDUP:
5185     // Not yet implemented
5186     return false;
5187   default: llvm_unreachable("unknown target shuffle node");
5188   }
5189
5190   return true;
5191 }
5192
5193 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5194 /// element of the result of the vector shuffle.
5195 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5196                                    unsigned Depth) {
5197   if (Depth == 6)
5198     return SDValue();  // Limit search depth.
5199
5200   SDValue V = SDValue(N, 0);
5201   EVT VT = V.getValueType();
5202   unsigned Opcode = V.getOpcode();
5203
5204   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5205   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5206     int Elt = SV->getMaskElt(Index);
5207
5208     if (Elt < 0)
5209       return DAG.getUNDEF(VT.getVectorElementType());
5210
5211     unsigned NumElems = VT.getVectorNumElements();
5212     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5213                                          : SV->getOperand(1);
5214     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5215   }
5216
5217   // Recurse into target specific vector shuffles to find scalars.
5218   if (isTargetShuffle(Opcode)) {
5219     MVT ShufVT = V.getSimpleValueType();
5220     unsigned NumElems = ShufVT.getVectorNumElements();
5221     SmallVector<int, 16> ShuffleMask;
5222     bool IsUnary;
5223
5224     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5225       return SDValue();
5226
5227     int Elt = ShuffleMask[Index];
5228     if (Elt < 0)
5229       return DAG.getUNDEF(ShufVT.getVectorElementType());
5230
5231     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5232                                          : N->getOperand(1);
5233     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5234                                Depth+1);
5235   }
5236
5237   // Actual nodes that may contain scalar elements
5238   if (Opcode == ISD::BITCAST) {
5239     V = V.getOperand(0);
5240     EVT SrcVT = V.getValueType();
5241     unsigned NumElems = VT.getVectorNumElements();
5242
5243     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5244       return SDValue();
5245   }
5246
5247   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5248     return (Index == 0) ? V.getOperand(0)
5249                         : DAG.getUNDEF(VT.getVectorElementType());
5250
5251   if (V.getOpcode() == ISD::BUILD_VECTOR)
5252     return V.getOperand(Index);
5253
5254   return SDValue();
5255 }
5256
5257 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5258 /// shuffle operation which come from a consecutively from a zero. The
5259 /// search can start in two different directions, from left or right.
5260 /// We count undefs as zeros until PreferredNum is reached.
5261 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5262                                          unsigned NumElems, bool ZerosFromLeft,
5263                                          SelectionDAG &DAG,
5264                                          unsigned PreferredNum = -1U) {
5265   unsigned NumZeros = 0;
5266   for (unsigned i = 0; i != NumElems; ++i) {
5267     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5268     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5269     if (!Elt.getNode())
5270       break;
5271
5272     if (X86::isZeroNode(Elt))
5273       ++NumZeros;
5274     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5275       NumZeros = std::min(NumZeros + 1, PreferredNum);
5276     else
5277       break;
5278   }
5279
5280   return NumZeros;
5281 }
5282
5283 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5284 /// correspond consecutively to elements from one of the vector operands,
5285 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5286 static
5287 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5288                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5289                               unsigned NumElems, unsigned &OpNum) {
5290   bool SeenV1 = false;
5291   bool SeenV2 = false;
5292
5293   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5294     int Idx = SVOp->getMaskElt(i);
5295     // Ignore undef indicies
5296     if (Idx < 0)
5297       continue;
5298
5299     if (Idx < (int)NumElems)
5300       SeenV1 = true;
5301     else
5302       SeenV2 = true;
5303
5304     // Only accept consecutive elements from the same vector
5305     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5306       return false;
5307   }
5308
5309   OpNum = SeenV1 ? 0 : 1;
5310   return true;
5311 }
5312
5313 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5314 /// logical left shift of a vector.
5315 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5316                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5317   unsigned NumElems =
5318     SVOp->getSimpleValueType(0).getVectorNumElements();
5319   unsigned NumZeros = getNumOfConsecutiveZeros(
5320       SVOp, NumElems, false /* check zeros from right */, DAG,
5321       SVOp->getMaskElt(0));
5322   unsigned OpSrc;
5323
5324   if (!NumZeros)
5325     return false;
5326
5327   // Considering the elements in the mask that are not consecutive zeros,
5328   // check if they consecutively come from only one of the source vectors.
5329   //
5330   //               V1 = {X, A, B, C}     0
5331   //                         \  \  \    /
5332   //   vector_shuffle V1, V2 <1, 2, 3, X>
5333   //
5334   if (!isShuffleMaskConsecutive(SVOp,
5335             0,                   // Mask Start Index
5336             NumElems-NumZeros,   // Mask End Index(exclusive)
5337             NumZeros,            // Where to start looking in the src vector
5338             NumElems,            // Number of elements in vector
5339             OpSrc))              // Which source operand ?
5340     return false;
5341
5342   isLeft = false;
5343   ShAmt = NumZeros;
5344   ShVal = SVOp->getOperand(OpSrc);
5345   return true;
5346 }
5347
5348 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5349 /// logical left shift of a vector.
5350 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5351                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5352   unsigned NumElems =
5353     SVOp->getSimpleValueType(0).getVectorNumElements();
5354   unsigned NumZeros = getNumOfConsecutiveZeros(
5355       SVOp, NumElems, true /* check zeros from left */, DAG,
5356       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5357   unsigned OpSrc;
5358
5359   if (!NumZeros)
5360     return false;
5361
5362   // Considering the elements in the mask that are not consecutive zeros,
5363   // check if they consecutively come from only one of the source vectors.
5364   //
5365   //                           0    { A, B, X, X } = V2
5366   //                          / \    /  /
5367   //   vector_shuffle V1, V2 <X, X, 4, 5>
5368   //
5369   if (!isShuffleMaskConsecutive(SVOp,
5370             NumZeros,     // Mask Start Index
5371             NumElems,     // Mask End Index(exclusive)
5372             0,            // Where to start looking in the src vector
5373             NumElems,     // Number of elements in vector
5374             OpSrc))       // Which source operand ?
5375     return false;
5376
5377   isLeft = true;
5378   ShAmt = NumZeros;
5379   ShVal = SVOp->getOperand(OpSrc);
5380   return true;
5381 }
5382
5383 /// isVectorShift - Returns true if the shuffle can be implemented as a
5384 /// logical left or right shift of a vector.
5385 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5386                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5387   // Although the logic below support any bitwidth size, there are no
5388   // shift instructions which handle more than 128-bit vectors.
5389   if (!SVOp->getSimpleValueType(0).is128BitVector())
5390     return false;
5391
5392   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5393       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5394     return true;
5395
5396   return false;
5397 }
5398
5399 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5400 ///
5401 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5402                                        unsigned NumNonZero, unsigned NumZero,
5403                                        SelectionDAG &DAG,
5404                                        const X86Subtarget* Subtarget,
5405                                        const TargetLowering &TLI) {
5406   if (NumNonZero > 8)
5407     return SDValue();
5408
5409   SDLoc dl(Op);
5410   SDValue V;
5411   bool First = true;
5412   for (unsigned i = 0; i < 16; ++i) {
5413     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5414     if (ThisIsNonZero && First) {
5415       if (NumZero)
5416         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5417       else
5418         V = DAG.getUNDEF(MVT::v8i16);
5419       First = false;
5420     }
5421
5422     if ((i & 1) != 0) {
5423       SDValue ThisElt, LastElt;
5424       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5425       if (LastIsNonZero) {
5426         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5427                               MVT::i16, Op.getOperand(i-1));
5428       }
5429       if (ThisIsNonZero) {
5430         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5431         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5432                               ThisElt, DAG.getConstant(8, MVT::i8));
5433         if (LastIsNonZero)
5434           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5435       } else
5436         ThisElt = LastElt;
5437
5438       if (ThisElt.getNode())
5439         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5440                         DAG.getIntPtrConstant(i/2));
5441     }
5442   }
5443
5444   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5445 }
5446
5447 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5448 ///
5449 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5450                                      unsigned NumNonZero, unsigned NumZero,
5451                                      SelectionDAG &DAG,
5452                                      const X86Subtarget* Subtarget,
5453                                      const TargetLowering &TLI) {
5454   if (NumNonZero > 4)
5455     return SDValue();
5456
5457   SDLoc dl(Op);
5458   SDValue V;
5459   bool First = true;
5460   for (unsigned i = 0; i < 8; ++i) {
5461     bool isNonZero = (NonZeros & (1 << i)) != 0;
5462     if (isNonZero) {
5463       if (First) {
5464         if (NumZero)
5465           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5466         else
5467           V = DAG.getUNDEF(MVT::v8i16);
5468         First = false;
5469       }
5470       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5471                       MVT::v8i16, V, Op.getOperand(i),
5472                       DAG.getIntPtrConstant(i));
5473     }
5474   }
5475
5476   return V;
5477 }
5478
5479 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5480 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5481                                      unsigned NonZeros, unsigned NumNonZero,
5482                                      unsigned NumZero, SelectionDAG &DAG,
5483                                      const X86Subtarget *Subtarget,
5484                                      const TargetLowering &TLI) {
5485   // We know there's at least one non-zero element
5486   unsigned FirstNonZeroIdx = 0;
5487   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5488   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5489          X86::isZeroNode(FirstNonZero)) {
5490     ++FirstNonZeroIdx;
5491     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5492   }
5493
5494   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5495       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5496     return SDValue();
5497
5498   SDValue V = FirstNonZero.getOperand(0);
5499   MVT VVT = V.getSimpleValueType();
5500   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5501     return SDValue();
5502
5503   unsigned FirstNonZeroDst =
5504       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5505   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5506   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5507   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5508
5509   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5510     SDValue Elem = Op.getOperand(Idx);
5511     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5512       continue;
5513
5514     // TODO: What else can be here? Deal with it.
5515     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5516       return SDValue();
5517
5518     // TODO: Some optimizations are still possible here
5519     // ex: Getting one element from a vector, and the rest from another.
5520     if (Elem.getOperand(0) != V)
5521       return SDValue();
5522
5523     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5524     if (Dst == Idx)
5525       ++CorrectIdx;
5526     else if (IncorrectIdx == -1U) {
5527       IncorrectIdx = Idx;
5528       IncorrectDst = Dst;
5529     } else
5530       // There was already one element with an incorrect index.
5531       // We can't optimize this case to an insertps.
5532       return SDValue();
5533   }
5534
5535   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5536     SDLoc dl(Op);
5537     EVT VT = Op.getSimpleValueType();
5538     unsigned ElementMoveMask = 0;
5539     if (IncorrectIdx == -1U)
5540       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5541     else
5542       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5543
5544     SDValue InsertpsMask =
5545         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5546     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5547   }
5548
5549   return SDValue();
5550 }
5551
5552 /// getVShift - Return a vector logical shift node.
5553 ///
5554 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5555                          unsigned NumBits, SelectionDAG &DAG,
5556                          const TargetLowering &TLI, SDLoc dl) {
5557   assert(VT.is128BitVector() && "Unknown type for VShift");
5558   EVT ShVT = MVT::v2i64;
5559   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5560   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5561   return DAG.getNode(ISD::BITCAST, dl, VT,
5562                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5563                              DAG.getConstant(NumBits,
5564                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5565 }
5566
5567 static SDValue
5568 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5569
5570   // Check if the scalar load can be widened into a vector load. And if
5571   // the address is "base + cst" see if the cst can be "absorbed" into
5572   // the shuffle mask.
5573   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5574     SDValue Ptr = LD->getBasePtr();
5575     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5576       return SDValue();
5577     EVT PVT = LD->getValueType(0);
5578     if (PVT != MVT::i32 && PVT != MVT::f32)
5579       return SDValue();
5580
5581     int FI = -1;
5582     int64_t Offset = 0;
5583     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5584       FI = FINode->getIndex();
5585       Offset = 0;
5586     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5587                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5588       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5589       Offset = Ptr.getConstantOperandVal(1);
5590       Ptr = Ptr.getOperand(0);
5591     } else {
5592       return SDValue();
5593     }
5594
5595     // FIXME: 256-bit vector instructions don't require a strict alignment,
5596     // improve this code to support it better.
5597     unsigned RequiredAlign = VT.getSizeInBits()/8;
5598     SDValue Chain = LD->getChain();
5599     // Make sure the stack object alignment is at least 16 or 32.
5600     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5601     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5602       if (MFI->isFixedObjectIndex(FI)) {
5603         // Can't change the alignment. FIXME: It's possible to compute
5604         // the exact stack offset and reference FI + adjust offset instead.
5605         // If someone *really* cares about this. That's the way to implement it.
5606         return SDValue();
5607       } else {
5608         MFI->setObjectAlignment(FI, RequiredAlign);
5609       }
5610     }
5611
5612     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5613     // Ptr + (Offset & ~15).
5614     if (Offset < 0)
5615       return SDValue();
5616     if ((Offset % RequiredAlign) & 3)
5617       return SDValue();
5618     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5619     if (StartOffset)
5620       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5621                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5622
5623     int EltNo = (Offset - StartOffset) >> 2;
5624     unsigned NumElems = VT.getVectorNumElements();
5625
5626     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5627     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5628                              LD->getPointerInfo().getWithOffset(StartOffset),
5629                              false, false, false, 0);
5630
5631     SmallVector<int, 8> Mask;
5632     for (unsigned i = 0; i != NumElems; ++i)
5633       Mask.push_back(EltNo);
5634
5635     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5636   }
5637
5638   return SDValue();
5639 }
5640
5641 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5642 /// vector of type 'VT', see if the elements can be replaced by a single large
5643 /// load which has the same value as a build_vector whose operands are 'elts'.
5644 ///
5645 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5646 ///
5647 /// FIXME: we'd also like to handle the case where the last elements are zero
5648 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5649 /// There's even a handy isZeroNode for that purpose.
5650 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5651                                         SDLoc &DL, SelectionDAG &DAG,
5652                                         bool isAfterLegalize) {
5653   EVT EltVT = VT.getVectorElementType();
5654   unsigned NumElems = Elts.size();
5655
5656   LoadSDNode *LDBase = nullptr;
5657   unsigned LastLoadedElt = -1U;
5658
5659   // For each element in the initializer, see if we've found a load or an undef.
5660   // If we don't find an initial load element, or later load elements are
5661   // non-consecutive, bail out.
5662   for (unsigned i = 0; i < NumElems; ++i) {
5663     SDValue Elt = Elts[i];
5664
5665     if (!Elt.getNode() ||
5666         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5667       return SDValue();
5668     if (!LDBase) {
5669       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5670         return SDValue();
5671       LDBase = cast<LoadSDNode>(Elt.getNode());
5672       LastLoadedElt = i;
5673       continue;
5674     }
5675     if (Elt.getOpcode() == ISD::UNDEF)
5676       continue;
5677
5678     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5679     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5680       return SDValue();
5681     LastLoadedElt = i;
5682   }
5683
5684   // If we have found an entire vector of loads and undefs, then return a large
5685   // load of the entire vector width starting at the base pointer.  If we found
5686   // consecutive loads for the low half, generate a vzext_load node.
5687   if (LastLoadedElt == NumElems - 1) {
5688
5689     if (isAfterLegalize &&
5690         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5691       return SDValue();
5692
5693     SDValue NewLd = SDValue();
5694
5695     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5696       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5697                           LDBase->getPointerInfo(),
5698                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5699                           LDBase->isInvariant(), 0);
5700     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5701                         LDBase->getPointerInfo(),
5702                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5703                         LDBase->isInvariant(), LDBase->getAlignment());
5704
5705     if (LDBase->hasAnyUseOfValue(1)) {
5706       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5707                                      SDValue(LDBase, 1),
5708                                      SDValue(NewLd.getNode(), 1));
5709       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5710       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5711                              SDValue(NewLd.getNode(), 1));
5712     }
5713
5714     return NewLd;
5715   }
5716   if (NumElems == 4 && LastLoadedElt == 1 &&
5717       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5718     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5719     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5720     SDValue ResNode =
5721         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5722                                 LDBase->getPointerInfo(),
5723                                 LDBase->getAlignment(),
5724                                 false/*isVolatile*/, true/*ReadMem*/,
5725                                 false/*WriteMem*/);
5726
5727     // Make sure the newly-created LOAD is in the same position as LDBase in
5728     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5729     // update uses of LDBase's output chain to use the TokenFactor.
5730     if (LDBase->hasAnyUseOfValue(1)) {
5731       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5732                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5733       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5734       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5735                              SDValue(ResNode.getNode(), 1));
5736     }
5737
5738     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5739   }
5740   return SDValue();
5741 }
5742
5743 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5744 /// to generate a splat value for the following cases:
5745 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5746 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5747 /// a scalar load, or a constant.
5748 /// The VBROADCAST node is returned when a pattern is found,
5749 /// or SDValue() otherwise.
5750 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5751                                     SelectionDAG &DAG) {
5752   if (!Subtarget->hasFp256())
5753     return SDValue();
5754
5755   MVT VT = Op.getSimpleValueType();
5756   SDLoc dl(Op);
5757
5758   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5759          "Unsupported vector type for broadcast.");
5760
5761   SDValue Ld;
5762   bool ConstSplatVal;
5763
5764   switch (Op.getOpcode()) {
5765     default:
5766       // Unknown pattern found.
5767       return SDValue();
5768
5769     case ISD::BUILD_VECTOR: {
5770       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5771       BitVector UndefElements;
5772       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5773
5774       // We need a splat of a single value to use broadcast, and it doesn't
5775       // make any sense if the value is only in one element of the vector.
5776       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5777         return SDValue();
5778
5779       Ld = Splat;
5780       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5781                        Ld.getOpcode() == ISD::ConstantFP);
5782
5783       // Make sure that all of the users of a non-constant load are from the
5784       // BUILD_VECTOR node.
5785       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5786         return SDValue();
5787       break;
5788     }
5789
5790     case ISD::VECTOR_SHUFFLE: {
5791       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5792
5793       // Shuffles must have a splat mask where the first element is
5794       // broadcasted.
5795       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5796         return SDValue();
5797
5798       SDValue Sc = Op.getOperand(0);
5799       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5800           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5801
5802         if (!Subtarget->hasInt256())
5803           return SDValue();
5804
5805         // Use the register form of the broadcast instruction available on AVX2.
5806         if (VT.getSizeInBits() >= 256)
5807           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5808         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5809       }
5810
5811       Ld = Sc.getOperand(0);
5812       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5813                        Ld.getOpcode() == ISD::ConstantFP);
5814
5815       // The scalar_to_vector node and the suspected
5816       // load node must have exactly one user.
5817       // Constants may have multiple users.
5818
5819       // AVX-512 has register version of the broadcast
5820       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5821         Ld.getValueType().getSizeInBits() >= 32;
5822       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5823           !hasRegVer))
5824         return SDValue();
5825       break;
5826     }
5827   }
5828
5829   bool IsGE256 = (VT.getSizeInBits() >= 256);
5830
5831   // Handle the broadcasting a single constant scalar from the constant pool
5832   // into a vector. On Sandybridge it is still better to load a constant vector
5833   // from the constant pool and not to broadcast it from a scalar.
5834   if (ConstSplatVal && Subtarget->hasInt256()) {
5835     EVT CVT = Ld.getValueType();
5836     assert(!CVT.isVector() && "Must not broadcast a vector type");
5837     unsigned ScalarSize = CVT.getSizeInBits();
5838
5839     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5840       const Constant *C = nullptr;
5841       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5842         C = CI->getConstantIntValue();
5843       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5844         C = CF->getConstantFPValue();
5845
5846       assert(C && "Invalid constant type");
5847
5848       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5849       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5850       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5851       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5852                        MachinePointerInfo::getConstantPool(),
5853                        false, false, false, Alignment);
5854
5855       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5856     }
5857   }
5858
5859   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5860   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5861
5862   // Handle AVX2 in-register broadcasts.
5863   if (!IsLoad && Subtarget->hasInt256() &&
5864       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5865     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5866
5867   // The scalar source must be a normal load.
5868   if (!IsLoad)
5869     return SDValue();
5870
5871   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5872     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5873
5874   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5875   // double since there is no vbroadcastsd xmm
5876   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5877     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5878       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5879   }
5880
5881   // Unsupported broadcast.
5882   return SDValue();
5883 }
5884
5885 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5886 /// underlying vector and index.
5887 ///
5888 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5889 /// index.
5890 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5891                                          SDValue ExtIdx) {
5892   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5893   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5894     return Idx;
5895
5896   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5897   // lowered this:
5898   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5899   // to:
5900   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5901   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5902   //                           undef)
5903   //                       Constant<0>)
5904   // In this case the vector is the extract_subvector expression and the index
5905   // is 2, as specified by the shuffle.
5906   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5907   SDValue ShuffleVec = SVOp->getOperand(0);
5908   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5909   assert(ShuffleVecVT.getVectorElementType() ==
5910          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5911
5912   int ShuffleIdx = SVOp->getMaskElt(Idx);
5913   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5914     ExtractedFromVec = ShuffleVec;
5915     return ShuffleIdx;
5916   }
5917   return Idx;
5918 }
5919
5920 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5921   MVT VT = Op.getSimpleValueType();
5922
5923   // Skip if insert_vec_elt is not supported.
5924   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5925   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5926     return SDValue();
5927
5928   SDLoc DL(Op);
5929   unsigned NumElems = Op.getNumOperands();
5930
5931   SDValue VecIn1;
5932   SDValue VecIn2;
5933   SmallVector<unsigned, 4> InsertIndices;
5934   SmallVector<int, 8> Mask(NumElems, -1);
5935
5936   for (unsigned i = 0; i != NumElems; ++i) {
5937     unsigned Opc = Op.getOperand(i).getOpcode();
5938
5939     if (Opc == ISD::UNDEF)
5940       continue;
5941
5942     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5943       // Quit if more than 1 elements need inserting.
5944       if (InsertIndices.size() > 1)
5945         return SDValue();
5946
5947       InsertIndices.push_back(i);
5948       continue;
5949     }
5950
5951     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5952     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5953     // Quit if non-constant index.
5954     if (!isa<ConstantSDNode>(ExtIdx))
5955       return SDValue();
5956     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5957
5958     // Quit if extracted from vector of different type.
5959     if (ExtractedFromVec.getValueType() != VT)
5960       return SDValue();
5961
5962     if (!VecIn1.getNode())
5963       VecIn1 = ExtractedFromVec;
5964     else if (VecIn1 != ExtractedFromVec) {
5965       if (!VecIn2.getNode())
5966         VecIn2 = ExtractedFromVec;
5967       else if (VecIn2 != ExtractedFromVec)
5968         // Quit if more than 2 vectors to shuffle
5969         return SDValue();
5970     }
5971
5972     if (ExtractedFromVec == VecIn1)
5973       Mask[i] = Idx;
5974     else if (ExtractedFromVec == VecIn2)
5975       Mask[i] = Idx + NumElems;
5976   }
5977
5978   if (!VecIn1.getNode())
5979     return SDValue();
5980
5981   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5982   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5983   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5984     unsigned Idx = InsertIndices[i];
5985     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5986                      DAG.getIntPtrConstant(Idx));
5987   }
5988
5989   return NV;
5990 }
5991
5992 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5993 SDValue
5994 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5995
5996   MVT VT = Op.getSimpleValueType();
5997   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5998          "Unexpected type in LowerBUILD_VECTORvXi1!");
5999
6000   SDLoc dl(Op);
6001   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6002     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6003     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6004     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6005   }
6006
6007   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6008     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6009     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6010     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6011   }
6012
6013   bool AllContants = true;
6014   uint64_t Immediate = 0;
6015   int NonConstIdx = -1;
6016   bool IsSplat = true;
6017   unsigned NumNonConsts = 0;
6018   unsigned NumConsts = 0;
6019   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6020     SDValue In = Op.getOperand(idx);
6021     if (In.getOpcode() == ISD::UNDEF)
6022       continue;
6023     if (!isa<ConstantSDNode>(In)) {
6024       AllContants = false;
6025       NonConstIdx = idx;
6026       NumNonConsts++;
6027     }
6028     else {
6029       NumConsts++;
6030       if (cast<ConstantSDNode>(In)->getZExtValue())
6031       Immediate |= (1ULL << idx);
6032     }
6033     if (In != Op.getOperand(0))
6034       IsSplat = false;
6035   }
6036
6037   if (AllContants) {
6038     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6039       DAG.getConstant(Immediate, MVT::i16));
6040     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6041                        DAG.getIntPtrConstant(0));
6042   }
6043
6044   if (NumNonConsts == 1 && NonConstIdx != 0) {
6045     SDValue DstVec;
6046     if (NumConsts) {
6047       SDValue VecAsImm = DAG.getConstant(Immediate,
6048                                          MVT::getIntegerVT(VT.getSizeInBits()));
6049       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6050     }
6051     else 
6052       DstVec = DAG.getUNDEF(VT);
6053     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6054                        Op.getOperand(NonConstIdx),
6055                        DAG.getIntPtrConstant(NonConstIdx));
6056   }
6057   if (!IsSplat && (NonConstIdx != 0))
6058     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6059   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6060   SDValue Select;
6061   if (IsSplat)
6062     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6063                           DAG.getConstant(-1, SelectVT),
6064                           DAG.getConstant(0, SelectVT));
6065   else
6066     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6067                          DAG.getConstant((Immediate | 1), SelectVT),
6068                          DAG.getConstant(Immediate, SelectVT));
6069   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6070 }
6071
6072 /// \brief Return true if \p N implements a horizontal binop and return the
6073 /// operands for the horizontal binop into V0 and V1.
6074 /// 
6075 /// This is a helper function of PerformBUILD_VECTORCombine.
6076 /// This function checks that the build_vector \p N in input implements a
6077 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6078 /// operation to match.
6079 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6080 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6081 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6082 /// arithmetic sub.
6083 ///
6084 /// This function only analyzes elements of \p N whose indices are
6085 /// in range [BaseIdx, LastIdx).
6086 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6087                               SelectionDAG &DAG,
6088                               unsigned BaseIdx, unsigned LastIdx,
6089                               SDValue &V0, SDValue &V1) {
6090   EVT VT = N->getValueType(0);
6091
6092   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6093   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6094          "Invalid Vector in input!");
6095   
6096   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6097   bool CanFold = true;
6098   unsigned ExpectedVExtractIdx = BaseIdx;
6099   unsigned NumElts = LastIdx - BaseIdx;
6100   V0 = DAG.getUNDEF(VT);
6101   V1 = DAG.getUNDEF(VT);
6102
6103   // Check if N implements a horizontal binop.
6104   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6105     SDValue Op = N->getOperand(i + BaseIdx);
6106
6107     // Skip UNDEFs.
6108     if (Op->getOpcode() == ISD::UNDEF) {
6109       // Update the expected vector extract index.
6110       if (i * 2 == NumElts)
6111         ExpectedVExtractIdx = BaseIdx;
6112       ExpectedVExtractIdx += 2;
6113       continue;
6114     }
6115
6116     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6117
6118     if (!CanFold)
6119       break;
6120
6121     SDValue Op0 = Op.getOperand(0);
6122     SDValue Op1 = Op.getOperand(1);
6123
6124     // Try to match the following pattern:
6125     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6126     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6127         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6128         Op0.getOperand(0) == Op1.getOperand(0) &&
6129         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6130         isa<ConstantSDNode>(Op1.getOperand(1)));
6131     if (!CanFold)
6132       break;
6133
6134     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6135     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6136
6137     if (i * 2 < NumElts) {
6138       if (V0.getOpcode() == ISD::UNDEF)
6139         V0 = Op0.getOperand(0);
6140     } else {
6141       if (V1.getOpcode() == ISD::UNDEF)
6142         V1 = Op0.getOperand(0);
6143       if (i * 2 == NumElts)
6144         ExpectedVExtractIdx = BaseIdx;
6145     }
6146
6147     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6148     if (I0 == ExpectedVExtractIdx)
6149       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6150     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6151       // Try to match the following dag sequence:
6152       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6153       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6154     } else
6155       CanFold = false;
6156
6157     ExpectedVExtractIdx += 2;
6158   }
6159
6160   return CanFold;
6161 }
6162
6163 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6164 /// a concat_vector. 
6165 ///
6166 /// This is a helper function of PerformBUILD_VECTORCombine.
6167 /// This function expects two 256-bit vectors called V0 and V1.
6168 /// At first, each vector is split into two separate 128-bit vectors.
6169 /// Then, the resulting 128-bit vectors are used to implement two
6170 /// horizontal binary operations. 
6171 ///
6172 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6173 ///
6174 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6175 /// the two new horizontal binop.
6176 /// When Mode is set, the first horizontal binop dag node would take as input
6177 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6178 /// horizontal binop dag node would take as input the lower 128-bit of V1
6179 /// and the upper 128-bit of V1.
6180 ///   Example:
6181 ///     HADD V0_LO, V0_HI
6182 ///     HADD V1_LO, V1_HI
6183 ///
6184 /// Otherwise, the first horizontal binop dag node takes as input the lower
6185 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6186 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6187 ///   Example:
6188 ///     HADD V0_LO, V1_LO
6189 ///     HADD V0_HI, V1_HI
6190 ///
6191 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6192 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6193 /// the upper 128-bits of the result.
6194 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6195                                      SDLoc DL, SelectionDAG &DAG,
6196                                      unsigned X86Opcode, bool Mode,
6197                                      bool isUndefLO, bool isUndefHI) {
6198   EVT VT = V0.getValueType();
6199   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6200          "Invalid nodes in input!");
6201
6202   unsigned NumElts = VT.getVectorNumElements();
6203   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6204   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6205   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6206   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6207   EVT NewVT = V0_LO.getValueType();
6208
6209   SDValue LO = DAG.getUNDEF(NewVT);
6210   SDValue HI = DAG.getUNDEF(NewVT);
6211
6212   if (Mode) {
6213     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6214     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6215       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6216     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6217       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6218   } else {
6219     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6220     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6221                        V1_LO->getOpcode() != ISD::UNDEF))
6222       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6223
6224     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6225                        V1_HI->getOpcode() != ISD::UNDEF))
6226       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6227   }
6228
6229   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6230 }
6231
6232 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6233 /// sequence of 'vadd + vsub + blendi'.
6234 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6235                            const X86Subtarget *Subtarget) {
6236   SDLoc DL(BV);
6237   EVT VT = BV->getValueType(0);
6238   unsigned NumElts = VT.getVectorNumElements();
6239   SDValue InVec0 = DAG.getUNDEF(VT);
6240   SDValue InVec1 = DAG.getUNDEF(VT);
6241
6242   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6243           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6244
6245   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6246   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6247   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6248     return SDValue();
6249
6250   // Odd-numbered elements in the input build vector are obtained from
6251   // adding two integer/float elements.
6252   // Even-numbered elements in the input build vector are obtained from
6253   // subtracting two integer/float elements.
6254   unsigned ExpectedOpcode = ISD::FSUB;
6255   unsigned NextExpectedOpcode = ISD::FADD;
6256   bool AddFound = false;
6257   bool SubFound = false;
6258
6259   for (unsigned i = 0, e = NumElts; i != e; i++) {
6260     SDValue Op = BV->getOperand(i);
6261       
6262     // Skip 'undef' values.
6263     unsigned Opcode = Op.getOpcode();
6264     if (Opcode == ISD::UNDEF) {
6265       std::swap(ExpectedOpcode, NextExpectedOpcode);
6266       continue;
6267     }
6268       
6269     // Early exit if we found an unexpected opcode.
6270     if (Opcode != ExpectedOpcode)
6271       return SDValue();
6272
6273     SDValue Op0 = Op.getOperand(0);
6274     SDValue Op1 = Op.getOperand(1);
6275
6276     // Try to match the following pattern:
6277     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6278     // Early exit if we cannot match that sequence.
6279     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6280         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6281         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6282         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6283         Op0.getOperand(1) != Op1.getOperand(1))
6284       return SDValue();
6285
6286     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6287     if (I0 != i)
6288       return SDValue();
6289
6290     // We found a valid add/sub node. Update the information accordingly.
6291     if (i & 1)
6292       AddFound = true;
6293     else
6294       SubFound = true;
6295
6296     // Update InVec0 and InVec1.
6297     if (InVec0.getOpcode() == ISD::UNDEF)
6298       InVec0 = Op0.getOperand(0);
6299     if (InVec1.getOpcode() == ISD::UNDEF)
6300       InVec1 = Op1.getOperand(0);
6301
6302     // Make sure that operands in input to each add/sub node always
6303     // come from a same pair of vectors.
6304     if (InVec0 != Op0.getOperand(0)) {
6305       if (ExpectedOpcode == ISD::FSUB)
6306         return SDValue();
6307
6308       // FADD is commutable. Try to commute the operands
6309       // and then test again.
6310       std::swap(Op0, Op1);
6311       if (InVec0 != Op0.getOperand(0))
6312         return SDValue();
6313     }
6314
6315     if (InVec1 != Op1.getOperand(0))
6316       return SDValue();
6317
6318     // Update the pair of expected opcodes.
6319     std::swap(ExpectedOpcode, NextExpectedOpcode);
6320   }
6321
6322   // Don't try to fold this build_vector into a VSELECT if it has
6323   // too many UNDEF operands.
6324   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6325       InVec1.getOpcode() != ISD::UNDEF) {
6326     // Emit a sequence of vector add and sub followed by a VSELECT.
6327     // The new VSELECT will be lowered into a BLENDI.
6328     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6329     // and emit a single ADDSUB instruction.
6330     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6331     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6332
6333     // Construct the VSELECT mask.
6334     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6335     EVT SVT = MaskVT.getVectorElementType();
6336     unsigned SVTBits = SVT.getSizeInBits();
6337     SmallVector<SDValue, 8> Ops;
6338
6339     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6340       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6341                             APInt::getAllOnesValue(SVTBits);
6342       SDValue Constant = DAG.getConstant(Value, SVT);
6343       Ops.push_back(Constant);
6344     }
6345
6346     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6347     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6348   }
6349   
6350   return SDValue();
6351 }
6352
6353 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6354                                           const X86Subtarget *Subtarget) {
6355   SDLoc DL(N);
6356   EVT VT = N->getValueType(0);
6357   unsigned NumElts = VT.getVectorNumElements();
6358   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6359   SDValue InVec0, InVec1;
6360
6361   // Try to match an ADDSUB.
6362   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6363       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6364     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6365     if (Value.getNode())
6366       return Value;
6367   }
6368
6369   // Try to match horizontal ADD/SUB.
6370   unsigned NumUndefsLO = 0;
6371   unsigned NumUndefsHI = 0;
6372   unsigned Half = NumElts/2;
6373
6374   // Count the number of UNDEF operands in the build_vector in input.
6375   for (unsigned i = 0, e = Half; i != e; ++i)
6376     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6377       NumUndefsLO++;
6378
6379   for (unsigned i = Half, e = NumElts; i != e; ++i)
6380     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6381       NumUndefsHI++;
6382
6383   // Early exit if this is either a build_vector of all UNDEFs or all the
6384   // operands but one are UNDEF.
6385   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6386     return SDValue();
6387
6388   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6389     // Try to match an SSE3 float HADD/HSUB.
6390     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6391       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6392     
6393     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6394       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6395   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6396     // Try to match an SSSE3 integer HADD/HSUB.
6397     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6398       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6399     
6400     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6401       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6402   }
6403   
6404   if (!Subtarget->hasAVX())
6405     return SDValue();
6406
6407   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6408     // Try to match an AVX horizontal add/sub of packed single/double
6409     // precision floating point values from 256-bit vectors.
6410     SDValue InVec2, InVec3;
6411     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6412         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6413         ((InVec0.getOpcode() == ISD::UNDEF ||
6414           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6415         ((InVec1.getOpcode() == ISD::UNDEF ||
6416           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6417       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6418
6419     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6420         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6421         ((InVec0.getOpcode() == ISD::UNDEF ||
6422           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6423         ((InVec1.getOpcode() == ISD::UNDEF ||
6424           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6425       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6426   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6427     // Try to match an AVX2 horizontal add/sub of signed integers.
6428     SDValue InVec2, InVec3;
6429     unsigned X86Opcode;
6430     bool CanFold = true;
6431
6432     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6433         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6434         ((InVec0.getOpcode() == ISD::UNDEF ||
6435           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6436         ((InVec1.getOpcode() == ISD::UNDEF ||
6437           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6438       X86Opcode = X86ISD::HADD;
6439     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6440         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6441         ((InVec0.getOpcode() == ISD::UNDEF ||
6442           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6443         ((InVec1.getOpcode() == ISD::UNDEF ||
6444           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6445       X86Opcode = X86ISD::HSUB;
6446     else
6447       CanFold = false;
6448
6449     if (CanFold) {
6450       // Fold this build_vector into a single horizontal add/sub.
6451       // Do this only if the target has AVX2.
6452       if (Subtarget->hasAVX2())
6453         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6454  
6455       // Do not try to expand this build_vector into a pair of horizontal
6456       // add/sub if we can emit a pair of scalar add/sub.
6457       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6458         return SDValue();
6459
6460       // Convert this build_vector into a pair of horizontal binop followed by
6461       // a concat vector.
6462       bool isUndefLO = NumUndefsLO == Half;
6463       bool isUndefHI = NumUndefsHI == Half;
6464       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6465                                    isUndefLO, isUndefHI);
6466     }
6467   }
6468
6469   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6470        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6471     unsigned X86Opcode;
6472     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6473       X86Opcode = X86ISD::HADD;
6474     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6475       X86Opcode = X86ISD::HSUB;
6476     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6477       X86Opcode = X86ISD::FHADD;
6478     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6479       X86Opcode = X86ISD::FHSUB;
6480     else
6481       return SDValue();
6482
6483     // Don't try to expand this build_vector into a pair of horizontal add/sub
6484     // if we can simply emit a pair of scalar add/sub.
6485     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6486       return SDValue();
6487
6488     // Convert this build_vector into two horizontal add/sub followed by
6489     // a concat vector.
6490     bool isUndefLO = NumUndefsLO == Half;
6491     bool isUndefHI = NumUndefsHI == Half;
6492     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6493                                  isUndefLO, isUndefHI);
6494   }
6495
6496   return SDValue();
6497 }
6498
6499 SDValue
6500 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6501   SDLoc dl(Op);
6502
6503   MVT VT = Op.getSimpleValueType();
6504   MVT ExtVT = VT.getVectorElementType();
6505   unsigned NumElems = Op.getNumOperands();
6506
6507   // Generate vectors for predicate vectors.
6508   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6509     return LowerBUILD_VECTORvXi1(Op, DAG);
6510
6511   // Vectors containing all zeros can be matched by pxor and xorps later
6512   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6513     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6514     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6515     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6516       return Op;
6517
6518     return getZeroVector(VT, Subtarget, DAG, dl);
6519   }
6520
6521   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6522   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6523   // vpcmpeqd on 256-bit vectors.
6524   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6525     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6526       return Op;
6527
6528     if (!VT.is512BitVector())
6529       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6530   }
6531
6532   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6533   if (Broadcast.getNode())
6534     return Broadcast;
6535
6536   unsigned EVTBits = ExtVT.getSizeInBits();
6537
6538   unsigned NumZero  = 0;
6539   unsigned NumNonZero = 0;
6540   unsigned NonZeros = 0;
6541   bool IsAllConstants = true;
6542   SmallSet<SDValue, 8> Values;
6543   for (unsigned i = 0; i < NumElems; ++i) {
6544     SDValue Elt = Op.getOperand(i);
6545     if (Elt.getOpcode() == ISD::UNDEF)
6546       continue;
6547     Values.insert(Elt);
6548     if (Elt.getOpcode() != ISD::Constant &&
6549         Elt.getOpcode() != ISD::ConstantFP)
6550       IsAllConstants = false;
6551     if (X86::isZeroNode(Elt))
6552       NumZero++;
6553     else {
6554       NonZeros |= (1 << i);
6555       NumNonZero++;
6556     }
6557   }
6558
6559   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6560   if (NumNonZero == 0)
6561     return DAG.getUNDEF(VT);
6562
6563   // Special case for single non-zero, non-undef, element.
6564   if (NumNonZero == 1) {
6565     unsigned Idx = countTrailingZeros(NonZeros);
6566     SDValue Item = Op.getOperand(Idx);
6567
6568     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6569     // the value are obviously zero, truncate the value to i32 and do the
6570     // insertion that way.  Only do this if the value is non-constant or if the
6571     // value is a constant being inserted into element 0.  It is cheaper to do
6572     // a constant pool load than it is to do a movd + shuffle.
6573     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6574         (!IsAllConstants || Idx == 0)) {
6575       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6576         // Handle SSE only.
6577         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6578         EVT VecVT = MVT::v4i32;
6579         unsigned VecElts = 4;
6580
6581         // Truncate the value (which may itself be a constant) to i32, and
6582         // convert it to a vector with movd (S2V+shuffle to zero extend).
6583         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6584         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6585         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6586
6587         // Now we have our 32-bit value zero extended in the low element of
6588         // a vector.  If Idx != 0, swizzle it into place.
6589         if (Idx != 0) {
6590           SmallVector<int, 4> Mask;
6591           Mask.push_back(Idx);
6592           for (unsigned i = 1; i != VecElts; ++i)
6593             Mask.push_back(i);
6594           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6595                                       &Mask[0]);
6596         }
6597         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6598       }
6599     }
6600
6601     // If we have a constant or non-constant insertion into the low element of
6602     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6603     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6604     // depending on what the source datatype is.
6605     if (Idx == 0) {
6606       if (NumZero == 0)
6607         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6608
6609       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6610           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6611         if (VT.is256BitVector() || VT.is512BitVector()) {
6612           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6613           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6614                              Item, DAG.getIntPtrConstant(0));
6615         }
6616         assert(VT.is128BitVector() && "Expected an SSE value type!");
6617         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6618         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6619         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6620       }
6621
6622       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6623         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6624         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6625         if (VT.is256BitVector()) {
6626           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6627           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6628         } else {
6629           assert(VT.is128BitVector() && "Expected an SSE value type!");
6630           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6631         }
6632         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6633       }
6634     }
6635
6636     // Is it a vector logical left shift?
6637     if (NumElems == 2 && Idx == 1 &&
6638         X86::isZeroNode(Op.getOperand(0)) &&
6639         !X86::isZeroNode(Op.getOperand(1))) {
6640       unsigned NumBits = VT.getSizeInBits();
6641       return getVShift(true, VT,
6642                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6643                                    VT, Op.getOperand(1)),
6644                        NumBits/2, DAG, *this, dl);
6645     }
6646
6647     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6648       return SDValue();
6649
6650     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6651     // is a non-constant being inserted into an element other than the low one,
6652     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6653     // movd/movss) to move this into the low element, then shuffle it into
6654     // place.
6655     if (EVTBits == 32) {
6656       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6657
6658       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6659       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6660       SmallVector<int, 8> MaskVec;
6661       for (unsigned i = 0; i != NumElems; ++i)
6662         MaskVec.push_back(i == Idx ? 0 : 1);
6663       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6664     }
6665   }
6666
6667   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6668   if (Values.size() == 1) {
6669     if (EVTBits == 32) {
6670       // Instead of a shuffle like this:
6671       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6672       // Check if it's possible to issue this instead.
6673       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6674       unsigned Idx = countTrailingZeros(NonZeros);
6675       SDValue Item = Op.getOperand(Idx);
6676       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6677         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6678     }
6679     return SDValue();
6680   }
6681
6682   // A vector full of immediates; various special cases are already
6683   // handled, so this is best done with a single constant-pool load.
6684   if (IsAllConstants)
6685     return SDValue();
6686
6687   // For AVX-length vectors, build the individual 128-bit pieces and use
6688   // shuffles to put them in place.
6689   if (VT.is256BitVector() || VT.is512BitVector()) {
6690     SmallVector<SDValue, 64> V;
6691     for (unsigned i = 0; i != NumElems; ++i)
6692       V.push_back(Op.getOperand(i));
6693
6694     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6695
6696     // Build both the lower and upper subvector.
6697     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6698                                 makeArrayRef(&V[0], NumElems/2));
6699     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6700                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6701
6702     // Recreate the wider vector with the lower and upper part.
6703     if (VT.is256BitVector())
6704       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6705     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6706   }
6707
6708   // Let legalizer expand 2-wide build_vectors.
6709   if (EVTBits == 64) {
6710     if (NumNonZero == 1) {
6711       // One half is zero or undef.
6712       unsigned Idx = countTrailingZeros(NonZeros);
6713       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6714                                  Op.getOperand(Idx));
6715       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6716     }
6717     return SDValue();
6718   }
6719
6720   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6721   if (EVTBits == 8 && NumElems == 16) {
6722     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6723                                         Subtarget, *this);
6724     if (V.getNode()) return V;
6725   }
6726
6727   if (EVTBits == 16 && NumElems == 8) {
6728     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6729                                       Subtarget, *this);
6730     if (V.getNode()) return V;
6731   }
6732
6733   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6734   if (EVTBits == 32 && NumElems == 4) {
6735     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6736                                       NumZero, DAG, Subtarget, *this);
6737     if (V.getNode())
6738       return V;
6739   }
6740
6741   // If element VT is == 32 bits, turn it into a number of shuffles.
6742   SmallVector<SDValue, 8> V(NumElems);
6743   if (NumElems == 4 && NumZero > 0) {
6744     for (unsigned i = 0; i < 4; ++i) {
6745       bool isZero = !(NonZeros & (1 << i));
6746       if (isZero)
6747         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6748       else
6749         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6750     }
6751
6752     for (unsigned i = 0; i < 2; ++i) {
6753       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6754         default: break;
6755         case 0:
6756           V[i] = V[i*2];  // Must be a zero vector.
6757           break;
6758         case 1:
6759           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6760           break;
6761         case 2:
6762           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6763           break;
6764         case 3:
6765           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6766           break;
6767       }
6768     }
6769
6770     bool Reverse1 = (NonZeros & 0x3) == 2;
6771     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6772     int MaskVec[] = {
6773       Reverse1 ? 1 : 0,
6774       Reverse1 ? 0 : 1,
6775       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6776       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6777     };
6778     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6779   }
6780
6781   if (Values.size() > 1 && VT.is128BitVector()) {
6782     // Check for a build vector of consecutive loads.
6783     for (unsigned i = 0; i < NumElems; ++i)
6784       V[i] = Op.getOperand(i);
6785
6786     // Check for elements which are consecutive loads.
6787     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6788     if (LD.getNode())
6789       return LD;
6790
6791     // Check for a build vector from mostly shuffle plus few inserting.
6792     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6793     if (Sh.getNode())
6794       return Sh;
6795
6796     // For SSE 4.1, use insertps to put the high elements into the low element.
6797     if (getSubtarget()->hasSSE41()) {
6798       SDValue Result;
6799       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6800         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6801       else
6802         Result = DAG.getUNDEF(VT);
6803
6804       for (unsigned i = 1; i < NumElems; ++i) {
6805         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6806         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6807                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6808       }
6809       return Result;
6810     }
6811
6812     // Otherwise, expand into a number of unpckl*, start by extending each of
6813     // our (non-undef) elements to the full vector width with the element in the
6814     // bottom slot of the vector (which generates no code for SSE).
6815     for (unsigned i = 0; i < NumElems; ++i) {
6816       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6817         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6818       else
6819         V[i] = DAG.getUNDEF(VT);
6820     }
6821
6822     // Next, we iteratively mix elements, e.g. for v4f32:
6823     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6824     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6825     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6826     unsigned EltStride = NumElems >> 1;
6827     while (EltStride != 0) {
6828       for (unsigned i = 0; i < EltStride; ++i) {
6829         // If V[i+EltStride] is undef and this is the first round of mixing,
6830         // then it is safe to just drop this shuffle: V[i] is already in the
6831         // right place, the one element (since it's the first round) being
6832         // inserted as undef can be dropped.  This isn't safe for successive
6833         // rounds because they will permute elements within both vectors.
6834         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6835             EltStride == NumElems/2)
6836           continue;
6837
6838         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6839       }
6840       EltStride >>= 1;
6841     }
6842     return V[0];
6843   }
6844   return SDValue();
6845 }
6846
6847 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6848 // to create 256-bit vectors from two other 128-bit ones.
6849 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6850   SDLoc dl(Op);
6851   MVT ResVT = Op.getSimpleValueType();
6852
6853   assert((ResVT.is256BitVector() ||
6854           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6855
6856   SDValue V1 = Op.getOperand(0);
6857   SDValue V2 = Op.getOperand(1);
6858   unsigned NumElems = ResVT.getVectorNumElements();
6859   if(ResVT.is256BitVector())
6860     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6861
6862   if (Op.getNumOperands() == 4) {
6863     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6864                                 ResVT.getVectorNumElements()/2);
6865     SDValue V3 = Op.getOperand(2);
6866     SDValue V4 = Op.getOperand(3);
6867     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6868       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6869   }
6870   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6871 }
6872
6873 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6874   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6875   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6876          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6877           Op.getNumOperands() == 4)));
6878
6879   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6880   // from two other 128-bit ones.
6881
6882   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6883   return LowerAVXCONCAT_VECTORS(Op, DAG);
6884 }
6885
6886
6887 //===----------------------------------------------------------------------===//
6888 // Vector shuffle lowering
6889 //
6890 // This is an experimental code path for lowering vector shuffles on x86. It is
6891 // designed to handle arbitrary vector shuffles and blends, gracefully
6892 // degrading performance as necessary. It works hard to recognize idiomatic
6893 // shuffles and lower them to optimal instruction patterns without leaving
6894 // a framework that allows reasonably efficient handling of all vector shuffle
6895 // patterns.
6896 //===----------------------------------------------------------------------===//
6897
6898 /// \brief Tiny helper function to identify a no-op mask.
6899 ///
6900 /// This is a somewhat boring predicate function. It checks whether the mask
6901 /// array input, which is assumed to be a single-input shuffle mask of the kind
6902 /// used by the X86 shuffle instructions (not a fully general
6903 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6904 /// in-place shuffle are 'no-op's.
6905 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6906   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6907     if (Mask[i] != -1 && Mask[i] != i)
6908       return false;
6909   return true;
6910 }
6911
6912 /// \brief Helper function to classify a mask as a single-input mask.
6913 ///
6914 /// This isn't a generic single-input test because in the vector shuffle
6915 /// lowering we canonicalize single inputs to be the first input operand. This
6916 /// means we can more quickly test for a single input by only checking whether
6917 /// an input from the second operand exists. We also assume that the size of
6918 /// mask corresponds to the size of the input vectors which isn't true in the
6919 /// fully general case.
6920 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6921   for (int M : Mask)
6922     if (M >= (int)Mask.size())
6923       return false;
6924   return true;
6925 }
6926
6927 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6928 ///
6929 /// This helper function produces an 8-bit shuffle immediate corresponding to
6930 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6931 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6932 /// example.
6933 ///
6934 /// NB: We rely heavily on "undef" masks preserving the input lane.
6935 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6936                                           SelectionDAG &DAG) {
6937   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6938   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6939   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6940   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6941   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6942
6943   unsigned Imm = 0;
6944   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6945   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6946   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6947   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6948   return DAG.getConstant(Imm, MVT::i8);
6949 }
6950
6951 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6952 ///
6953 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6954 /// support for floating point shuffles but not integer shuffles. These
6955 /// instructions will incur a domain crossing penalty on some chips though so
6956 /// it is better to avoid lowering through this for integer vectors where
6957 /// possible.
6958 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6959                                        const X86Subtarget *Subtarget,
6960                                        SelectionDAG &DAG) {
6961   SDLoc DL(Op);
6962   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6963   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6964   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6965   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6966   ArrayRef<int> Mask = SVOp->getMask();
6967   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6968
6969   if (isSingleInputShuffleMask(Mask)) {
6970     // Straight shuffle of a single input vector. Simulate this by using the
6971     // single input as both of the "inputs" to this instruction..
6972     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6973     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6974                        DAG.getConstant(SHUFPDMask, MVT::i8));
6975   }
6976   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6977   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6978
6979   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6980   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6981                      DAG.getConstant(SHUFPDMask, MVT::i8));
6982 }
6983
6984 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6985 ///
6986 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6987 /// the integer unit to minimize domain crossing penalties. However, for blends
6988 /// it falls back to the floating point shuffle operation with appropriate bit
6989 /// casting.
6990 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6991                                        const X86Subtarget *Subtarget,
6992                                        SelectionDAG &DAG) {
6993   SDLoc DL(Op);
6994   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
6995   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6996   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6997   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6998   ArrayRef<int> Mask = SVOp->getMask();
6999   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7000
7001   if (isSingleInputShuffleMask(Mask)) {
7002     // Straight shuffle of a single input vector. For everything from SSE2
7003     // onward this has a single fast instruction with no scary immediates.
7004     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7005     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7006     int WidenedMask[4] = {
7007         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7008         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7009     return DAG.getNode(
7010         ISD::BITCAST, DL, MVT::v2i64,
7011         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7012                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7013   }
7014
7015   // We implement this with SHUFPD which is pretty lame because it will likely
7016   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7017   // However, all the alternatives are still more cycles and newer chips don't
7018   // have this problem. It would be really nice if x86 had better shuffles here.
7019   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7020   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7021   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7022                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7023 }
7024
7025 /// \brief Lower 4-lane 32-bit floating point shuffles.
7026 ///
7027 /// Uses instructions exclusively from the floating point unit to minimize
7028 /// domain crossing penalties, as these are sufficient to implement all v4f32
7029 /// shuffles.
7030 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7031                                        const X86Subtarget *Subtarget,
7032                                        SelectionDAG &DAG) {
7033   SDLoc DL(Op);
7034   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7035   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7036   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7037   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7038   ArrayRef<int> Mask = SVOp->getMask();
7039   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7040
7041   SDValue LowV = V1, HighV = V2;
7042   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7043
7044   int NumV2Elements =
7045       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7046
7047   if (NumV2Elements == 0)
7048     // Straight shuffle of a single input vector. We pass the input vector to
7049     // both operands to simulate this with a SHUFPS.
7050     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7051                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7052
7053   if (NumV2Elements == 1) {
7054     int V2Index =
7055         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7056         Mask.begin();
7057     // Compute the index adjacent to V2Index and in the same half by toggling
7058     // the low bit.
7059     int V2AdjIndex = V2Index ^ 1;
7060
7061     if (Mask[V2AdjIndex] == -1) {
7062       // Handles all the cases where we have a single V2 element and an undef.
7063       // This will only ever happen in the high lanes because we commute the
7064       // vector otherwise.
7065       if (V2Index < 2)
7066         std::swap(LowV, HighV);
7067       NewMask[V2Index] -= 4;
7068     } else {
7069       // Handle the case where the V2 element ends up adjacent to a V1 element.
7070       // To make this work, blend them together as the first step.
7071       int V1Index = V2AdjIndex;
7072       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7073       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7074                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7075
7076       // Now proceed to reconstruct the final blend as we have the necessary
7077       // high or low half formed.
7078       if (V2Index < 2) {
7079         LowV = V2;
7080         HighV = V1;
7081       } else {
7082         HighV = V2;
7083       }
7084       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7085       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7086     }
7087   } else if (NumV2Elements == 2) {
7088     if (Mask[0] < 4 && Mask[1] < 4) {
7089       // Handle the easy case where we have V1 in the low lanes and V2 in the
7090       // high lanes. We never see this reversed because we sort the shuffle.
7091       NewMask[2] -= 4;
7092       NewMask[3] -= 4;
7093     } else {
7094       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7095       // trying to place elements directly, just blend them and set up the final
7096       // shuffle to place them.
7097
7098       // The first two blend mask elements are for V1, the second two are for
7099       // V2.
7100       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7101                           Mask[2] < 4 ? Mask[2] : Mask[3],
7102                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7103                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7104       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7105                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7106
7107       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7108       // a blend.
7109       LowV = HighV = V1;
7110       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7111       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7112       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7113       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7114     }
7115   }
7116   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7117                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7118 }
7119
7120 /// \brief Lower 4-lane i32 vector shuffles.
7121 ///
7122 /// We try to handle these with integer-domain shuffles where we can, but for
7123 /// blends we use the floating point domain blend instructions.
7124 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7125                                        const X86Subtarget *Subtarget,
7126                                        SelectionDAG &DAG) {
7127   SDLoc DL(Op);
7128   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7129   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7130   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7131   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7132   ArrayRef<int> Mask = SVOp->getMask();
7133   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7134
7135   if (isSingleInputShuffleMask(Mask))
7136     // Straight shuffle of a single input vector. For everything from SSE2
7137     // onward this has a single fast instruction with no scary immediates.
7138     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7139                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7140
7141   // We implement this with SHUFPS because it can blend from two vectors.
7142   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7143   // up the inputs, bypassing domain shift penalties that we would encur if we
7144   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7145   // relevant.
7146   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7147                      DAG.getVectorShuffle(
7148                          MVT::v4f32, DL,
7149                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7150                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7151 }
7152
7153 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7154 /// shuffle lowering, and the most complex part.
7155 ///
7156 /// The lowering strategy is to try to form pairs of input lanes which are
7157 /// targeted at the same half of the final vector, and then use a dword shuffle
7158 /// to place them onto the right half, and finally unpack the paired lanes into
7159 /// their final position.
7160 ///
7161 /// The exact breakdown of how to form these dword pairs and align them on the
7162 /// correct sides is really tricky. See the comments within the function for
7163 /// more of the details.
7164 static SDValue lowerV8I16SingleInputVectorShuffle(
7165     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7166     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7167   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7168   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7169   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7170
7171   SmallVector<int, 4> LoInputs;
7172   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7173                [](int M) { return M >= 0; });
7174   std::sort(LoInputs.begin(), LoInputs.end());
7175   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7176   SmallVector<int, 4> HiInputs;
7177   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7178                [](int M) { return M >= 0; });
7179   std::sort(HiInputs.begin(), HiInputs.end());
7180   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7181   int NumLToL =
7182       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7183   int NumHToL = LoInputs.size() - NumLToL;
7184   int NumLToH =
7185       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7186   int NumHToH = HiInputs.size() - NumLToH;
7187   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7188   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7189   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7190   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7191
7192   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7193   // such inputs we can swap two of the dwords across the half mark and end up
7194   // with <=2 inputs to each half in each half. Once there, we can fall through
7195   // to the generic code below. For example:
7196   //
7197   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7198   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7199   //
7200   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7201   // and 2-2.
7202   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7203                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7204     // Compute the index of dword with only one word among the three inputs in
7205     // a half by taking the sum of the half with three inputs and subtracting
7206     // the sum of the actual three inputs. The difference is the remaining
7207     // slot.
7208     int DWordA = (ThreeInputHalfSum -
7209                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7210                  2;
7211     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7212
7213     int PSHUFDMask[] = {0, 1, 2, 3};
7214     PSHUFDMask[DWordA] = DWordB;
7215     PSHUFDMask[DWordB] = DWordA;
7216     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7217                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7218                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7219                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7220
7221     // Adjust the mask to match the new locations of A and B.
7222     for (int &M : Mask)
7223       if (M != -1 && M/2 == DWordA)
7224         M = 2 * DWordB + M % 2;
7225       else if (M != -1 && M/2 == DWordB)
7226         M = 2 * DWordA + M % 2;
7227
7228     // Recurse back into this routine to re-compute state now that this isn't
7229     // a 3 and 1 problem.
7230     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7231                                 Mask);
7232   };
7233   if (NumLToL == 3 && NumHToL == 1)
7234     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7235   else if (NumLToL == 1 && NumHToL == 3)
7236     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7237   else if (NumLToH == 1 && NumHToH == 3)
7238     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7239   else if (NumLToH == 3 && NumHToH == 1)
7240     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7241
7242   // At this point there are at most two inputs to the low and high halves from
7243   // each half. That means the inputs can always be grouped into dwords and
7244   // those dwords can then be moved to the correct half with a dword shuffle.
7245   // We use at most one low and one high word shuffle to collect these paired
7246   // inputs into dwords, and finally a dword shuffle to place them.
7247   int PSHUFLMask[4] = {-1, -1, -1, -1};
7248   int PSHUFHMask[4] = {-1, -1, -1, -1};
7249   int PSHUFDMask[4] = {-1, -1, -1, -1};
7250
7251   // First fix the masks for all the inputs that are staying in their
7252   // original halves. This will then dictate the targets of the cross-half
7253   // shuffles.
7254   auto fixInPlaceInputs = [&PSHUFDMask](
7255       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7256       MutableArrayRef<int> HalfMask, int HalfOffset) {
7257     if (InPlaceInputs.empty())
7258       return;
7259     if (InPlaceInputs.size() == 1) {
7260       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7261           InPlaceInputs[0] - HalfOffset;
7262       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7263       return;
7264     }
7265
7266     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7267     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7268         InPlaceInputs[0] - HalfOffset;
7269     // Put the second input next to the first so that they are packed into
7270     // a dword. We find the adjacent index by toggling the low bit.
7271     int AdjIndex = InPlaceInputs[0] ^ 1;
7272     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7273     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7274     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7275   };
7276   if (!HToLInputs.empty())
7277     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7278   if (!LToHInputs.empty())
7279     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7280
7281   // Now gather the cross-half inputs and place them into a free dword of
7282   // their target half.
7283   // FIXME: This operation could almost certainly be simplified dramatically to
7284   // look more like the 3-1 fixing operation.
7285   auto moveInputsToRightHalf = [&PSHUFDMask](
7286       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7287       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7288       int SourceOffset, int DestOffset) {
7289     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7290       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7291     };
7292     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7293                                                int Word) {
7294       int LowWord = Word & ~1;
7295       int HighWord = Word | 1;
7296       return isWordClobbered(SourceHalfMask, LowWord) ||
7297              isWordClobbered(SourceHalfMask, HighWord);
7298     };
7299
7300     if (IncomingInputs.empty())
7301       return;
7302
7303     if (ExistingInputs.empty()) {
7304       // Map any dwords with inputs from them into the right half.
7305       for (int Input : IncomingInputs) {
7306         // If the source half mask maps over the inputs, turn those into
7307         // swaps and use the swapped lane.
7308         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7309           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7310             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7311                 Input - SourceOffset;
7312             // We have to swap the uses in our half mask in one sweep.
7313             for (int &M : HalfMask)
7314               if (M == SourceHalfMask[Input - SourceOffset])
7315                 M = Input;
7316               else if (M == Input)
7317                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7318           } else {
7319             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7320                        Input - SourceOffset &&
7321                    "Previous placement doesn't match!");
7322           }
7323           // Note that this correctly re-maps both when we do a swap and when
7324           // we observe the other side of the swap above. We rely on that to
7325           // avoid swapping the members of the input list directly.
7326           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7327         }
7328
7329         // Map the input's dword into the correct half.
7330         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7331           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7332         else
7333           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7334                      Input / 2 &&
7335                  "Previous placement doesn't match!");
7336       }
7337
7338       // And just directly shift any other-half mask elements to be same-half
7339       // as we will have mirrored the dword containing the element into the
7340       // same position within that half.
7341       for (int &M : HalfMask)
7342         if (M >= SourceOffset && M < SourceOffset + 4) {
7343           M = M - SourceOffset + DestOffset;
7344           assert(M >= 0 && "This should never wrap below zero!");
7345         }
7346       return;
7347     }
7348
7349     // Ensure we have the input in a viable dword of its current half. This
7350     // is particularly tricky because the original position may be clobbered
7351     // by inputs being moved and *staying* in that half.
7352     if (IncomingInputs.size() == 1) {
7353       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7354         int InputFixed = std::find(std::begin(SourceHalfMask),
7355                                    std::end(SourceHalfMask), -1) -
7356                          std::begin(SourceHalfMask) + SourceOffset;
7357         SourceHalfMask[InputFixed - SourceOffset] =
7358             IncomingInputs[0] - SourceOffset;
7359         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7360                      InputFixed);
7361         IncomingInputs[0] = InputFixed;
7362       }
7363     } else if (IncomingInputs.size() == 2) {
7364       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7365           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7366         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7367         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7368                "Not all dwords can be clobbered!");
7369         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7370         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7371         for (int &M : HalfMask)
7372           if (M == IncomingInputs[0])
7373             M = SourceDWordBase + SourceOffset;
7374           else if (M == IncomingInputs[1])
7375             M = SourceDWordBase + 1 + SourceOffset;
7376         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7377         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7378       }
7379     } else {
7380       llvm_unreachable("Unhandled input size!");
7381     }
7382
7383     // Now hoist the DWord down to the right half.
7384     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7385     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7386     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7387     for (int Input : IncomingInputs)
7388       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7389                    FreeDWord * 2 + Input % 2);
7390   };
7391   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7392                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7393   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7394                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7395
7396   // Now enact all the shuffles we've computed to move the inputs into their
7397   // target half.
7398   if (!isNoopShuffleMask(PSHUFLMask))
7399     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7400                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7401   if (!isNoopShuffleMask(PSHUFHMask))
7402     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7403                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7404   if (!isNoopShuffleMask(PSHUFDMask))
7405     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7406                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7407                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7408                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7409
7410   // At this point, each half should contain all its inputs, and we can then
7411   // just shuffle them into their final position.
7412   assert(std::count_if(LoMask.begin(), LoMask.end(),
7413                        [](int M) { return M >= 4; }) == 0 &&
7414          "Failed to lift all the high half inputs to the low mask!");
7415   assert(std::count_if(HiMask.begin(), HiMask.end(),
7416                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7417          "Failed to lift all the low half inputs to the high mask!");
7418
7419   // Do a half shuffle for the low mask.
7420   if (!isNoopShuffleMask(LoMask))
7421     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7422                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7423
7424   // Do a half shuffle with the high mask after shifting its values down.
7425   for (int &M : HiMask)
7426     if (M >= 0)
7427       M -= 4;
7428   if (!isNoopShuffleMask(HiMask))
7429     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7430                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7431
7432   return V;
7433 }
7434
7435 /// \brief Detect whether the mask pattern should be lowered through
7436 /// interleaving.
7437 ///
7438 /// This essentially tests whether viewing the mask as an interleaving of two
7439 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7440 /// lowering it through interleaving is a significantly better strategy.
7441 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7442   int NumEvenInputs[2] = {0, 0};
7443   int NumOddInputs[2] = {0, 0};
7444   int NumLoInputs[2] = {0, 0};
7445   int NumHiInputs[2] = {0, 0};
7446   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7447     if (Mask[i] < 0)
7448       continue;
7449
7450     int InputIdx = Mask[i] >= Size;
7451
7452     if (i < Size / 2)
7453       ++NumLoInputs[InputIdx];
7454     else
7455       ++NumHiInputs[InputIdx];
7456
7457     if ((i % 2) == 0)
7458       ++NumEvenInputs[InputIdx];
7459     else
7460       ++NumOddInputs[InputIdx];
7461   }
7462
7463   // The minimum number of cross-input results for both the interleaved and
7464   // split cases. If interleaving results in fewer cross-input results, return
7465   // true.
7466   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7467                                     NumEvenInputs[0] + NumOddInputs[1]);
7468   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7469                               NumLoInputs[0] + NumHiInputs[1]);
7470   return InterleavedCrosses < SplitCrosses;
7471 }
7472
7473 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7474 ///
7475 /// This strategy only works when the inputs from each vector fit into a single
7476 /// half of that vector, and generally there are not so many inputs as to leave
7477 /// the in-place shuffles required highly constrained (and thus expensive). It
7478 /// shifts all the inputs into a single side of both input vectors and then
7479 /// uses an unpack to interleave these inputs in a single vector. At that
7480 /// point, we will fall back on the generic single input shuffle lowering.
7481 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7482                                                  SDValue V2,
7483                                                  MutableArrayRef<int> Mask,
7484                                                  const X86Subtarget *Subtarget,
7485                                                  SelectionDAG &DAG) {
7486   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7487   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7488   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7489   for (int i = 0; i < 8; ++i)
7490     if (Mask[i] >= 0 && Mask[i] < 4)
7491       LoV1Inputs.push_back(i);
7492     else if (Mask[i] >= 4 && Mask[i] < 8)
7493       HiV1Inputs.push_back(i);
7494     else if (Mask[i] >= 8 && Mask[i] < 12)
7495       LoV2Inputs.push_back(i);
7496     else if (Mask[i] >= 12)
7497       HiV2Inputs.push_back(i);
7498
7499   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7500   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7501   (void)NumV1Inputs;
7502   (void)NumV2Inputs;
7503   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7504   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7505   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7506
7507   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7508                      HiV1Inputs.size() + HiV2Inputs.size();
7509
7510   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7511                               ArrayRef<int> HiInputs, bool MoveToLo,
7512                               int MaskOffset) {
7513     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7514     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7515     if (BadInputs.empty())
7516       return V;
7517
7518     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7519     int MoveOffset = MoveToLo ? 0 : 4;
7520
7521     if (GoodInputs.empty()) {
7522       for (int BadInput : BadInputs) {
7523         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7524         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7525       }
7526     } else {
7527       if (GoodInputs.size() == 2) {
7528         // If the low inputs are spread across two dwords, pack them into
7529         // a single dword.
7530         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7531             Mask[GoodInputs[0]] - MaskOffset;
7532         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7533             Mask[GoodInputs[1]] - MaskOffset;
7534         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7535         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7536       } else {
7537         // Otherwise pin the low inputs.
7538         for (int GoodInput : GoodInputs)
7539           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7540       }
7541
7542       int MoveMaskIdx =
7543           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7544           std::begin(MoveMask);
7545       assert(MoveMaskIdx >= MoveOffset && "Established above");
7546
7547       if (BadInputs.size() == 2) {
7548         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7549         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7550         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7551             Mask[BadInputs[0]] - MaskOffset;
7552         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7553             Mask[BadInputs[1]] - MaskOffset;
7554         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7555         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7556       } else {
7557         assert(BadInputs.size() == 1 && "All sizes handled");
7558         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7559         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7560       }
7561     }
7562
7563     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7564                                 MoveMask);
7565   };
7566   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7567                         /*MaskOffset*/ 0);
7568   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7569                         /*MaskOffset*/ 8);
7570
7571   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7572   // cross-half traffic in the final shuffle.
7573
7574   // Munge the mask to be a single-input mask after the unpack merges the
7575   // results.
7576   for (int &M : Mask)
7577     if (M != -1)
7578       M = 2 * (M % 4) + (M / 8);
7579
7580   return DAG.getVectorShuffle(
7581       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7582                                   DL, MVT::v8i16, V1, V2),
7583       DAG.getUNDEF(MVT::v8i16), Mask);
7584 }
7585
7586 /// \brief Generic lowering of 8-lane i16 shuffles.
7587 ///
7588 /// This handles both single-input shuffles and combined shuffle/blends with
7589 /// two inputs. The single input shuffles are immediately delegated to
7590 /// a dedicated lowering routine.
7591 ///
7592 /// The blends are lowered in one of three fundamental ways. If there are few
7593 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7594 /// of the input is significantly cheaper when lowered as an interleaving of
7595 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7596 /// halves of the inputs separately (making them have relatively few inputs)
7597 /// and then concatenate them.
7598 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7599                                        const X86Subtarget *Subtarget,
7600                                        SelectionDAG &DAG) {
7601   SDLoc DL(Op);
7602   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7603   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7604   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7605   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7606   ArrayRef<int> OrigMask = SVOp->getMask();
7607   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7608                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7609   MutableArrayRef<int> Mask(MaskStorage);
7610
7611   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7612
7613   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7614   auto isV2 = [](int M) { return M >= 8; };
7615
7616   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7617   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7618
7619   if (NumV2Inputs == 0)
7620     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7621
7622   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7623                             "to be V1-input shuffles.");
7624
7625   if (NumV1Inputs + NumV2Inputs <= 4)
7626     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7627
7628   // Check whether an interleaving lowering is likely to be more efficient.
7629   // This isn't perfect but it is a strong heuristic that tends to work well on
7630   // the kinds of shuffles that show up in practice.
7631   //
7632   // FIXME: Handle 1x, 2x, and 4x interleaving.
7633   if (shouldLowerAsInterleaving(Mask)) {
7634     // FIXME: Figure out whether we should pack these into the low or high
7635     // halves.
7636
7637     int EMask[8], OMask[8];
7638     for (int i = 0; i < 4; ++i) {
7639       EMask[i] = Mask[2*i];
7640       OMask[i] = Mask[2*i + 1];
7641       EMask[i + 4] = -1;
7642       OMask[i + 4] = -1;
7643     }
7644
7645     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7646     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7647
7648     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7649   }
7650
7651   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7652   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7653
7654   for (int i = 0; i < 4; ++i) {
7655     LoBlendMask[i] = Mask[i];
7656     HiBlendMask[i] = Mask[i + 4];
7657   }
7658
7659   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7660   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7661   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7662   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7663
7664   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7665                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7666 }
7667
7668 /// \brief Generic lowering of v16i8 shuffles.
7669 ///
7670 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7671 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7672 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7673 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7674 /// back together.
7675 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7676                                        const X86Subtarget *Subtarget,
7677                                        SelectionDAG &DAG) {
7678   SDLoc DL(Op);
7679   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7680   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7681   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7682   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7683   ArrayRef<int> OrigMask = SVOp->getMask();
7684   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7685   int MaskStorage[16] = {
7686       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7687       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7688       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7689       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7690   MutableArrayRef<int> Mask(MaskStorage);
7691   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7692   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7693
7694   // For single-input shuffles, there are some nicer lowering tricks we can use.
7695   if (isSingleInputShuffleMask(Mask)) {
7696     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7697     // Notably, this handles splat and partial-splat shuffles more efficiently.
7698     //
7699     // FIXME: We should check for other patterns which can be widened into an
7700     // i16 shuffle as well.
7701     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7702       for (int i = 0; i < 16; i += 2) {
7703         if (Mask[i] != Mask[i + 1])
7704           return false;
7705       }
7706       return true;
7707     };
7708     if (canWidenViaDuplication(Mask)) {
7709       SmallVector<int, 4> LoInputs;
7710       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7711                    [](int M) { return M >= 0 && M < 8; });
7712       std::sort(LoInputs.begin(), LoInputs.end());
7713       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7714                      LoInputs.end());
7715       SmallVector<int, 4> HiInputs;
7716       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7717                    [](int M) { return M >= 8; });
7718       std::sort(HiInputs.begin(), HiInputs.end());
7719       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7720                      HiInputs.end());
7721
7722       bool TargetLo = LoInputs.size() >= HiInputs.size();
7723       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7724       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7725
7726       int ByteMask[16];
7727       SmallDenseMap<int, int, 8> LaneMap;
7728       for (int i = 0; i < 16; ++i)
7729         ByteMask[i] = -1;
7730       for (int I : InPlaceInputs) {
7731         ByteMask[I] = I;
7732         LaneMap[I] = I;
7733       }
7734       int FreeByteIdx = 0;
7735       int TargetOffset = TargetLo ? 0 : 8;
7736       for (int I : MovingInputs) {
7737         // Walk the free index into the byte mask until we find an unoccupied
7738         // spot. We bound this to 8 steps to catch bugs, the pigeonhole
7739         // principle indicates that there *must* be a spot as we can only have
7740         // 8 duplicated inputs. We have to walk the index using modular
7741         // arithmetic to wrap around as necessary.
7742         // FIXME: We could do a much better job of picking an inexpensive slot
7743         // so this doesn't go through the worst case for the byte shuffle.
7744         for (int j = 0; j < 8 && ByteMask[FreeByteIdx + TargetOffset] != -1;
7745              ++j, FreeByteIdx = (FreeByteIdx + 1) % 8)
7746           ;
7747         assert(ByteMask[FreeByteIdx + TargetOffset] == -1 &&
7748                "Failed to find a free byte!");
7749         ByteMask[FreeByteIdx + TargetOffset] = I;
7750         LaneMap[I] = FreeByteIdx + TargetOffset;
7751       }
7752       V1 = DAG.getVectorShuffle(MVT::v16i8, DL, V1, DAG.getUNDEF(MVT::v16i8),
7753                                 ByteMask);
7754       for (int &M : Mask)
7755         if (M != -1)
7756           M = LaneMap[M];
7757
7758       // Unpack the bytes to form the i16s that will be shuffled into place.
7759       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7760                        MVT::v16i8, V1, V1);
7761
7762       int I16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7763       for (int i = 0; i < 16; i += 2) {
7764         if (Mask[i] != -1)
7765           I16Shuffle[i / 2] = Mask[i] - (TargetLo ? 0 : 8);
7766         assert(I16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7767       }
7768       return DAG.getVectorShuffle(MVT::v8i16, DL,
7769                                   DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7770                                   DAG.getUNDEF(MVT::v8i16), I16Shuffle);
7771     }
7772   }
7773
7774   // Check whether an interleaving lowering is likely to be more efficient.
7775   // This isn't perfect but it is a strong heuristic that tends to work well on
7776   // the kinds of shuffles that show up in practice.
7777   //
7778   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7779   if (shouldLowerAsInterleaving(Mask)) {
7780     // FIXME: Figure out whether we should pack these into the low or high
7781     // halves.
7782
7783     int EMask[16], OMask[16];
7784     for (int i = 0; i < 8; ++i) {
7785       EMask[i] = Mask[2*i];
7786       OMask[i] = Mask[2*i + 1];
7787       EMask[i + 8] = -1;
7788       OMask[i + 8] = -1;
7789     }
7790
7791     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7792     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7793
7794     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7795   }
7796   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7797   SDValue LoV1 =
7798       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7799                   DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, Zero));
7800   SDValue HiV1 =
7801       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7802                   DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, Zero));
7803   SDValue LoV2 =
7804       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7805                   DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V2, Zero));
7806   SDValue HiV2 =
7807       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7808                   DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V2, Zero));
7809
7810   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7811   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7812   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7813   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7814
7815   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7816                             MutableArrayRef<int> V1HalfBlendMask,
7817                             MutableArrayRef<int> V2HalfBlendMask) {
7818     for (int i = 0; i < 8; ++i)
7819       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7820         V1HalfBlendMask[i] = HalfMask[i];
7821         HalfMask[i] = i;
7822       } else if (HalfMask[i] >= 16) {
7823         V2HalfBlendMask[i] = HalfMask[i] - 16;
7824         HalfMask[i] = i + 8;
7825       }
7826   };
7827   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7828   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7829
7830   SDValue V1Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1LoBlendMask);
7831   SDValue V2Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2LoBlendMask);
7832   SDValue V1Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1HiBlendMask);
7833   SDValue V2Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2HiBlendMask);
7834
7835   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7836   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7837
7838   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7839 }
7840
7841 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7842 ///
7843 /// This routine breaks down the specific type of 128-bit shuffle and
7844 /// dispatches to the lowering routines accordingly.
7845 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7846                                         MVT VT, const X86Subtarget *Subtarget,
7847                                         SelectionDAG &DAG) {
7848   switch (VT.SimpleTy) {
7849   case MVT::v2i64:
7850     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7851   case MVT::v2f64:
7852     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7853   case MVT::v4i32:
7854     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7855   case MVT::v4f32:
7856     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7857   case MVT::v8i16:
7858     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7859   case MVT::v16i8:
7860     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7861
7862   default:
7863     llvm_unreachable("Unimplemented!");
7864   }
7865 }
7866
7867 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7868 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7869   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7870     if (Mask[i] + 1 != Mask[i+1])
7871       return false;
7872
7873   return true;
7874 }
7875
7876 /// \brief Top-level lowering for x86 vector shuffles.
7877 ///
7878 /// This handles decomposition, canonicalization, and lowering of all x86
7879 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7880 /// above in helper routines. The canonicalization attempts to widen shuffles
7881 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7882 /// s.t. only one of the two inputs needs to be tested, etc.
7883 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7884                                   SelectionDAG &DAG) {
7885   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7886   ArrayRef<int> Mask = SVOp->getMask();
7887   SDValue V1 = Op.getOperand(0);
7888   SDValue V2 = Op.getOperand(1);
7889   MVT VT = Op.getSimpleValueType();
7890   int NumElements = VT.getVectorNumElements();
7891   SDLoc dl(Op);
7892
7893   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7894
7895   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7896   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7897   if (V1IsUndef && V2IsUndef)
7898     return DAG.getUNDEF(VT);
7899
7900   // When we create a shuffle node we put the UNDEF node to second operand,
7901   // but in some cases the first operand may be transformed to UNDEF.
7902   // In this case we should just commute the node.
7903   if (V1IsUndef)
7904     return CommuteVectorShuffle(SVOp, DAG);
7905
7906   // Check for non-undef masks pointing at an undef vector and make the masks
7907   // undef as well. This makes it easier to match the shuffle based solely on
7908   // the mask.
7909   if (V2IsUndef)
7910     for (int M : Mask)
7911       if (M >= NumElements) {
7912         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7913         for (int &M : NewMask)
7914           if (M >= NumElements)
7915             M = -1;
7916         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7917       }
7918
7919   // For integer vector shuffles, try to collapse them into a shuffle of fewer
7920   // lanes but wider integers. We cap this to not form integers larger than i64
7921   // but it might be interesting to form i128 integers to handle flipping the
7922   // low and high halves of AVX 256-bit vectors.
7923   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7924       areAdjacentMasksSequential(Mask)) {
7925     SmallVector<int, 8> NewMask;
7926     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7927       NewMask.push_back(Mask[i] / 2);
7928     MVT NewVT =
7929         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7930                          VT.getVectorNumElements() / 2);
7931     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7932     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7933     return DAG.getNode(ISD::BITCAST, dl, VT,
7934                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7935   }
7936
7937   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7938   for (int M : SVOp->getMask())
7939     if (M < 0)
7940       ++NumUndefElements;
7941     else if (M < NumElements)
7942       ++NumV1Elements;
7943     else
7944       ++NumV2Elements;
7945
7946   // Commute the shuffle as needed such that more elements come from V1 than
7947   // V2. This allows us to match the shuffle pattern strictly on how many
7948   // elements come from V1 without handling the symmetric cases.
7949   if (NumV2Elements > NumV1Elements)
7950     return CommuteVectorShuffle(SVOp, DAG);
7951
7952   // When the number of V1 and V2 elements are the same, try to minimize the
7953   // number of uses of V2 in the low half of the vector.
7954   if (NumV1Elements == NumV2Elements) {
7955     int LowV1Elements = 0, LowV2Elements = 0;
7956     for (int M : SVOp->getMask().slice(0, NumElements / 2))
7957       if (M >= NumElements)
7958         ++LowV2Elements;
7959       else if (M >= 0)
7960         ++LowV1Elements;
7961     if (LowV2Elements > LowV1Elements)
7962       return CommuteVectorShuffle(SVOp, DAG);
7963   }
7964
7965   // For each vector width, delegate to a specialized lowering routine.
7966   if (VT.getSizeInBits() == 128)
7967     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
7968
7969   llvm_unreachable("Unimplemented!");
7970 }
7971
7972
7973 //===----------------------------------------------------------------------===//
7974 // Legacy vector shuffle lowering
7975 //
7976 // This code is the legacy code handling vector shuffles until the above
7977 // replaces its functionality and performance.
7978 //===----------------------------------------------------------------------===//
7979
7980 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
7981                         bool hasInt256, unsigned *MaskOut = nullptr) {
7982   MVT EltVT = VT.getVectorElementType();
7983
7984   // There is no blend with immediate in AVX-512.
7985   if (VT.is512BitVector())
7986     return false;
7987
7988   if (!hasSSE41 || EltVT == MVT::i8)
7989     return false;
7990   if (!hasInt256 && VT == MVT::v16i16)
7991     return false;
7992
7993   unsigned MaskValue = 0;
7994   unsigned NumElems = VT.getVectorNumElements();
7995   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
7996   unsigned NumLanes = (NumElems - 1) / 8 + 1;
7997   unsigned NumElemsInLane = NumElems / NumLanes;
7998
7999   // Blend for v16i16 should be symetric for the both lanes.
8000   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8001
8002     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8003     int EltIdx = MaskVals[i];
8004
8005     if ((EltIdx < 0 || EltIdx == (int)i) &&
8006         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8007       continue;
8008
8009     if (((unsigned)EltIdx == (i + NumElems)) &&
8010         (SndLaneEltIdx < 0 ||
8011          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8012       MaskValue |= (1 << i);
8013     else
8014       return false;
8015   }
8016
8017   if (MaskOut)
8018     *MaskOut = MaskValue;
8019   return true;
8020 }
8021
8022 // Try to lower a shuffle node into a simple blend instruction.
8023 // This function assumes isBlendMask returns true for this
8024 // SuffleVectorSDNode
8025 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8026                                           unsigned MaskValue,
8027                                           const X86Subtarget *Subtarget,
8028                                           SelectionDAG &DAG) {
8029   MVT VT = SVOp->getSimpleValueType(0);
8030   MVT EltVT = VT.getVectorElementType();
8031   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8032                      Subtarget->hasInt256() && "Trying to lower a "
8033                                                "VECTOR_SHUFFLE to a Blend but "
8034                                                "with the wrong mask"));
8035   SDValue V1 = SVOp->getOperand(0);
8036   SDValue V2 = SVOp->getOperand(1);
8037   SDLoc dl(SVOp);
8038   unsigned NumElems = VT.getVectorNumElements();
8039
8040   // Convert i32 vectors to floating point if it is not AVX2.
8041   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8042   MVT BlendVT = VT;
8043   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8044     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8045                                NumElems);
8046     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8047     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8048   }
8049
8050   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8051                             DAG.getConstant(MaskValue, MVT::i32));
8052   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8053 }
8054
8055 /// In vector type \p VT, return true if the element at index \p InputIdx
8056 /// falls on a different 128-bit lane than \p OutputIdx.
8057 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8058                                      unsigned OutputIdx) {
8059   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8060   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8061 }
8062
8063 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8064 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8065 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8066 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8067 /// zero.
8068 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8069                          SelectionDAG &DAG) {
8070   MVT VT = V1.getSimpleValueType();
8071   assert(VT.is128BitVector() || VT.is256BitVector());
8072
8073   MVT EltVT = VT.getVectorElementType();
8074   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8075   unsigned NumElts = VT.getVectorNumElements();
8076
8077   SmallVector<SDValue, 32> PshufbMask;
8078   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8079     int InputIdx = MaskVals[OutputIdx];
8080     unsigned InputByteIdx;
8081
8082     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8083       InputByteIdx = 0x80;
8084     else {
8085       // Cross lane is not allowed.
8086       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8087         return SDValue();
8088       InputByteIdx = InputIdx * EltSizeInBytes;
8089       // Index is an byte offset within the 128-bit lane.
8090       InputByteIdx &= 0xf;
8091     }
8092
8093     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8094       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8095       if (InputByteIdx != 0x80)
8096         ++InputByteIdx;
8097     }
8098   }
8099
8100   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8101   if (ShufVT != VT)
8102     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8103   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8104                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8105 }
8106
8107 // v8i16 shuffles - Prefer shuffles in the following order:
8108 // 1. [all]   pshuflw, pshufhw, optional move
8109 // 2. [ssse3] 1 x pshufb
8110 // 3. [ssse3] 2 x pshufb + 1 x por
8111 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8112 static SDValue
8113 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8114                          SelectionDAG &DAG) {
8115   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8116   SDValue V1 = SVOp->getOperand(0);
8117   SDValue V2 = SVOp->getOperand(1);
8118   SDLoc dl(SVOp);
8119   SmallVector<int, 8> MaskVals;
8120
8121   // Determine if more than 1 of the words in each of the low and high quadwords
8122   // of the result come from the same quadword of one of the two inputs.  Undef
8123   // mask values count as coming from any quadword, for better codegen.
8124   //
8125   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8126   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8127   unsigned LoQuad[] = { 0, 0, 0, 0 };
8128   unsigned HiQuad[] = { 0, 0, 0, 0 };
8129   // Indices of quads used.
8130   std::bitset<4> InputQuads;
8131   for (unsigned i = 0; i < 8; ++i) {
8132     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8133     int EltIdx = SVOp->getMaskElt(i);
8134     MaskVals.push_back(EltIdx);
8135     if (EltIdx < 0) {
8136       ++Quad[0];
8137       ++Quad[1];
8138       ++Quad[2];
8139       ++Quad[3];
8140       continue;
8141     }
8142     ++Quad[EltIdx / 4];
8143     InputQuads.set(EltIdx / 4);
8144   }
8145
8146   int BestLoQuad = -1;
8147   unsigned MaxQuad = 1;
8148   for (unsigned i = 0; i < 4; ++i) {
8149     if (LoQuad[i] > MaxQuad) {
8150       BestLoQuad = i;
8151       MaxQuad = LoQuad[i];
8152     }
8153   }
8154
8155   int BestHiQuad = -1;
8156   MaxQuad = 1;
8157   for (unsigned i = 0; i < 4; ++i) {
8158     if (HiQuad[i] > MaxQuad) {
8159       BestHiQuad = i;
8160       MaxQuad = HiQuad[i];
8161     }
8162   }
8163
8164   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8165   // of the two input vectors, shuffle them into one input vector so only a
8166   // single pshufb instruction is necessary. If there are more than 2 input
8167   // quads, disable the next transformation since it does not help SSSE3.
8168   bool V1Used = InputQuads[0] || InputQuads[1];
8169   bool V2Used = InputQuads[2] || InputQuads[3];
8170   if (Subtarget->hasSSSE3()) {
8171     if (InputQuads.count() == 2 && V1Used && V2Used) {
8172       BestLoQuad = InputQuads[0] ? 0 : 1;
8173       BestHiQuad = InputQuads[2] ? 2 : 3;
8174     }
8175     if (InputQuads.count() > 2) {
8176       BestLoQuad = -1;
8177       BestHiQuad = -1;
8178     }
8179   }
8180
8181   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8182   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8183   // words from all 4 input quadwords.
8184   SDValue NewV;
8185   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8186     int MaskV[] = {
8187       BestLoQuad < 0 ? 0 : BestLoQuad,
8188       BestHiQuad < 0 ? 1 : BestHiQuad
8189     };
8190     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8191                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8192                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8193     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8194
8195     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8196     // source words for the shuffle, to aid later transformations.
8197     bool AllWordsInNewV = true;
8198     bool InOrder[2] = { true, true };
8199     for (unsigned i = 0; i != 8; ++i) {
8200       int idx = MaskVals[i];
8201       if (idx != (int)i)
8202         InOrder[i/4] = false;
8203       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8204         continue;
8205       AllWordsInNewV = false;
8206       break;
8207     }
8208
8209     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8210     if (AllWordsInNewV) {
8211       for (int i = 0; i != 8; ++i) {
8212         int idx = MaskVals[i];
8213         if (idx < 0)
8214           continue;
8215         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8216         if ((idx != i) && idx < 4)
8217           pshufhw = false;
8218         if ((idx != i) && idx > 3)
8219           pshuflw = false;
8220       }
8221       V1 = NewV;
8222       V2Used = false;
8223       BestLoQuad = 0;
8224       BestHiQuad = 1;
8225     }
8226
8227     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8228     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8229     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8230       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8231       unsigned TargetMask = 0;
8232       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8233                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8234       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8235       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8236                              getShufflePSHUFLWImmediate(SVOp);
8237       V1 = NewV.getOperand(0);
8238       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8239     }
8240   }
8241
8242   // Promote splats to a larger type which usually leads to more efficient code.
8243   // FIXME: Is this true if pshufb is available?
8244   if (SVOp->isSplat())
8245     return PromoteSplat(SVOp, DAG);
8246
8247   // If we have SSSE3, and all words of the result are from 1 input vector,
8248   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8249   // is present, fall back to case 4.
8250   if (Subtarget->hasSSSE3()) {
8251     SmallVector<SDValue,16> pshufbMask;
8252
8253     // If we have elements from both input vectors, set the high bit of the
8254     // shuffle mask element to zero out elements that come from V2 in the V1
8255     // mask, and elements that come from V1 in the V2 mask, so that the two
8256     // results can be OR'd together.
8257     bool TwoInputs = V1Used && V2Used;
8258     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8259     if (!TwoInputs)
8260       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8261
8262     // Calculate the shuffle mask for the second input, shuffle it, and
8263     // OR it with the first shuffled input.
8264     CommuteVectorShuffleMask(MaskVals, 8);
8265     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8266     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8267     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8268   }
8269
8270   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8271   // and update MaskVals with new element order.
8272   std::bitset<8> InOrder;
8273   if (BestLoQuad >= 0) {
8274     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8275     for (int i = 0; i != 4; ++i) {
8276       int idx = MaskVals[i];
8277       if (idx < 0) {
8278         InOrder.set(i);
8279       } else if ((idx / 4) == BestLoQuad) {
8280         MaskV[i] = idx & 3;
8281         InOrder.set(i);
8282       }
8283     }
8284     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8285                                 &MaskV[0]);
8286
8287     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8288       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8289       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8290                                   NewV.getOperand(0),
8291                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8292     }
8293   }
8294
8295   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8296   // and update MaskVals with the new element order.
8297   if (BestHiQuad >= 0) {
8298     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8299     for (unsigned i = 4; i != 8; ++i) {
8300       int idx = MaskVals[i];
8301       if (idx < 0) {
8302         InOrder.set(i);
8303       } else if ((idx / 4) == BestHiQuad) {
8304         MaskV[i] = (idx & 3) + 4;
8305         InOrder.set(i);
8306       }
8307     }
8308     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8309                                 &MaskV[0]);
8310
8311     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8312       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8313       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8314                                   NewV.getOperand(0),
8315                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8316     }
8317   }
8318
8319   // In case BestHi & BestLo were both -1, which means each quadword has a word
8320   // from each of the four input quadwords, calculate the InOrder bitvector now
8321   // before falling through to the insert/extract cleanup.
8322   if (BestLoQuad == -1 && BestHiQuad == -1) {
8323     NewV = V1;
8324     for (int i = 0; i != 8; ++i)
8325       if (MaskVals[i] < 0 || MaskVals[i] == i)
8326         InOrder.set(i);
8327   }
8328
8329   // The other elements are put in the right place using pextrw and pinsrw.
8330   for (unsigned i = 0; i != 8; ++i) {
8331     if (InOrder[i])
8332       continue;
8333     int EltIdx = MaskVals[i];
8334     if (EltIdx < 0)
8335       continue;
8336     SDValue ExtOp = (EltIdx < 8) ?
8337       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8338                   DAG.getIntPtrConstant(EltIdx)) :
8339       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8340                   DAG.getIntPtrConstant(EltIdx - 8));
8341     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8342                        DAG.getIntPtrConstant(i));
8343   }
8344   return NewV;
8345 }
8346
8347 /// \brief v16i16 shuffles
8348 ///
8349 /// FIXME: We only support generation of a single pshufb currently.  We can
8350 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8351 /// well (e.g 2 x pshufb + 1 x por).
8352 static SDValue
8353 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8354   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8355   SDValue V1 = SVOp->getOperand(0);
8356   SDValue V2 = SVOp->getOperand(1);
8357   SDLoc dl(SVOp);
8358
8359   if (V2.getOpcode() != ISD::UNDEF)
8360     return SDValue();
8361
8362   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8363   return getPSHUFB(MaskVals, V1, dl, DAG);
8364 }
8365
8366 // v16i8 shuffles - Prefer shuffles in the following order:
8367 // 1. [ssse3] 1 x pshufb
8368 // 2. [ssse3] 2 x pshufb + 1 x por
8369 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8370 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8371                                         const X86Subtarget* Subtarget,
8372                                         SelectionDAG &DAG) {
8373   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8374   SDValue V1 = SVOp->getOperand(0);
8375   SDValue V2 = SVOp->getOperand(1);
8376   SDLoc dl(SVOp);
8377   ArrayRef<int> MaskVals = SVOp->getMask();
8378
8379   // Promote splats to a larger type which usually leads to more efficient code.
8380   // FIXME: Is this true if pshufb is available?
8381   if (SVOp->isSplat())
8382     return PromoteSplat(SVOp, DAG);
8383
8384   // If we have SSSE3, case 1 is generated when all result bytes come from
8385   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8386   // present, fall back to case 3.
8387
8388   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8389   if (Subtarget->hasSSSE3()) {
8390     SmallVector<SDValue,16> pshufbMask;
8391
8392     // If all result elements are from one input vector, then only translate
8393     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8394     //
8395     // Otherwise, we have elements from both input vectors, and must zero out
8396     // elements that come from V2 in the first mask, and V1 in the second mask
8397     // so that we can OR them together.
8398     for (unsigned i = 0; i != 16; ++i) {
8399       int EltIdx = MaskVals[i];
8400       if (EltIdx < 0 || EltIdx >= 16)
8401         EltIdx = 0x80;
8402       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8403     }
8404     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8405                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8406                                  MVT::v16i8, pshufbMask));
8407
8408     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8409     // the 2nd operand if it's undefined or zero.
8410     if (V2.getOpcode() == ISD::UNDEF ||
8411         ISD::isBuildVectorAllZeros(V2.getNode()))
8412       return V1;
8413
8414     // Calculate the shuffle mask for the second input, shuffle it, and
8415     // OR it with the first shuffled input.
8416     pshufbMask.clear();
8417     for (unsigned i = 0; i != 16; ++i) {
8418       int EltIdx = MaskVals[i];
8419       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8420       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8421     }
8422     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8423                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8424                                  MVT::v16i8, pshufbMask));
8425     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8426   }
8427
8428   // No SSSE3 - Calculate in place words and then fix all out of place words
8429   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8430   // the 16 different words that comprise the two doublequadword input vectors.
8431   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8432   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8433   SDValue NewV = V1;
8434   for (int i = 0; i != 8; ++i) {
8435     int Elt0 = MaskVals[i*2];
8436     int Elt1 = MaskVals[i*2+1];
8437
8438     // This word of the result is all undef, skip it.
8439     if (Elt0 < 0 && Elt1 < 0)
8440       continue;
8441
8442     // This word of the result is already in the correct place, skip it.
8443     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8444       continue;
8445
8446     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8447     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8448     SDValue InsElt;
8449
8450     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8451     // using a single extract together, load it and store it.
8452     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8453       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8454                            DAG.getIntPtrConstant(Elt1 / 2));
8455       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8456                         DAG.getIntPtrConstant(i));
8457       continue;
8458     }
8459
8460     // If Elt1 is defined, extract it from the appropriate source.  If the
8461     // source byte is not also odd, shift the extracted word left 8 bits
8462     // otherwise clear the bottom 8 bits if we need to do an or.
8463     if (Elt1 >= 0) {
8464       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8465                            DAG.getIntPtrConstant(Elt1 / 2));
8466       if ((Elt1 & 1) == 0)
8467         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8468                              DAG.getConstant(8,
8469                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8470       else if (Elt0 >= 0)
8471         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8472                              DAG.getConstant(0xFF00, MVT::i16));
8473     }
8474     // If Elt0 is defined, extract it from the appropriate source.  If the
8475     // source byte is not also even, shift the extracted word right 8 bits. If
8476     // Elt1 was also defined, OR the extracted values together before
8477     // inserting them in the result.
8478     if (Elt0 >= 0) {
8479       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8480                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8481       if ((Elt0 & 1) != 0)
8482         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8483                               DAG.getConstant(8,
8484                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8485       else if (Elt1 >= 0)
8486         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8487                              DAG.getConstant(0x00FF, MVT::i16));
8488       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8489                          : InsElt0;
8490     }
8491     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8492                        DAG.getIntPtrConstant(i));
8493   }
8494   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8495 }
8496
8497 // v32i8 shuffles - Translate to VPSHUFB if possible.
8498 static
8499 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8500                                  const X86Subtarget *Subtarget,
8501                                  SelectionDAG &DAG) {
8502   MVT VT = SVOp->getSimpleValueType(0);
8503   SDValue V1 = SVOp->getOperand(0);
8504   SDValue V2 = SVOp->getOperand(1);
8505   SDLoc dl(SVOp);
8506   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8507
8508   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8509   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8510   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8511
8512   // VPSHUFB may be generated if
8513   // (1) one of input vector is undefined or zeroinitializer.
8514   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8515   // And (2) the mask indexes don't cross the 128-bit lane.
8516   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8517       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8518     return SDValue();
8519
8520   if (V1IsAllZero && !V2IsAllZero) {
8521     CommuteVectorShuffleMask(MaskVals, 32);
8522     V1 = V2;
8523   }
8524   return getPSHUFB(MaskVals, V1, dl, DAG);
8525 }
8526
8527 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8528 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8529 /// done when every pair / quad of shuffle mask elements point to elements in
8530 /// the right sequence. e.g.
8531 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8532 static
8533 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8534                                  SelectionDAG &DAG) {
8535   MVT VT = SVOp->getSimpleValueType(0);
8536   SDLoc dl(SVOp);
8537   unsigned NumElems = VT.getVectorNumElements();
8538   MVT NewVT;
8539   unsigned Scale;
8540   switch (VT.SimpleTy) {
8541   default: llvm_unreachable("Unexpected!");
8542   case MVT::v2i64:
8543   case MVT::v2f64:
8544            return SDValue(SVOp, 0);
8545   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8546   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8547   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8548   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8549   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8550   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8551   }
8552
8553   SmallVector<int, 8> MaskVec;
8554   for (unsigned i = 0; i != NumElems; i += Scale) {
8555     int StartIdx = -1;
8556     for (unsigned j = 0; j != Scale; ++j) {
8557       int EltIdx = SVOp->getMaskElt(i+j);
8558       if (EltIdx < 0)
8559         continue;
8560       if (StartIdx < 0)
8561         StartIdx = (EltIdx / Scale);
8562       if (EltIdx != (int)(StartIdx*Scale + j))
8563         return SDValue();
8564     }
8565     MaskVec.push_back(StartIdx);
8566   }
8567
8568   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8569   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8570   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8571 }
8572
8573 /// getVZextMovL - Return a zero-extending vector move low node.
8574 ///
8575 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8576                             SDValue SrcOp, SelectionDAG &DAG,
8577                             const X86Subtarget *Subtarget, SDLoc dl) {
8578   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8579     LoadSDNode *LD = nullptr;
8580     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8581       LD = dyn_cast<LoadSDNode>(SrcOp);
8582     if (!LD) {
8583       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8584       // instead.
8585       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8586       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8587           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8588           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8589           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8590         // PR2108
8591         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8592         return DAG.getNode(ISD::BITCAST, dl, VT,
8593                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8594                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8595                                                    OpVT,
8596                                                    SrcOp.getOperand(0)
8597                                                           .getOperand(0))));
8598       }
8599     }
8600   }
8601
8602   return DAG.getNode(ISD::BITCAST, dl, VT,
8603                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8604                                  DAG.getNode(ISD::BITCAST, dl,
8605                                              OpVT, SrcOp)));
8606 }
8607
8608 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8609 /// which could not be matched by any known target speficic shuffle
8610 static SDValue
8611 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8612
8613   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8614   if (NewOp.getNode())
8615     return NewOp;
8616
8617   MVT VT = SVOp->getSimpleValueType(0);
8618
8619   unsigned NumElems = VT.getVectorNumElements();
8620   unsigned NumLaneElems = NumElems / 2;
8621
8622   SDLoc dl(SVOp);
8623   MVT EltVT = VT.getVectorElementType();
8624   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8625   SDValue Output[2];
8626
8627   SmallVector<int, 16> Mask;
8628   for (unsigned l = 0; l < 2; ++l) {
8629     // Build a shuffle mask for the output, discovering on the fly which
8630     // input vectors to use as shuffle operands (recorded in InputUsed).
8631     // If building a suitable shuffle vector proves too hard, then bail
8632     // out with UseBuildVector set.
8633     bool UseBuildVector = false;
8634     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8635     unsigned LaneStart = l * NumLaneElems;
8636     for (unsigned i = 0; i != NumLaneElems; ++i) {
8637       // The mask element.  This indexes into the input.
8638       int Idx = SVOp->getMaskElt(i+LaneStart);
8639       if (Idx < 0) {
8640         // the mask element does not index into any input vector.
8641         Mask.push_back(-1);
8642         continue;
8643       }
8644
8645       // The input vector this mask element indexes into.
8646       int Input = Idx / NumLaneElems;
8647
8648       // Turn the index into an offset from the start of the input vector.
8649       Idx -= Input * NumLaneElems;
8650
8651       // Find or create a shuffle vector operand to hold this input.
8652       unsigned OpNo;
8653       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8654         if (InputUsed[OpNo] == Input)
8655           // This input vector is already an operand.
8656           break;
8657         if (InputUsed[OpNo] < 0) {
8658           // Create a new operand for this input vector.
8659           InputUsed[OpNo] = Input;
8660           break;
8661         }
8662       }
8663
8664       if (OpNo >= array_lengthof(InputUsed)) {
8665         // More than two input vectors used!  Give up on trying to create a
8666         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8667         UseBuildVector = true;
8668         break;
8669       }
8670
8671       // Add the mask index for the new shuffle vector.
8672       Mask.push_back(Idx + OpNo * NumLaneElems);
8673     }
8674
8675     if (UseBuildVector) {
8676       SmallVector<SDValue, 16> SVOps;
8677       for (unsigned i = 0; i != NumLaneElems; ++i) {
8678         // The mask element.  This indexes into the input.
8679         int Idx = SVOp->getMaskElt(i+LaneStart);
8680         if (Idx < 0) {
8681           SVOps.push_back(DAG.getUNDEF(EltVT));
8682           continue;
8683         }
8684
8685         // The input vector this mask element indexes into.
8686         int Input = Idx / NumElems;
8687
8688         // Turn the index into an offset from the start of the input vector.
8689         Idx -= Input * NumElems;
8690
8691         // Extract the vector element by hand.
8692         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8693                                     SVOp->getOperand(Input),
8694                                     DAG.getIntPtrConstant(Idx)));
8695       }
8696
8697       // Construct the output using a BUILD_VECTOR.
8698       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8699     } else if (InputUsed[0] < 0) {
8700       // No input vectors were used! The result is undefined.
8701       Output[l] = DAG.getUNDEF(NVT);
8702     } else {
8703       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8704                                         (InputUsed[0] % 2) * NumLaneElems,
8705                                         DAG, dl);
8706       // If only one input was used, use an undefined vector for the other.
8707       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8708         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8709                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8710       // At least one input vector was used. Create a new shuffle vector.
8711       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8712     }
8713
8714     Mask.clear();
8715   }
8716
8717   // Concatenate the result back
8718   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8719 }
8720
8721 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8722 /// 4 elements, and match them with several different shuffle types.
8723 static SDValue
8724 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8725   SDValue V1 = SVOp->getOperand(0);
8726   SDValue V2 = SVOp->getOperand(1);
8727   SDLoc dl(SVOp);
8728   MVT VT = SVOp->getSimpleValueType(0);
8729
8730   assert(VT.is128BitVector() && "Unsupported vector size");
8731
8732   std::pair<int, int> Locs[4];
8733   int Mask1[] = { -1, -1, -1, -1 };
8734   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8735
8736   unsigned NumHi = 0;
8737   unsigned NumLo = 0;
8738   for (unsigned i = 0; i != 4; ++i) {
8739     int Idx = PermMask[i];
8740     if (Idx < 0) {
8741       Locs[i] = std::make_pair(-1, -1);
8742     } else {
8743       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8744       if (Idx < 4) {
8745         Locs[i] = std::make_pair(0, NumLo);
8746         Mask1[NumLo] = Idx;
8747         NumLo++;
8748       } else {
8749         Locs[i] = std::make_pair(1, NumHi);
8750         if (2+NumHi < 4)
8751           Mask1[2+NumHi] = Idx;
8752         NumHi++;
8753       }
8754     }
8755   }
8756
8757   if (NumLo <= 2 && NumHi <= 2) {
8758     // If no more than two elements come from either vector. This can be
8759     // implemented with two shuffles. First shuffle gather the elements.
8760     // The second shuffle, which takes the first shuffle as both of its
8761     // vector operands, put the elements into the right order.
8762     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8763
8764     int Mask2[] = { -1, -1, -1, -1 };
8765
8766     for (unsigned i = 0; i != 4; ++i)
8767       if (Locs[i].first != -1) {
8768         unsigned Idx = (i < 2) ? 0 : 4;
8769         Idx += Locs[i].first * 2 + Locs[i].second;
8770         Mask2[i] = Idx;
8771       }
8772
8773     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8774   }
8775
8776   if (NumLo == 3 || NumHi == 3) {
8777     // Otherwise, we must have three elements from one vector, call it X, and
8778     // one element from the other, call it Y.  First, use a shufps to build an
8779     // intermediate vector with the one element from Y and the element from X
8780     // that will be in the same half in the final destination (the indexes don't
8781     // matter). Then, use a shufps to build the final vector, taking the half
8782     // containing the element from Y from the intermediate, and the other half
8783     // from X.
8784     if (NumHi == 3) {
8785       // Normalize it so the 3 elements come from V1.
8786       CommuteVectorShuffleMask(PermMask, 4);
8787       std::swap(V1, V2);
8788     }
8789
8790     // Find the element from V2.
8791     unsigned HiIndex;
8792     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8793       int Val = PermMask[HiIndex];
8794       if (Val < 0)
8795         continue;
8796       if (Val >= 4)
8797         break;
8798     }
8799
8800     Mask1[0] = PermMask[HiIndex];
8801     Mask1[1] = -1;
8802     Mask1[2] = PermMask[HiIndex^1];
8803     Mask1[3] = -1;
8804     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8805
8806     if (HiIndex >= 2) {
8807       Mask1[0] = PermMask[0];
8808       Mask1[1] = PermMask[1];
8809       Mask1[2] = HiIndex & 1 ? 6 : 4;
8810       Mask1[3] = HiIndex & 1 ? 4 : 6;
8811       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8812     }
8813
8814     Mask1[0] = HiIndex & 1 ? 2 : 0;
8815     Mask1[1] = HiIndex & 1 ? 0 : 2;
8816     Mask1[2] = PermMask[2];
8817     Mask1[3] = PermMask[3];
8818     if (Mask1[2] >= 0)
8819       Mask1[2] += 4;
8820     if (Mask1[3] >= 0)
8821       Mask1[3] += 4;
8822     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8823   }
8824
8825   // Break it into (shuffle shuffle_hi, shuffle_lo).
8826   int LoMask[] = { -1, -1, -1, -1 };
8827   int HiMask[] = { -1, -1, -1, -1 };
8828
8829   int *MaskPtr = LoMask;
8830   unsigned MaskIdx = 0;
8831   unsigned LoIdx = 0;
8832   unsigned HiIdx = 2;
8833   for (unsigned i = 0; i != 4; ++i) {
8834     if (i == 2) {
8835       MaskPtr = HiMask;
8836       MaskIdx = 1;
8837       LoIdx = 0;
8838       HiIdx = 2;
8839     }
8840     int Idx = PermMask[i];
8841     if (Idx < 0) {
8842       Locs[i] = std::make_pair(-1, -1);
8843     } else if (Idx < 4) {
8844       Locs[i] = std::make_pair(MaskIdx, LoIdx);
8845       MaskPtr[LoIdx] = Idx;
8846       LoIdx++;
8847     } else {
8848       Locs[i] = std::make_pair(MaskIdx, HiIdx);
8849       MaskPtr[HiIdx] = Idx;
8850       HiIdx++;
8851     }
8852   }
8853
8854   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8855   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8856   int MaskOps[] = { -1, -1, -1, -1 };
8857   for (unsigned i = 0; i != 4; ++i)
8858     if (Locs[i].first != -1)
8859       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8860   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8861 }
8862
8863 static bool MayFoldVectorLoad(SDValue V) {
8864   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8865     V = V.getOperand(0);
8866
8867   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8868     V = V.getOperand(0);
8869   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8870       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8871     // BUILD_VECTOR (load), undef
8872     V = V.getOperand(0);
8873
8874   return MayFoldLoad(V);
8875 }
8876
8877 static
8878 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8879   MVT VT = Op.getSimpleValueType();
8880
8881   // Canonizalize to v2f64.
8882   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8883   return DAG.getNode(ISD::BITCAST, dl, VT,
8884                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8885                                           V1, DAG));
8886 }
8887
8888 static
8889 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8890                         bool HasSSE2) {
8891   SDValue V1 = Op.getOperand(0);
8892   SDValue V2 = Op.getOperand(1);
8893   MVT VT = Op.getSimpleValueType();
8894
8895   assert(VT != MVT::v2i64 && "unsupported shuffle type");
8896
8897   if (HasSSE2 && VT == MVT::v2f64)
8898     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8899
8900   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8901   return DAG.getNode(ISD::BITCAST, dl, VT,
8902                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8903                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8904                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8905 }
8906
8907 static
8908 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8909   SDValue V1 = Op.getOperand(0);
8910   SDValue V2 = Op.getOperand(1);
8911   MVT VT = Op.getSimpleValueType();
8912
8913   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8914          "unsupported shuffle type");
8915
8916   if (V2.getOpcode() == ISD::UNDEF)
8917     V2 = V1;
8918
8919   // v4i32 or v4f32
8920   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8921 }
8922
8923 static
8924 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8925   SDValue V1 = Op.getOperand(0);
8926   SDValue V2 = Op.getOperand(1);
8927   MVT VT = Op.getSimpleValueType();
8928   unsigned NumElems = VT.getVectorNumElements();
8929
8930   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8931   // operand of these instructions is only memory, so check if there's a
8932   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8933   // same masks.
8934   bool CanFoldLoad = false;
8935
8936   // Trivial case, when V2 comes from a load.
8937   if (MayFoldVectorLoad(V2))
8938     CanFoldLoad = true;
8939
8940   // When V1 is a load, it can be folded later into a store in isel, example:
8941   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8942   //    turns into:
8943   //  (MOVLPSmr addr:$src1, VR128:$src2)
8944   // So, recognize this potential and also use MOVLPS or MOVLPD
8945   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8946     CanFoldLoad = true;
8947
8948   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8949   if (CanFoldLoad) {
8950     if (HasSSE2 && NumElems == 2)
8951       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
8952
8953     if (NumElems == 4)
8954       // If we don't care about the second element, proceed to use movss.
8955       if (SVOp->getMaskElt(1) != -1)
8956         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
8957   }
8958
8959   // movl and movlp will both match v2i64, but v2i64 is never matched by
8960   // movl earlier because we make it strict to avoid messing with the movlp load
8961   // folding logic (see the code above getMOVLP call). Match it here then,
8962   // this is horrible, but will stay like this until we move all shuffle
8963   // matching to x86 specific nodes. Note that for the 1st condition all
8964   // types are matched with movsd.
8965   if (HasSSE2) {
8966     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
8967     // as to remove this logic from here, as much as possible
8968     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
8969       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8970     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8971   }
8972
8973   assert(VT != MVT::v4i32 && "unsupported shuffle type");
8974
8975   // Invert the operand order and use SHUFPS to match it.
8976   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
8977                               getShuffleSHUFImmediate(SVOp), DAG);
8978 }
8979
8980 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
8981                                          SelectionDAG &DAG) {
8982   SDLoc dl(Load);
8983   MVT VT = Load->getSimpleValueType(0);
8984   MVT EVT = VT.getVectorElementType();
8985   SDValue Addr = Load->getOperand(1);
8986   SDValue NewAddr = DAG.getNode(
8987       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
8988       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
8989
8990   SDValue NewLoad =
8991       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
8992                   DAG.getMachineFunction().getMachineMemOperand(
8993                       Load->getMemOperand(), 0, EVT.getStoreSize()));
8994   return NewLoad;
8995 }
8996
8997 // It is only safe to call this function if isINSERTPSMask is true for
8998 // this shufflevector mask.
8999 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9000                            SelectionDAG &DAG) {
9001   // Generate an insertps instruction when inserting an f32 from memory onto a
9002   // v4f32 or when copying a member from one v4f32 to another.
9003   // We also use it for transferring i32 from one register to another,
9004   // since it simply copies the same bits.
9005   // If we're transferring an i32 from memory to a specific element in a
9006   // register, we output a generic DAG that will match the PINSRD
9007   // instruction.
9008   MVT VT = SVOp->getSimpleValueType(0);
9009   MVT EVT = VT.getVectorElementType();
9010   SDValue V1 = SVOp->getOperand(0);
9011   SDValue V2 = SVOp->getOperand(1);
9012   auto Mask = SVOp->getMask();
9013   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9014          "unsupported vector type for insertps/pinsrd");
9015
9016   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9017   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9018   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9019
9020   SDValue From;
9021   SDValue To;
9022   unsigned DestIndex;
9023   if (FromV1 == 1) {
9024     From = V1;
9025     To = V2;
9026     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9027                 Mask.begin();
9028   } else {
9029     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9030            "More than one element from V1 and from V2, or no elements from one "
9031            "of the vectors. This case should not have returned true from "
9032            "isINSERTPSMask");
9033     From = V2;
9034     To = V1;
9035     DestIndex =
9036         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9037   }
9038
9039   unsigned SrcIndex = Mask[DestIndex] % 4;
9040   if (MayFoldLoad(From)) {
9041     // Trivial case, when From comes from a load and is only used by the
9042     // shuffle. Make it use insertps from the vector that we need from that
9043     // load.
9044     SDValue NewLoad =
9045         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9046     if (!NewLoad.getNode())
9047       return SDValue();
9048
9049     if (EVT == MVT::f32) {
9050       // Create this as a scalar to vector to match the instruction pattern.
9051       SDValue LoadScalarToVector =
9052           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9053       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9054       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9055                          InsertpsMask);
9056     } else { // EVT == MVT::i32
9057       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9058       // instruction, to match the PINSRD instruction, which loads an i32 to a
9059       // certain vector element.
9060       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9061                          DAG.getConstant(DestIndex, MVT::i32));
9062     }
9063   }
9064
9065   // Vector-element-to-vector
9066   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9067   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9068 }
9069
9070 // Reduce a vector shuffle to zext.
9071 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9072                                     SelectionDAG &DAG) {
9073   // PMOVZX is only available from SSE41.
9074   if (!Subtarget->hasSSE41())
9075     return SDValue();
9076
9077   MVT VT = Op.getSimpleValueType();
9078
9079   // Only AVX2 support 256-bit vector integer extending.
9080   if (!Subtarget->hasInt256() && VT.is256BitVector())
9081     return SDValue();
9082
9083   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9084   SDLoc DL(Op);
9085   SDValue V1 = Op.getOperand(0);
9086   SDValue V2 = Op.getOperand(1);
9087   unsigned NumElems = VT.getVectorNumElements();
9088
9089   // Extending is an unary operation and the element type of the source vector
9090   // won't be equal to or larger than i64.
9091   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9092       VT.getVectorElementType() == MVT::i64)
9093     return SDValue();
9094
9095   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9096   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9097   while ((1U << Shift) < NumElems) {
9098     if (SVOp->getMaskElt(1U << Shift) == 1)
9099       break;
9100     Shift += 1;
9101     // The maximal ratio is 8, i.e. from i8 to i64.
9102     if (Shift > 3)
9103       return SDValue();
9104   }
9105
9106   // Check the shuffle mask.
9107   unsigned Mask = (1U << Shift) - 1;
9108   for (unsigned i = 0; i != NumElems; ++i) {
9109     int EltIdx = SVOp->getMaskElt(i);
9110     if ((i & Mask) != 0 && EltIdx != -1)
9111       return SDValue();
9112     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9113       return SDValue();
9114   }
9115
9116   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9117   MVT NeVT = MVT::getIntegerVT(NBits);
9118   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9119
9120   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9121     return SDValue();
9122
9123   // Simplify the operand as it's prepared to be fed into shuffle.
9124   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9125   if (V1.getOpcode() == ISD::BITCAST &&
9126       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9127       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9128       V1.getOperand(0).getOperand(0)
9129         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9130     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9131     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9132     ConstantSDNode *CIdx =
9133       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9134     // If it's foldable, i.e. normal load with single use, we will let code
9135     // selection to fold it. Otherwise, we will short the conversion sequence.
9136     if (CIdx && CIdx->getZExtValue() == 0 &&
9137         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9138       MVT FullVT = V.getSimpleValueType();
9139       MVT V1VT = V1.getSimpleValueType();
9140       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9141         // The "ext_vec_elt" node is wider than the result node.
9142         // In this case we should extract subvector from V.
9143         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9144         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9145         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9146                                         FullVT.getVectorNumElements()/Ratio);
9147         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9148                         DAG.getIntPtrConstant(0));
9149       }
9150       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9151     }
9152   }
9153
9154   return DAG.getNode(ISD::BITCAST, DL, VT,
9155                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9156 }
9157
9158 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9159                                       SelectionDAG &DAG) {
9160   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9161   MVT VT = Op.getSimpleValueType();
9162   SDLoc dl(Op);
9163   SDValue V1 = Op.getOperand(0);
9164   SDValue V2 = Op.getOperand(1);
9165
9166   if (isZeroShuffle(SVOp))
9167     return getZeroVector(VT, Subtarget, DAG, dl);
9168
9169   // Handle splat operations
9170   if (SVOp->isSplat()) {
9171     // Use vbroadcast whenever the splat comes from a foldable load
9172     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9173     if (Broadcast.getNode())
9174       return Broadcast;
9175   }
9176
9177   // Check integer expanding shuffles.
9178   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9179   if (NewOp.getNode())
9180     return NewOp;
9181
9182   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9183   // do it!
9184   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9185       VT == MVT::v32i8) {
9186     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9187     if (NewOp.getNode())
9188       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9189   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9190     // FIXME: Figure out a cleaner way to do this.
9191     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9192       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9193       if (NewOp.getNode()) {
9194         MVT NewVT = NewOp.getSimpleValueType();
9195         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9196                                NewVT, true, false))
9197           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9198                               dl);
9199       }
9200     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9201       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9202       if (NewOp.getNode()) {
9203         MVT NewVT = NewOp.getSimpleValueType();
9204         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9205           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9206                               dl);
9207       }
9208     }
9209   }
9210   return SDValue();
9211 }
9212
9213 SDValue
9214 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9215   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9216   SDValue V1 = Op.getOperand(0);
9217   SDValue V2 = Op.getOperand(1);
9218   MVT VT = Op.getSimpleValueType();
9219   SDLoc dl(Op);
9220   unsigned NumElems = VT.getVectorNumElements();
9221   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9222   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9223   bool V1IsSplat = false;
9224   bool V2IsSplat = false;
9225   bool HasSSE2 = Subtarget->hasSSE2();
9226   bool HasFp256    = Subtarget->hasFp256();
9227   bool HasInt256   = Subtarget->hasInt256();
9228   MachineFunction &MF = DAG.getMachineFunction();
9229   bool OptForSize = MF.getFunction()->getAttributes().
9230     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9231
9232   // Check if we should use the experimental vector shuffle lowering. If so,
9233   // delegate completely to that code path.
9234   if (ExperimentalVectorShuffleLowering)
9235     return lowerVectorShuffle(Op, Subtarget, DAG);
9236
9237   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9238
9239   if (V1IsUndef && V2IsUndef)
9240     return DAG.getUNDEF(VT);
9241
9242   // When we create a shuffle node we put the UNDEF node to second operand,
9243   // but in some cases the first operand may be transformed to UNDEF.
9244   // In this case we should just commute the node.
9245   if (V1IsUndef)
9246     return CommuteVectorShuffle(SVOp, DAG);
9247
9248   // Vector shuffle lowering takes 3 steps:
9249   //
9250   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9251   //    narrowing and commutation of operands should be handled.
9252   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9253   //    shuffle nodes.
9254   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9255   //    so the shuffle can be broken into other shuffles and the legalizer can
9256   //    try the lowering again.
9257   //
9258   // The general idea is that no vector_shuffle operation should be left to
9259   // be matched during isel, all of them must be converted to a target specific
9260   // node here.
9261
9262   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9263   // narrowing and commutation of operands should be handled. The actual code
9264   // doesn't include all of those, work in progress...
9265   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9266   if (NewOp.getNode())
9267     return NewOp;
9268
9269   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9270
9271   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9272   // unpckh_undef). Only use pshufd if speed is more important than size.
9273   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9274     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9275   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9276     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9277
9278   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9279       V2IsUndef && MayFoldVectorLoad(V1))
9280     return getMOVDDup(Op, dl, V1, DAG);
9281
9282   if (isMOVHLPS_v_undef_Mask(M, VT))
9283     return getMOVHighToLow(Op, dl, DAG);
9284
9285   // Use to match splats
9286   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9287       (VT == MVT::v2f64 || VT == MVT::v2i64))
9288     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9289
9290   if (isPSHUFDMask(M, VT)) {
9291     // The actual implementation will match the mask in the if above and then
9292     // during isel it can match several different instructions, not only pshufd
9293     // as its name says, sad but true, emulate the behavior for now...
9294     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9295       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9296
9297     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9298
9299     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9300       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9301
9302     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9303       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9304                                   DAG);
9305
9306     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9307                                 TargetMask, DAG);
9308   }
9309
9310   if (isPALIGNRMask(M, VT, Subtarget))
9311     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9312                                 getShufflePALIGNRImmediate(SVOp),
9313                                 DAG);
9314
9315   // Check if this can be converted into a logical shift.
9316   bool isLeft = false;
9317   unsigned ShAmt = 0;
9318   SDValue ShVal;
9319   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9320   if (isShift && ShVal.hasOneUse()) {
9321     // If the shifted value has multiple uses, it may be cheaper to use
9322     // v_set0 + movlhps or movhlps, etc.
9323     MVT EltVT = VT.getVectorElementType();
9324     ShAmt *= EltVT.getSizeInBits();
9325     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9326   }
9327
9328   if (isMOVLMask(M, VT)) {
9329     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9330       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9331     if (!isMOVLPMask(M, VT)) {
9332       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9333         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9334
9335       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9336         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9337     }
9338   }
9339
9340   // FIXME: fold these into legal mask.
9341   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9342     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9343
9344   if (isMOVHLPSMask(M, VT))
9345     return getMOVHighToLow(Op, dl, DAG);
9346
9347   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9348     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9349
9350   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9351     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9352
9353   if (isMOVLPMask(M, VT))
9354     return getMOVLP(Op, dl, DAG, HasSSE2);
9355
9356   if (ShouldXformToMOVHLPS(M, VT) ||
9357       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9358     return CommuteVectorShuffle(SVOp, DAG);
9359
9360   if (isShift) {
9361     // No better options. Use a vshldq / vsrldq.
9362     MVT EltVT = VT.getVectorElementType();
9363     ShAmt *= EltVT.getSizeInBits();
9364     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9365   }
9366
9367   bool Commuted = false;
9368   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9369   // 1,1,1,1 -> v8i16 though.
9370   BitVector UndefElements;
9371   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9372     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9373       V1IsSplat = true;
9374   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9375     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9376       V2IsSplat = true;
9377
9378   // Canonicalize the splat or undef, if present, to be on the RHS.
9379   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9380     CommuteVectorShuffleMask(M, NumElems);
9381     std::swap(V1, V2);
9382     std::swap(V1IsSplat, V2IsSplat);
9383     Commuted = true;
9384   }
9385
9386   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9387     // Shuffling low element of v1 into undef, just return v1.
9388     if (V2IsUndef)
9389       return V1;
9390     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9391     // the instruction selector will not match, so get a canonical MOVL with
9392     // swapped operands to undo the commute.
9393     return getMOVL(DAG, dl, VT, V2, V1);
9394   }
9395
9396   if (isUNPCKLMask(M, VT, HasInt256))
9397     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9398
9399   if (isUNPCKHMask(M, VT, HasInt256))
9400     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9401
9402   if (V2IsSplat) {
9403     // Normalize mask so all entries that point to V2 points to its first
9404     // element then try to match unpck{h|l} again. If match, return a
9405     // new vector_shuffle with the corrected mask.p
9406     SmallVector<int, 8> NewMask(M.begin(), M.end());
9407     NormalizeMask(NewMask, NumElems);
9408     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9409       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9410     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9411       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9412   }
9413
9414   if (Commuted) {
9415     // Commute is back and try unpck* again.
9416     // FIXME: this seems wrong.
9417     CommuteVectorShuffleMask(M, NumElems);
9418     std::swap(V1, V2);
9419     std::swap(V1IsSplat, V2IsSplat);
9420
9421     if (isUNPCKLMask(M, VT, HasInt256))
9422       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9423
9424     if (isUNPCKHMask(M, VT, HasInt256))
9425       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9426   }
9427
9428   // Normalize the node to match x86 shuffle ops if needed
9429   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9430     return CommuteVectorShuffle(SVOp, DAG);
9431
9432   // The checks below are all present in isShuffleMaskLegal, but they are
9433   // inlined here right now to enable us to directly emit target specific
9434   // nodes, and remove one by one until they don't return Op anymore.
9435
9436   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9437       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9438     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9439       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9440   }
9441
9442   if (isPSHUFHWMask(M, VT, HasInt256))
9443     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9444                                 getShufflePSHUFHWImmediate(SVOp),
9445                                 DAG);
9446
9447   if (isPSHUFLWMask(M, VT, HasInt256))
9448     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9449                                 getShufflePSHUFLWImmediate(SVOp),
9450                                 DAG);
9451
9452   unsigned MaskValue;
9453   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9454                   &MaskValue))
9455     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9456
9457   if (isSHUFPMask(M, VT))
9458     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9459                                 getShuffleSHUFImmediate(SVOp), DAG);
9460
9461   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9462     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9463   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9464     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9465
9466   //===--------------------------------------------------------------------===//
9467   // Generate target specific nodes for 128 or 256-bit shuffles only
9468   // supported in the AVX instruction set.
9469   //
9470
9471   // Handle VMOVDDUPY permutations
9472   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9473     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9474
9475   // Handle VPERMILPS/D* permutations
9476   if (isVPERMILPMask(M, VT)) {
9477     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9478       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9479                                   getShuffleSHUFImmediate(SVOp), DAG);
9480     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9481                                 getShuffleSHUFImmediate(SVOp), DAG);
9482   }
9483
9484   unsigned Idx;
9485   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9486     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9487                               Idx*(NumElems/2), DAG, dl);
9488
9489   // Handle VPERM2F128/VPERM2I128 permutations
9490   if (isVPERM2X128Mask(M, VT, HasFp256))
9491     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9492                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9493
9494   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9495     return getINSERTPS(SVOp, dl, DAG);
9496
9497   unsigned Imm8;
9498   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9499     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9500
9501   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9502       VT.is512BitVector()) {
9503     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9504     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9505     SmallVector<SDValue, 16> permclMask;
9506     for (unsigned i = 0; i != NumElems; ++i) {
9507       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9508     }
9509
9510     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9511     if (V2IsUndef)
9512       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9513       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9514                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9515     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9516                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9517   }
9518
9519   //===--------------------------------------------------------------------===//
9520   // Since no target specific shuffle was selected for this generic one,
9521   // lower it into other known shuffles. FIXME: this isn't true yet, but
9522   // this is the plan.
9523   //
9524
9525   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9526   if (VT == MVT::v8i16) {
9527     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9528     if (NewOp.getNode())
9529       return NewOp;
9530   }
9531
9532   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9533     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9534     if (NewOp.getNode())
9535       return NewOp;
9536   }
9537
9538   if (VT == MVT::v16i8) {
9539     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9540     if (NewOp.getNode())
9541       return NewOp;
9542   }
9543
9544   if (VT == MVT::v32i8) {
9545     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9546     if (NewOp.getNode())
9547       return NewOp;
9548   }
9549
9550   // Handle all 128-bit wide vectors with 4 elements, and match them with
9551   // several different shuffle types.
9552   if (NumElems == 4 && VT.is128BitVector())
9553     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9554
9555   // Handle general 256-bit shuffles
9556   if (VT.is256BitVector())
9557     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9558
9559   return SDValue();
9560 }
9561
9562 // This function assumes its argument is a BUILD_VECTOR of constants or
9563 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9564 // true.
9565 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9566                                     unsigned &MaskValue) {
9567   MaskValue = 0;
9568   unsigned NumElems = BuildVector->getNumOperands();
9569   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9570   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9571   unsigned NumElemsInLane = NumElems / NumLanes;
9572
9573   // Blend for v16i16 should be symetric for the both lanes.
9574   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9575     SDValue EltCond = BuildVector->getOperand(i);
9576     SDValue SndLaneEltCond =
9577         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9578
9579     int Lane1Cond = -1, Lane2Cond = -1;
9580     if (isa<ConstantSDNode>(EltCond))
9581       Lane1Cond = !isZero(EltCond);
9582     if (isa<ConstantSDNode>(SndLaneEltCond))
9583       Lane2Cond = !isZero(SndLaneEltCond);
9584
9585     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9586       // Lane1Cond != 0, means we want the first argument.
9587       // Lane1Cond == 0, means we want the second argument.
9588       // The encoding of this argument is 0 for the first argument, 1
9589       // for the second. Therefore, invert the condition.
9590       MaskValue |= !Lane1Cond << i;
9591     else if (Lane1Cond < 0)
9592       MaskValue |= !Lane2Cond << i;
9593     else
9594       return false;
9595   }
9596   return true;
9597 }
9598
9599 // Try to lower a vselect node into a simple blend instruction.
9600 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9601                                    SelectionDAG &DAG) {
9602   SDValue Cond = Op.getOperand(0);
9603   SDValue LHS = Op.getOperand(1);
9604   SDValue RHS = Op.getOperand(2);
9605   SDLoc dl(Op);
9606   MVT VT = Op.getSimpleValueType();
9607   MVT EltVT = VT.getVectorElementType();
9608   unsigned NumElems = VT.getVectorNumElements();
9609
9610   // There is no blend with immediate in AVX-512.
9611   if (VT.is512BitVector())
9612     return SDValue();
9613
9614   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9615     return SDValue();
9616   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9617     return SDValue();
9618
9619   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9620     return SDValue();
9621
9622   // Check the mask for BLEND and build the value.
9623   unsigned MaskValue = 0;
9624   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9625     return SDValue();
9626
9627   // Convert i32 vectors to floating point if it is not AVX2.
9628   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9629   MVT BlendVT = VT;
9630   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9631     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9632                                NumElems);
9633     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9634     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9635   }
9636
9637   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9638                             DAG.getConstant(MaskValue, MVT::i32));
9639   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9640 }
9641
9642 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9643   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9644   if (BlendOp.getNode())
9645     return BlendOp;
9646
9647   // Some types for vselect were previously set to Expand, not Legal or
9648   // Custom. Return an empty SDValue so we fall-through to Expand, after
9649   // the Custom lowering phase.
9650   MVT VT = Op.getSimpleValueType();
9651   switch (VT.SimpleTy) {
9652   default:
9653     break;
9654   case MVT::v8i16:
9655   case MVT::v16i16:
9656     return SDValue();
9657   }
9658
9659   // We couldn't create a "Blend with immediate" node.
9660   // This node should still be legal, but we'll have to emit a blendv*
9661   // instruction.
9662   return Op;
9663 }
9664
9665 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9666   MVT VT = Op.getSimpleValueType();
9667   SDLoc dl(Op);
9668
9669   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9670     return SDValue();
9671
9672   if (VT.getSizeInBits() == 8) {
9673     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9674                                   Op.getOperand(0), Op.getOperand(1));
9675     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9676                                   DAG.getValueType(VT));
9677     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9678   }
9679
9680   if (VT.getSizeInBits() == 16) {
9681     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9682     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9683     if (Idx == 0)
9684       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9685                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9686                                      DAG.getNode(ISD::BITCAST, dl,
9687                                                  MVT::v4i32,
9688                                                  Op.getOperand(0)),
9689                                      Op.getOperand(1)));
9690     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9691                                   Op.getOperand(0), Op.getOperand(1));
9692     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9693                                   DAG.getValueType(VT));
9694     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9695   }
9696
9697   if (VT == MVT::f32) {
9698     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9699     // the result back to FR32 register. It's only worth matching if the
9700     // result has a single use which is a store or a bitcast to i32.  And in
9701     // the case of a store, it's not worth it if the index is a constant 0,
9702     // because a MOVSSmr can be used instead, which is smaller and faster.
9703     if (!Op.hasOneUse())
9704       return SDValue();
9705     SDNode *User = *Op.getNode()->use_begin();
9706     if ((User->getOpcode() != ISD::STORE ||
9707          (isa<ConstantSDNode>(Op.getOperand(1)) &&
9708           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9709         (User->getOpcode() != ISD::BITCAST ||
9710          User->getValueType(0) != MVT::i32))
9711       return SDValue();
9712     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9713                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9714                                               Op.getOperand(0)),
9715                                               Op.getOperand(1));
9716     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9717   }
9718
9719   if (VT == MVT::i32 || VT == MVT::i64) {
9720     // ExtractPS/pextrq works with constant index.
9721     if (isa<ConstantSDNode>(Op.getOperand(1)))
9722       return Op;
9723   }
9724   return SDValue();
9725 }
9726
9727 /// Extract one bit from mask vector, like v16i1 or v8i1.
9728 /// AVX-512 feature.
9729 SDValue
9730 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9731   SDValue Vec = Op.getOperand(0);
9732   SDLoc dl(Vec);
9733   MVT VecVT = Vec.getSimpleValueType();
9734   SDValue Idx = Op.getOperand(1);
9735   MVT EltVT = Op.getSimpleValueType();
9736
9737   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9738
9739   // variable index can't be handled in mask registers,
9740   // extend vector to VR512
9741   if (!isa<ConstantSDNode>(Idx)) {
9742     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9743     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9744     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9745                               ExtVT.getVectorElementType(), Ext, Idx);
9746     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9747   }
9748
9749   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9750   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9751   unsigned MaxSift = rc->getSize()*8 - 1;
9752   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9753                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9754   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9755                     DAG.getConstant(MaxSift, MVT::i8));
9756   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9757                        DAG.getIntPtrConstant(0));
9758 }
9759
9760 SDValue
9761 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9762                                            SelectionDAG &DAG) const {
9763   SDLoc dl(Op);
9764   SDValue Vec = Op.getOperand(0);
9765   MVT VecVT = Vec.getSimpleValueType();
9766   SDValue Idx = Op.getOperand(1);
9767
9768   if (Op.getSimpleValueType() == MVT::i1)
9769     return ExtractBitFromMaskVector(Op, DAG);
9770
9771   if (!isa<ConstantSDNode>(Idx)) {
9772     if (VecVT.is512BitVector() ||
9773         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9774          VecVT.getVectorElementType().getSizeInBits() == 32)) {
9775
9776       MVT MaskEltVT =
9777         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9778       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9779                                     MaskEltVT.getSizeInBits());
9780
9781       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9782       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9783                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
9784                                 Idx, DAG.getConstant(0, getPointerTy()));
9785       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9786       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9787                         Perm, DAG.getConstant(0, getPointerTy()));
9788     }
9789     return SDValue();
9790   }
9791
9792   // If this is a 256-bit vector result, first extract the 128-bit vector and
9793   // then extract the element from the 128-bit vector.
9794   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9795
9796     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9797     // Get the 128-bit vector.
9798     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9799     MVT EltVT = VecVT.getVectorElementType();
9800
9801     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9802
9803     //if (IdxVal >= NumElems/2)
9804     //  IdxVal -= NumElems/2;
9805     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9806     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9807                        DAG.getConstant(IdxVal, MVT::i32));
9808   }
9809
9810   assert(VecVT.is128BitVector() && "Unexpected vector length");
9811
9812   if (Subtarget->hasSSE41()) {
9813     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9814     if (Res.getNode())
9815       return Res;
9816   }
9817
9818   MVT VT = Op.getSimpleValueType();
9819   // TODO: handle v16i8.
9820   if (VT.getSizeInBits() == 16) {
9821     SDValue Vec = Op.getOperand(0);
9822     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9823     if (Idx == 0)
9824       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9825                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9826                                      DAG.getNode(ISD::BITCAST, dl,
9827                                                  MVT::v4i32, Vec),
9828                                      Op.getOperand(1)));
9829     // Transform it so it match pextrw which produces a 32-bit result.
9830     MVT EltVT = MVT::i32;
9831     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9832                                   Op.getOperand(0), Op.getOperand(1));
9833     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9834                                   DAG.getValueType(VT));
9835     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9836   }
9837
9838   if (VT.getSizeInBits() == 32) {
9839     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9840     if (Idx == 0)
9841       return Op;
9842
9843     // SHUFPS the element to the lowest double word, then movss.
9844     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9845     MVT VVT = Op.getOperand(0).getSimpleValueType();
9846     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9847                                        DAG.getUNDEF(VVT), Mask);
9848     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9849                        DAG.getIntPtrConstant(0));
9850   }
9851
9852   if (VT.getSizeInBits() == 64) {
9853     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9854     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9855     //        to match extract_elt for f64.
9856     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9857     if (Idx == 0)
9858       return Op;
9859
9860     // UNPCKHPD the element to the lowest double word, then movsd.
9861     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9862     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9863     int Mask[2] = { 1, -1 };
9864     MVT VVT = Op.getOperand(0).getSimpleValueType();
9865     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9866                                        DAG.getUNDEF(VVT), Mask);
9867     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9868                        DAG.getIntPtrConstant(0));
9869   }
9870
9871   return SDValue();
9872 }
9873
9874 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9875   MVT VT = Op.getSimpleValueType();
9876   MVT EltVT = VT.getVectorElementType();
9877   SDLoc dl(Op);
9878
9879   SDValue N0 = Op.getOperand(0);
9880   SDValue N1 = Op.getOperand(1);
9881   SDValue N2 = Op.getOperand(2);
9882
9883   if (!VT.is128BitVector())
9884     return SDValue();
9885
9886   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9887       isa<ConstantSDNode>(N2)) {
9888     unsigned Opc;
9889     if (VT == MVT::v8i16)
9890       Opc = X86ISD::PINSRW;
9891     else if (VT == MVT::v16i8)
9892       Opc = X86ISD::PINSRB;
9893     else
9894       Opc = X86ISD::PINSRB;
9895
9896     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9897     // argument.
9898     if (N1.getValueType() != MVT::i32)
9899       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9900     if (N2.getValueType() != MVT::i32)
9901       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9902     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9903   }
9904
9905   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9906     // Bits [7:6] of the constant are the source select.  This will always be
9907     //  zero here.  The DAG Combiner may combine an extract_elt index into these
9908     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
9909     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
9910     // Bits [5:4] of the constant are the destination select.  This is the
9911     //  value of the incoming immediate.
9912     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
9913     //   combine either bitwise AND or insert of float 0.0 to set these bits.
9914     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9915     // Create this as a scalar to vector..
9916     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9917     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9918   }
9919
9920   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9921     // PINSR* works with constant index.
9922     return Op;
9923   }
9924   return SDValue();
9925 }
9926
9927 /// Insert one bit to mask vector, like v16i1 or v8i1.
9928 /// AVX-512 feature.
9929 SDValue 
9930 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9931   SDLoc dl(Op);
9932   SDValue Vec = Op.getOperand(0);
9933   SDValue Elt = Op.getOperand(1);
9934   SDValue Idx = Op.getOperand(2);
9935   MVT VecVT = Vec.getSimpleValueType();
9936
9937   if (!isa<ConstantSDNode>(Idx)) {
9938     // Non constant index. Extend source and destination,
9939     // insert element and then truncate the result.
9940     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9941     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
9942     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
9943       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9944       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9945     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9946   }
9947
9948   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9949   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
9950   if (Vec.getOpcode() == ISD::UNDEF)
9951     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9952                        DAG.getConstant(IdxVal, MVT::i8));
9953   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9954   unsigned MaxSift = rc->getSize()*8 - 1;
9955   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9956                     DAG.getConstant(MaxSift, MVT::i8));
9957   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
9958                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9959   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
9960 }
9961 SDValue
9962 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
9963   MVT VT = Op.getSimpleValueType();
9964   MVT EltVT = VT.getVectorElementType();
9965   
9966   if (EltVT == MVT::i1)
9967     return InsertBitToMaskVector(Op, DAG);
9968
9969   SDLoc dl(Op);
9970   SDValue N0 = Op.getOperand(0);
9971   SDValue N1 = Op.getOperand(1);
9972   SDValue N2 = Op.getOperand(2);
9973
9974   // If this is a 256-bit vector result, first extract the 128-bit vector,
9975   // insert the element into the extracted half and then place it back.
9976   if (VT.is256BitVector() || VT.is512BitVector()) {
9977     if (!isa<ConstantSDNode>(N2))
9978       return SDValue();
9979
9980     // Get the desired 128-bit vector half.
9981     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
9982     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
9983
9984     // Insert the element into the desired half.
9985     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
9986     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
9987
9988     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
9989                     DAG.getConstant(IdxIn128, MVT::i32));
9990
9991     // Insert the changed part back to the 256-bit vector
9992     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
9993   }
9994
9995   if (Subtarget->hasSSE41())
9996     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
9997
9998   if (EltVT == MVT::i8)
9999     return SDValue();
10000
10001   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10002     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10003     // as its second argument.
10004     if (N1.getValueType() != MVT::i32)
10005       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10006     if (N2.getValueType() != MVT::i32)
10007       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10008     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10009   }
10010   return SDValue();
10011 }
10012
10013 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10014   SDLoc dl(Op);
10015   MVT OpVT = Op.getSimpleValueType();
10016
10017   // If this is a 256-bit vector result, first insert into a 128-bit
10018   // vector and then insert into the 256-bit vector.
10019   if (!OpVT.is128BitVector()) {
10020     // Insert into a 128-bit vector.
10021     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10022     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10023                                  OpVT.getVectorNumElements() / SizeFactor);
10024
10025     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10026
10027     // Insert the 128-bit vector.
10028     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10029   }
10030
10031   if (OpVT == MVT::v1i64 &&
10032       Op.getOperand(0).getValueType() == MVT::i64)
10033     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10034
10035   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10036   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10037   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10038                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10039 }
10040
10041 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10042 // a simple subregister reference or explicit instructions to grab
10043 // upper bits of a vector.
10044 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10045                                       SelectionDAG &DAG) {
10046   SDLoc dl(Op);
10047   SDValue In =  Op.getOperand(0);
10048   SDValue Idx = Op.getOperand(1);
10049   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10050   MVT ResVT   = Op.getSimpleValueType();
10051   MVT InVT    = In.getSimpleValueType();
10052
10053   if (Subtarget->hasFp256()) {
10054     if (ResVT.is128BitVector() &&
10055         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10056         isa<ConstantSDNode>(Idx)) {
10057       return Extract128BitVector(In, IdxVal, DAG, dl);
10058     }
10059     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10060         isa<ConstantSDNode>(Idx)) {
10061       return Extract256BitVector(In, IdxVal, DAG, dl);
10062     }
10063   }
10064   return SDValue();
10065 }
10066
10067 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10068 // simple superregister reference or explicit instructions to insert
10069 // the upper bits of a vector.
10070 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10071                                      SelectionDAG &DAG) {
10072   if (Subtarget->hasFp256()) {
10073     SDLoc dl(Op.getNode());
10074     SDValue Vec = Op.getNode()->getOperand(0);
10075     SDValue SubVec = Op.getNode()->getOperand(1);
10076     SDValue Idx = Op.getNode()->getOperand(2);
10077
10078     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10079          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10080         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10081         isa<ConstantSDNode>(Idx)) {
10082       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10083       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10084     }
10085
10086     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10087         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10088         isa<ConstantSDNode>(Idx)) {
10089       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10090       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10091     }
10092   }
10093   return SDValue();
10094 }
10095
10096 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10097 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10098 // one of the above mentioned nodes. It has to be wrapped because otherwise
10099 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10100 // be used to form addressing mode. These wrapped nodes will be selected
10101 // into MOV32ri.
10102 SDValue
10103 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10104   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10105
10106   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10107   // global base reg.
10108   unsigned char OpFlag = 0;
10109   unsigned WrapperKind = X86ISD::Wrapper;
10110   CodeModel::Model M = DAG.getTarget().getCodeModel();
10111
10112   if (Subtarget->isPICStyleRIPRel() &&
10113       (M == CodeModel::Small || M == CodeModel::Kernel))
10114     WrapperKind = X86ISD::WrapperRIP;
10115   else if (Subtarget->isPICStyleGOT())
10116     OpFlag = X86II::MO_GOTOFF;
10117   else if (Subtarget->isPICStyleStubPIC())
10118     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10119
10120   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10121                                              CP->getAlignment(),
10122                                              CP->getOffset(), OpFlag);
10123   SDLoc DL(CP);
10124   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10125   // With PIC, the address is actually $g + Offset.
10126   if (OpFlag) {
10127     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10128                          DAG.getNode(X86ISD::GlobalBaseReg,
10129                                      SDLoc(), getPointerTy()),
10130                          Result);
10131   }
10132
10133   return Result;
10134 }
10135
10136 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10137   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10138
10139   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10140   // global base reg.
10141   unsigned char OpFlag = 0;
10142   unsigned WrapperKind = X86ISD::Wrapper;
10143   CodeModel::Model M = DAG.getTarget().getCodeModel();
10144
10145   if (Subtarget->isPICStyleRIPRel() &&
10146       (M == CodeModel::Small || M == CodeModel::Kernel))
10147     WrapperKind = X86ISD::WrapperRIP;
10148   else if (Subtarget->isPICStyleGOT())
10149     OpFlag = X86II::MO_GOTOFF;
10150   else if (Subtarget->isPICStyleStubPIC())
10151     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10152
10153   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10154                                           OpFlag);
10155   SDLoc DL(JT);
10156   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10157
10158   // With PIC, the address is actually $g + Offset.
10159   if (OpFlag)
10160     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10161                          DAG.getNode(X86ISD::GlobalBaseReg,
10162                                      SDLoc(), getPointerTy()),
10163                          Result);
10164
10165   return Result;
10166 }
10167
10168 SDValue
10169 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10170   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10171
10172   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10173   // global base reg.
10174   unsigned char OpFlag = 0;
10175   unsigned WrapperKind = X86ISD::Wrapper;
10176   CodeModel::Model M = DAG.getTarget().getCodeModel();
10177
10178   if (Subtarget->isPICStyleRIPRel() &&
10179       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10180     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10181       OpFlag = X86II::MO_GOTPCREL;
10182     WrapperKind = X86ISD::WrapperRIP;
10183   } else if (Subtarget->isPICStyleGOT()) {
10184     OpFlag = X86II::MO_GOT;
10185   } else if (Subtarget->isPICStyleStubPIC()) {
10186     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10187   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10188     OpFlag = X86II::MO_DARWIN_NONLAZY;
10189   }
10190
10191   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10192
10193   SDLoc DL(Op);
10194   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10195
10196   // With PIC, the address is actually $g + Offset.
10197   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10198       !Subtarget->is64Bit()) {
10199     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10200                          DAG.getNode(X86ISD::GlobalBaseReg,
10201                                      SDLoc(), getPointerTy()),
10202                          Result);
10203   }
10204
10205   // For symbols that require a load from a stub to get the address, emit the
10206   // load.
10207   if (isGlobalStubReference(OpFlag))
10208     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10209                          MachinePointerInfo::getGOT(), false, false, false, 0);
10210
10211   return Result;
10212 }
10213
10214 SDValue
10215 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10216   // Create the TargetBlockAddressAddress node.
10217   unsigned char OpFlags =
10218     Subtarget->ClassifyBlockAddressReference();
10219   CodeModel::Model M = DAG.getTarget().getCodeModel();
10220   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10221   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10222   SDLoc dl(Op);
10223   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10224                                              OpFlags);
10225
10226   if (Subtarget->isPICStyleRIPRel() &&
10227       (M == CodeModel::Small || M == CodeModel::Kernel))
10228     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10229   else
10230     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10231
10232   // With PIC, the address is actually $g + Offset.
10233   if (isGlobalRelativeToPICBase(OpFlags)) {
10234     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10235                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10236                          Result);
10237   }
10238
10239   return Result;
10240 }
10241
10242 SDValue
10243 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10244                                       int64_t Offset, SelectionDAG &DAG) const {
10245   // Create the TargetGlobalAddress node, folding in the constant
10246   // offset if it is legal.
10247   unsigned char OpFlags =
10248       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10249   CodeModel::Model M = DAG.getTarget().getCodeModel();
10250   SDValue Result;
10251   if (OpFlags == X86II::MO_NO_FLAG &&
10252       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10253     // A direct static reference to a global.
10254     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10255     Offset = 0;
10256   } else {
10257     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10258   }
10259
10260   if (Subtarget->isPICStyleRIPRel() &&
10261       (M == CodeModel::Small || M == CodeModel::Kernel))
10262     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10263   else
10264     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10265
10266   // With PIC, the address is actually $g + Offset.
10267   if (isGlobalRelativeToPICBase(OpFlags)) {
10268     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10269                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10270                          Result);
10271   }
10272
10273   // For globals that require a load from a stub to get the address, emit the
10274   // load.
10275   if (isGlobalStubReference(OpFlags))
10276     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10277                          MachinePointerInfo::getGOT(), false, false, false, 0);
10278
10279   // If there was a non-zero offset that we didn't fold, create an explicit
10280   // addition for it.
10281   if (Offset != 0)
10282     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10283                          DAG.getConstant(Offset, getPointerTy()));
10284
10285   return Result;
10286 }
10287
10288 SDValue
10289 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10290   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10291   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10292   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10293 }
10294
10295 static SDValue
10296 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10297            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10298            unsigned char OperandFlags, bool LocalDynamic = false) {
10299   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10300   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10301   SDLoc dl(GA);
10302   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10303                                            GA->getValueType(0),
10304                                            GA->getOffset(),
10305                                            OperandFlags);
10306
10307   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10308                                            : X86ISD::TLSADDR;
10309
10310   if (InFlag) {
10311     SDValue Ops[] = { Chain,  TGA, *InFlag };
10312     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10313   } else {
10314     SDValue Ops[]  = { Chain, TGA };
10315     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10316   }
10317
10318   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10319   MFI->setAdjustsStack(true);
10320
10321   SDValue Flag = Chain.getValue(1);
10322   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10323 }
10324
10325 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10326 static SDValue
10327 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10328                                 const EVT PtrVT) {
10329   SDValue InFlag;
10330   SDLoc dl(GA);  // ? function entry point might be better
10331   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10332                                    DAG.getNode(X86ISD::GlobalBaseReg,
10333                                                SDLoc(), PtrVT), InFlag);
10334   InFlag = Chain.getValue(1);
10335
10336   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10337 }
10338
10339 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10340 static SDValue
10341 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10342                                 const EVT PtrVT) {
10343   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10344                     X86::RAX, X86II::MO_TLSGD);
10345 }
10346
10347 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10348                                            SelectionDAG &DAG,
10349                                            const EVT PtrVT,
10350                                            bool is64Bit) {
10351   SDLoc dl(GA);
10352
10353   // Get the start address of the TLS block for this module.
10354   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10355       .getInfo<X86MachineFunctionInfo>();
10356   MFI->incNumLocalDynamicTLSAccesses();
10357
10358   SDValue Base;
10359   if (is64Bit) {
10360     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10361                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10362   } else {
10363     SDValue InFlag;
10364     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10365         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10366     InFlag = Chain.getValue(1);
10367     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10368                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10369   }
10370
10371   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10372   // of Base.
10373
10374   // Build x@dtpoff.
10375   unsigned char OperandFlags = X86II::MO_DTPOFF;
10376   unsigned WrapperKind = X86ISD::Wrapper;
10377   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10378                                            GA->getValueType(0),
10379                                            GA->getOffset(), OperandFlags);
10380   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10381
10382   // Add x@dtpoff with the base.
10383   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10384 }
10385
10386 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10387 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10388                                    const EVT PtrVT, TLSModel::Model model,
10389                                    bool is64Bit, bool isPIC) {
10390   SDLoc dl(GA);
10391
10392   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10393   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10394                                                          is64Bit ? 257 : 256));
10395
10396   SDValue ThreadPointer =
10397       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10398                   MachinePointerInfo(Ptr), false, false, false, 0);
10399
10400   unsigned char OperandFlags = 0;
10401   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10402   // initialexec.
10403   unsigned WrapperKind = X86ISD::Wrapper;
10404   if (model == TLSModel::LocalExec) {
10405     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10406   } else if (model == TLSModel::InitialExec) {
10407     if (is64Bit) {
10408       OperandFlags = X86II::MO_GOTTPOFF;
10409       WrapperKind = X86ISD::WrapperRIP;
10410     } else {
10411       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10412     }
10413   } else {
10414     llvm_unreachable("Unexpected model");
10415   }
10416
10417   // emit "addl x@ntpoff,%eax" (local exec)
10418   // or "addl x@indntpoff,%eax" (initial exec)
10419   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10420   SDValue TGA =
10421       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10422                                  GA->getOffset(), OperandFlags);
10423   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10424
10425   if (model == TLSModel::InitialExec) {
10426     if (isPIC && !is64Bit) {
10427       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10428                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10429                            Offset);
10430     }
10431
10432     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10433                          MachinePointerInfo::getGOT(), false, false, false, 0);
10434   }
10435
10436   // The address of the thread local variable is the add of the thread
10437   // pointer with the offset of the variable.
10438   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10439 }
10440
10441 SDValue
10442 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10443
10444   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10445   const GlobalValue *GV = GA->getGlobal();
10446
10447   if (Subtarget->isTargetELF()) {
10448     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10449
10450     switch (model) {
10451       case TLSModel::GeneralDynamic:
10452         if (Subtarget->is64Bit())
10453           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10454         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10455       case TLSModel::LocalDynamic:
10456         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10457                                            Subtarget->is64Bit());
10458       case TLSModel::InitialExec:
10459       case TLSModel::LocalExec:
10460         return LowerToTLSExecModel(
10461             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10462             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10463     }
10464     llvm_unreachable("Unknown TLS model.");
10465   }
10466
10467   if (Subtarget->isTargetDarwin()) {
10468     // Darwin only has one model of TLS.  Lower to that.
10469     unsigned char OpFlag = 0;
10470     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10471                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10472
10473     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10474     // global base reg.
10475     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10476                  !Subtarget->is64Bit();
10477     if (PIC32)
10478       OpFlag = X86II::MO_TLVP_PIC_BASE;
10479     else
10480       OpFlag = X86II::MO_TLVP;
10481     SDLoc DL(Op);
10482     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10483                                                 GA->getValueType(0),
10484                                                 GA->getOffset(), OpFlag);
10485     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10486
10487     // With PIC32, the address is actually $g + Offset.
10488     if (PIC32)
10489       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10490                            DAG.getNode(X86ISD::GlobalBaseReg,
10491                                        SDLoc(), getPointerTy()),
10492                            Offset);
10493
10494     // Lowering the machine isd will make sure everything is in the right
10495     // location.
10496     SDValue Chain = DAG.getEntryNode();
10497     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10498     SDValue Args[] = { Chain, Offset };
10499     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10500
10501     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10502     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10503     MFI->setAdjustsStack(true);
10504
10505     // And our return value (tls address) is in the standard call return value
10506     // location.
10507     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10508     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10509                               Chain.getValue(1));
10510   }
10511
10512   if (Subtarget->isTargetKnownWindowsMSVC() ||
10513       Subtarget->isTargetWindowsGNU()) {
10514     // Just use the implicit TLS architecture
10515     // Need to generate someting similar to:
10516     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10517     //                                  ; from TEB
10518     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10519     //   mov     rcx, qword [rdx+rcx*8]
10520     //   mov     eax, .tls$:tlsvar
10521     //   [rax+rcx] contains the address
10522     // Windows 64bit: gs:0x58
10523     // Windows 32bit: fs:__tls_array
10524
10525     SDLoc dl(GA);
10526     SDValue Chain = DAG.getEntryNode();
10527
10528     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10529     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10530     // use its literal value of 0x2C.
10531     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10532                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10533                                                              256)
10534                                         : Type::getInt32PtrTy(*DAG.getContext(),
10535                                                               257));
10536
10537     SDValue TlsArray =
10538         Subtarget->is64Bit()
10539             ? DAG.getIntPtrConstant(0x58)
10540             : (Subtarget->isTargetWindowsGNU()
10541                    ? DAG.getIntPtrConstant(0x2C)
10542                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10543
10544     SDValue ThreadPointer =
10545         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10546                     MachinePointerInfo(Ptr), false, false, false, 0);
10547
10548     // Load the _tls_index variable
10549     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10550     if (Subtarget->is64Bit())
10551       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10552                            IDX, MachinePointerInfo(), MVT::i32,
10553                            false, false, 0);
10554     else
10555       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10556                         false, false, false, 0);
10557
10558     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10559                                     getPointerTy());
10560     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10561
10562     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10563     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10564                       false, false, false, 0);
10565
10566     // Get the offset of start of .tls section
10567     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10568                                              GA->getValueType(0),
10569                                              GA->getOffset(), X86II::MO_SECREL);
10570     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10571
10572     // The address of the thread local variable is the add of the thread
10573     // pointer with the offset of the variable.
10574     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10575   }
10576
10577   llvm_unreachable("TLS not implemented for this target.");
10578 }
10579
10580 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10581 /// and take a 2 x i32 value to shift plus a shift amount.
10582 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10583   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10584   MVT VT = Op.getSimpleValueType();
10585   unsigned VTBits = VT.getSizeInBits();
10586   SDLoc dl(Op);
10587   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10588   SDValue ShOpLo = Op.getOperand(0);
10589   SDValue ShOpHi = Op.getOperand(1);
10590   SDValue ShAmt  = Op.getOperand(2);
10591   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10592   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10593   // during isel.
10594   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10595                                   DAG.getConstant(VTBits - 1, MVT::i8));
10596   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10597                                      DAG.getConstant(VTBits - 1, MVT::i8))
10598                        : DAG.getConstant(0, VT);
10599
10600   SDValue Tmp2, Tmp3;
10601   if (Op.getOpcode() == ISD::SHL_PARTS) {
10602     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10603     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10604   } else {
10605     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10606     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10607   }
10608
10609   // If the shift amount is larger or equal than the width of a part we can't
10610   // rely on the results of shld/shrd. Insert a test and select the appropriate
10611   // values for large shift amounts.
10612   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10613                                 DAG.getConstant(VTBits, MVT::i8));
10614   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10615                              AndNode, DAG.getConstant(0, MVT::i8));
10616
10617   SDValue Hi, Lo;
10618   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10619   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10620   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10621
10622   if (Op.getOpcode() == ISD::SHL_PARTS) {
10623     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10624     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10625   } else {
10626     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10627     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10628   }
10629
10630   SDValue Ops[2] = { Lo, Hi };
10631   return DAG.getMergeValues(Ops, dl);
10632 }
10633
10634 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10635                                            SelectionDAG &DAG) const {
10636   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10637
10638   if (SrcVT.isVector())
10639     return SDValue();
10640
10641   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10642          "Unknown SINT_TO_FP to lower!");
10643
10644   // These are really Legal; return the operand so the caller accepts it as
10645   // Legal.
10646   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10647     return Op;
10648   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10649       Subtarget->is64Bit()) {
10650     return Op;
10651   }
10652
10653   SDLoc dl(Op);
10654   unsigned Size = SrcVT.getSizeInBits()/8;
10655   MachineFunction &MF = DAG.getMachineFunction();
10656   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10657   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10658   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10659                                StackSlot,
10660                                MachinePointerInfo::getFixedStack(SSFI),
10661                                false, false, 0);
10662   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10663 }
10664
10665 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10666                                      SDValue StackSlot,
10667                                      SelectionDAG &DAG) const {
10668   // Build the FILD
10669   SDLoc DL(Op);
10670   SDVTList Tys;
10671   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10672   if (useSSE)
10673     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10674   else
10675     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10676
10677   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10678
10679   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10680   MachineMemOperand *MMO;
10681   if (FI) {
10682     int SSFI = FI->getIndex();
10683     MMO =
10684       DAG.getMachineFunction()
10685       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10686                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10687   } else {
10688     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10689     StackSlot = StackSlot.getOperand(1);
10690   }
10691   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10692   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10693                                            X86ISD::FILD, DL,
10694                                            Tys, Ops, SrcVT, MMO);
10695
10696   if (useSSE) {
10697     Chain = Result.getValue(1);
10698     SDValue InFlag = Result.getValue(2);
10699
10700     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10701     // shouldn't be necessary except that RFP cannot be live across
10702     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10703     MachineFunction &MF = DAG.getMachineFunction();
10704     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10705     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10706     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10707     Tys = DAG.getVTList(MVT::Other);
10708     SDValue Ops[] = {
10709       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10710     };
10711     MachineMemOperand *MMO =
10712       DAG.getMachineFunction()
10713       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10714                             MachineMemOperand::MOStore, SSFISize, SSFISize);
10715
10716     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10717                                     Ops, Op.getValueType(), MMO);
10718     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10719                          MachinePointerInfo::getFixedStack(SSFI),
10720                          false, false, false, 0);
10721   }
10722
10723   return Result;
10724 }
10725
10726 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10727 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10728                                                SelectionDAG &DAG) const {
10729   // This algorithm is not obvious. Here it is what we're trying to output:
10730   /*
10731      movq       %rax,  %xmm0
10732      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10733      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10734      #ifdef __SSE3__
10735        haddpd   %xmm0, %xmm0
10736      #else
10737        pshufd   $0x4e, %xmm0, %xmm1
10738        addpd    %xmm1, %xmm0
10739      #endif
10740   */
10741
10742   SDLoc dl(Op);
10743   LLVMContext *Context = DAG.getContext();
10744
10745   // Build some magic constants.
10746   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10747   Constant *C0 = ConstantDataVector::get(*Context, CV0);
10748   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10749
10750   SmallVector<Constant*,2> CV1;
10751   CV1.push_back(
10752     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10753                                       APInt(64, 0x4330000000000000ULL))));
10754   CV1.push_back(
10755     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10756                                       APInt(64, 0x4530000000000000ULL))));
10757   Constant *C1 = ConstantVector::get(CV1);
10758   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10759
10760   // Load the 64-bit value into an XMM register.
10761   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10762                             Op.getOperand(0));
10763   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10764                               MachinePointerInfo::getConstantPool(),
10765                               false, false, false, 16);
10766   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10767                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10768                               CLod0);
10769
10770   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10771                               MachinePointerInfo::getConstantPool(),
10772                               false, false, false, 16);
10773   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10774   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10775   SDValue Result;
10776
10777   if (Subtarget->hasSSE3()) {
10778     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10779     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10780   } else {
10781     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10782     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10783                                            S2F, 0x4E, DAG);
10784     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10785                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10786                          Sub);
10787   }
10788
10789   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10790                      DAG.getIntPtrConstant(0));
10791 }
10792
10793 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10794 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10795                                                SelectionDAG &DAG) const {
10796   SDLoc dl(Op);
10797   // FP constant to bias correct the final result.
10798   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10799                                    MVT::f64);
10800
10801   // Load the 32-bit value into an XMM register.
10802   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10803                              Op.getOperand(0));
10804
10805   // Zero out the upper parts of the register.
10806   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10807
10808   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10809                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10810                      DAG.getIntPtrConstant(0));
10811
10812   // Or the load with the bias.
10813   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10814                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10815                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10816                                                    MVT::v2f64, Load)),
10817                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10818                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10819                                                    MVT::v2f64, Bias)));
10820   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10821                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10822                    DAG.getIntPtrConstant(0));
10823
10824   // Subtract the bias.
10825   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10826
10827   // Handle final rounding.
10828   EVT DestVT = Op.getValueType();
10829
10830   if (DestVT.bitsLT(MVT::f64))
10831     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10832                        DAG.getIntPtrConstant(0));
10833   if (DestVT.bitsGT(MVT::f64))
10834     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10835
10836   // Handle final rounding.
10837   return Sub;
10838 }
10839
10840 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10841                                                SelectionDAG &DAG) const {
10842   SDValue N0 = Op.getOperand(0);
10843   MVT SVT = N0.getSimpleValueType();
10844   SDLoc dl(Op);
10845
10846   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10847           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10848          "Custom UINT_TO_FP is not supported!");
10849
10850   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10851   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10852                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10853 }
10854
10855 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10856                                            SelectionDAG &DAG) const {
10857   SDValue N0 = Op.getOperand(0);
10858   SDLoc dl(Op);
10859
10860   if (Op.getValueType().isVector())
10861     return lowerUINT_TO_FP_vec(Op, DAG);
10862
10863   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10864   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10865   // the optimization here.
10866   if (DAG.SignBitIsZero(N0))
10867     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10868
10869   MVT SrcVT = N0.getSimpleValueType();
10870   MVT DstVT = Op.getSimpleValueType();
10871   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10872     return LowerUINT_TO_FP_i64(Op, DAG);
10873   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10874     return LowerUINT_TO_FP_i32(Op, DAG);
10875   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10876     return SDValue();
10877
10878   // Make a 64-bit buffer, and use it to build an FILD.
10879   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10880   if (SrcVT == MVT::i32) {
10881     SDValue WordOff = DAG.getConstant(4, getPointerTy());
10882     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10883                                      getPointerTy(), StackSlot, WordOff);
10884     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10885                                   StackSlot, MachinePointerInfo(),
10886                                   false, false, 0);
10887     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10888                                   OffsetSlot, MachinePointerInfo(),
10889                                   false, false, 0);
10890     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10891     return Fild;
10892   }
10893
10894   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10895   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10896                                StackSlot, MachinePointerInfo(),
10897                                false, false, 0);
10898   // For i64 source, we need to add the appropriate power of 2 if the input
10899   // was negative.  This is the same as the optimization in
10900   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10901   // we must be careful to do the computation in x87 extended precision, not
10902   // in SSE. (The generic code can't know it's OK to do this, or how to.)
10903   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10904   MachineMemOperand *MMO =
10905     DAG.getMachineFunction()
10906     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10907                           MachineMemOperand::MOLoad, 8, 8);
10908
10909   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10910   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10911   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10912                                          MVT::i64, MMO);
10913
10914   APInt FF(32, 0x5F800000ULL);
10915
10916   // Check whether the sign bit is set.
10917   SDValue SignSet = DAG.getSetCC(dl,
10918                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
10919                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10920                                  ISD::SETLT);
10921
10922   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10923   SDValue FudgePtr = DAG.getConstantPool(
10924                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10925                                          getPointerTy());
10926
10927   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10928   SDValue Zero = DAG.getIntPtrConstant(0);
10929   SDValue Four = DAG.getIntPtrConstant(4);
10930   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10931                                Zero, Four);
10932   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10933
10934   // Load the value out, extending it from f32 to f80.
10935   // FIXME: Avoid the extend by constructing the right constant pool?
10936   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10937                                  FudgePtr, MachinePointerInfo::getConstantPool(),
10938                                  MVT::f32, false, false, 4);
10939   // Extend everything to 80 bits to force it to be done on x87.
10940   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10941   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10942 }
10943
10944 std::pair<SDValue,SDValue>
10945 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10946                                     bool IsSigned, bool IsReplace) const {
10947   SDLoc DL(Op);
10948
10949   EVT DstTy = Op.getValueType();
10950
10951   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
10952     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
10953     DstTy = MVT::i64;
10954   }
10955
10956   assert(DstTy.getSimpleVT() <= MVT::i64 &&
10957          DstTy.getSimpleVT() >= MVT::i16 &&
10958          "Unknown FP_TO_INT to lower!");
10959
10960   // These are really Legal.
10961   if (DstTy == MVT::i32 &&
10962       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10963     return std::make_pair(SDValue(), SDValue());
10964   if (Subtarget->is64Bit() &&
10965       DstTy == MVT::i64 &&
10966       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10967     return std::make_pair(SDValue(), SDValue());
10968
10969   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
10970   // stack slot, or into the FTOL runtime function.
10971   MachineFunction &MF = DAG.getMachineFunction();
10972   unsigned MemSize = DstTy.getSizeInBits()/8;
10973   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
10974   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10975
10976   unsigned Opc;
10977   if (!IsSigned && isIntegerTypeFTOL(DstTy))
10978     Opc = X86ISD::WIN_FTOL;
10979   else
10980     switch (DstTy.getSimpleVT().SimpleTy) {
10981     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
10982     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
10983     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
10984     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
10985     }
10986
10987   SDValue Chain = DAG.getEntryNode();
10988   SDValue Value = Op.getOperand(0);
10989   EVT TheVT = Op.getOperand(0).getValueType();
10990   // FIXME This causes a redundant load/store if the SSE-class value is already
10991   // in memory, such as if it is on the callstack.
10992   if (isScalarFPTypeInSSEReg(TheVT)) {
10993     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
10994     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
10995                          MachinePointerInfo::getFixedStack(SSFI),
10996                          false, false, 0);
10997     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
10998     SDValue Ops[] = {
10999       Chain, StackSlot, DAG.getValueType(TheVT)
11000     };
11001
11002     MachineMemOperand *MMO =
11003       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11004                               MachineMemOperand::MOLoad, MemSize, MemSize);
11005     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11006     Chain = Value.getValue(1);
11007     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11008     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11009   }
11010
11011   MachineMemOperand *MMO =
11012     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11013                             MachineMemOperand::MOStore, MemSize, MemSize);
11014
11015   if (Opc != X86ISD::WIN_FTOL) {
11016     // Build the FP_TO_INT*_IN_MEM
11017     SDValue Ops[] = { Chain, Value, StackSlot };
11018     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11019                                            Ops, DstTy, MMO);
11020     return std::make_pair(FIST, StackSlot);
11021   } else {
11022     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11023       DAG.getVTList(MVT::Other, MVT::Glue),
11024       Chain, Value);
11025     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11026       MVT::i32, ftol.getValue(1));
11027     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11028       MVT::i32, eax.getValue(2));
11029     SDValue Ops[] = { eax, edx };
11030     SDValue pair = IsReplace
11031       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11032       : DAG.getMergeValues(Ops, DL);
11033     return std::make_pair(pair, SDValue());
11034   }
11035 }
11036
11037 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11038                               const X86Subtarget *Subtarget) {
11039   MVT VT = Op->getSimpleValueType(0);
11040   SDValue In = Op->getOperand(0);
11041   MVT InVT = In.getSimpleValueType();
11042   SDLoc dl(Op);
11043
11044   // Optimize vectors in AVX mode:
11045   //
11046   //   v8i16 -> v8i32
11047   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11048   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11049   //   Concat upper and lower parts.
11050   //
11051   //   v4i32 -> v4i64
11052   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11053   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11054   //   Concat upper and lower parts.
11055   //
11056
11057   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11058       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11059       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11060     return SDValue();
11061
11062   if (Subtarget->hasInt256())
11063     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11064
11065   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11066   SDValue Undef = DAG.getUNDEF(InVT);
11067   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11068   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11069   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11070
11071   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11072                              VT.getVectorNumElements()/2);
11073
11074   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11075   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11076
11077   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11078 }
11079
11080 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11081                                         SelectionDAG &DAG) {
11082   MVT VT = Op->getSimpleValueType(0);
11083   SDValue In = Op->getOperand(0);
11084   MVT InVT = In.getSimpleValueType();
11085   SDLoc DL(Op);
11086   unsigned int NumElts = VT.getVectorNumElements();
11087   if (NumElts != 8 && NumElts != 16)
11088     return SDValue();
11089
11090   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11091     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11092
11093   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11094   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11095   // Now we have only mask extension
11096   assert(InVT.getVectorElementType() == MVT::i1);
11097   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11098   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11099   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11100   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11101   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11102                            MachinePointerInfo::getConstantPool(),
11103                            false, false, false, Alignment);
11104
11105   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11106   if (VT.is512BitVector())
11107     return Brcst;
11108   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11109 }
11110
11111 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11112                                SelectionDAG &DAG) {
11113   if (Subtarget->hasFp256()) {
11114     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11115     if (Res.getNode())
11116       return Res;
11117   }
11118
11119   return SDValue();
11120 }
11121
11122 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11123                                 SelectionDAG &DAG) {
11124   SDLoc DL(Op);
11125   MVT VT = Op.getSimpleValueType();
11126   SDValue In = Op.getOperand(0);
11127   MVT SVT = In.getSimpleValueType();
11128
11129   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11130     return LowerZERO_EXTEND_AVX512(Op, DAG);
11131
11132   if (Subtarget->hasFp256()) {
11133     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11134     if (Res.getNode())
11135       return Res;
11136   }
11137
11138   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11139          VT.getVectorNumElements() != SVT.getVectorNumElements());
11140   return SDValue();
11141 }
11142
11143 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11144   SDLoc DL(Op);
11145   MVT VT = Op.getSimpleValueType();
11146   SDValue In = Op.getOperand(0);
11147   MVT InVT = In.getSimpleValueType();
11148
11149   if (VT == MVT::i1) {
11150     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11151            "Invalid scalar TRUNCATE operation");
11152     if (InVT == MVT::i32)
11153       return SDValue();
11154     if (InVT.getSizeInBits() == 64)
11155       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11156     else if (InVT.getSizeInBits() < 32)
11157       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11158     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11159   }
11160   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11161          "Invalid TRUNCATE operation");
11162
11163   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11164     if (VT.getVectorElementType().getSizeInBits() >=8)
11165       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11166
11167     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11168     unsigned NumElts = InVT.getVectorNumElements();
11169     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11170     if (InVT.getSizeInBits() < 512) {
11171       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11172       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11173       InVT = ExtVT;
11174     }
11175     
11176     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11177     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11178     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11179     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11180     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11181                            MachinePointerInfo::getConstantPool(),
11182                            false, false, false, Alignment);
11183     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11184     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11185     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11186   }
11187
11188   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11189     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11190     if (Subtarget->hasInt256()) {
11191       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11192       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11193       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11194                                 ShufMask);
11195       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11196                          DAG.getIntPtrConstant(0));
11197     }
11198
11199     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11200                                DAG.getIntPtrConstant(0));
11201     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11202                                DAG.getIntPtrConstant(2));
11203     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11204     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11205     static const int ShufMask[] = {0, 2, 4, 6};
11206     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11207   }
11208
11209   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11210     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11211     if (Subtarget->hasInt256()) {
11212       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11213
11214       SmallVector<SDValue,32> pshufbMask;
11215       for (unsigned i = 0; i < 2; ++i) {
11216         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11217         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11218         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11219         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11220         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11221         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11222         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11223         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11224         for (unsigned j = 0; j < 8; ++j)
11225           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11226       }
11227       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11228       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11229       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11230
11231       static const int ShufMask[] = {0,  2,  -1,  -1};
11232       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11233                                 &ShufMask[0]);
11234       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11235                        DAG.getIntPtrConstant(0));
11236       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11237     }
11238
11239     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11240                                DAG.getIntPtrConstant(0));
11241
11242     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11243                                DAG.getIntPtrConstant(4));
11244
11245     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11246     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11247
11248     // The PSHUFB mask:
11249     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11250                                    -1, -1, -1, -1, -1, -1, -1, -1};
11251
11252     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11253     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11254     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11255
11256     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11257     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11258
11259     // The MOVLHPS Mask:
11260     static const int ShufMask2[] = {0, 1, 4, 5};
11261     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11262     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11263   }
11264
11265   // Handle truncation of V256 to V128 using shuffles.
11266   if (!VT.is128BitVector() || !InVT.is256BitVector())
11267     return SDValue();
11268
11269   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11270
11271   unsigned NumElems = VT.getVectorNumElements();
11272   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11273
11274   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11275   // Prepare truncation shuffle mask
11276   for (unsigned i = 0; i != NumElems; ++i)
11277     MaskVec[i] = i * 2;
11278   SDValue V = DAG.getVectorShuffle(NVT, DL,
11279                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11280                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11281   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11282                      DAG.getIntPtrConstant(0));
11283 }
11284
11285 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11286                                            SelectionDAG &DAG) const {
11287   assert(!Op.getSimpleValueType().isVector());
11288
11289   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11290     /*IsSigned=*/ true, /*IsReplace=*/ false);
11291   SDValue FIST = Vals.first, StackSlot = Vals.second;
11292   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11293   if (!FIST.getNode()) return Op;
11294
11295   if (StackSlot.getNode())
11296     // Load the result.
11297     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11298                        FIST, StackSlot, MachinePointerInfo(),
11299                        false, false, false, 0);
11300
11301   // The node is the result.
11302   return FIST;
11303 }
11304
11305 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11306                                            SelectionDAG &DAG) const {
11307   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11308     /*IsSigned=*/ false, /*IsReplace=*/ false);
11309   SDValue FIST = Vals.first, StackSlot = Vals.second;
11310   assert(FIST.getNode() && "Unexpected failure");
11311
11312   if (StackSlot.getNode())
11313     // Load the result.
11314     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11315                        FIST, StackSlot, MachinePointerInfo(),
11316                        false, false, false, 0);
11317
11318   // The node is the result.
11319   return FIST;
11320 }
11321
11322 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11323   SDLoc DL(Op);
11324   MVT VT = Op.getSimpleValueType();
11325   SDValue In = Op.getOperand(0);
11326   MVT SVT = In.getSimpleValueType();
11327
11328   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11329
11330   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11331                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11332                                  In, DAG.getUNDEF(SVT)));
11333 }
11334
11335 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11336   LLVMContext *Context = DAG.getContext();
11337   SDLoc dl(Op);
11338   MVT VT = Op.getSimpleValueType();
11339   MVT EltVT = VT;
11340   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11341   if (VT.isVector()) {
11342     EltVT = VT.getVectorElementType();
11343     NumElts = VT.getVectorNumElements();
11344   }
11345   Constant *C;
11346   if (EltVT == MVT::f64)
11347     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11348                                           APInt(64, ~(1ULL << 63))));
11349   else
11350     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11351                                           APInt(32, ~(1U << 31))));
11352   C = ConstantVector::getSplat(NumElts, C);
11353   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11354   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11355   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11356   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11357                              MachinePointerInfo::getConstantPool(),
11358                              false, false, false, Alignment);
11359   if (VT.isVector()) {
11360     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11361     return DAG.getNode(ISD::BITCAST, dl, VT,
11362                        DAG.getNode(ISD::AND, dl, ANDVT,
11363                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11364                                                Op.getOperand(0)),
11365                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11366   }
11367   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11368 }
11369
11370 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11371   LLVMContext *Context = DAG.getContext();
11372   SDLoc dl(Op);
11373   MVT VT = Op.getSimpleValueType();
11374   MVT EltVT = VT;
11375   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11376   if (VT.isVector()) {
11377     EltVT = VT.getVectorElementType();
11378     NumElts = VT.getVectorNumElements();
11379   }
11380   Constant *C;
11381   if (EltVT == MVT::f64)
11382     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11383                                           APInt(64, 1ULL << 63)));
11384   else
11385     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11386                                           APInt(32, 1U << 31)));
11387   C = ConstantVector::getSplat(NumElts, C);
11388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11389   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11390   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11391   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11392                              MachinePointerInfo::getConstantPool(),
11393                              false, false, false, Alignment);
11394   if (VT.isVector()) {
11395     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11396     return DAG.getNode(ISD::BITCAST, dl, VT,
11397                        DAG.getNode(ISD::XOR, dl, XORVT,
11398                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11399                                                Op.getOperand(0)),
11400                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11401   }
11402
11403   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11404 }
11405
11406 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11407   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11408   LLVMContext *Context = DAG.getContext();
11409   SDValue Op0 = Op.getOperand(0);
11410   SDValue Op1 = Op.getOperand(1);
11411   SDLoc dl(Op);
11412   MVT VT = Op.getSimpleValueType();
11413   MVT SrcVT = Op1.getSimpleValueType();
11414
11415   // If second operand is smaller, extend it first.
11416   if (SrcVT.bitsLT(VT)) {
11417     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11418     SrcVT = VT;
11419   }
11420   // And if it is bigger, shrink it first.
11421   if (SrcVT.bitsGT(VT)) {
11422     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11423     SrcVT = VT;
11424   }
11425
11426   // At this point the operands and the result should have the same
11427   // type, and that won't be f80 since that is not custom lowered.
11428
11429   // First get the sign bit of second operand.
11430   SmallVector<Constant*,4> CV;
11431   if (SrcVT == MVT::f64) {
11432     const fltSemantics &Sem = APFloat::IEEEdouble;
11433     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11434     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11435   } else {
11436     const fltSemantics &Sem = APFloat::IEEEsingle;
11437     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11438     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11439     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11440     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11441   }
11442   Constant *C = ConstantVector::get(CV);
11443   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11444   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11445                               MachinePointerInfo::getConstantPool(),
11446                               false, false, false, 16);
11447   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11448
11449   // Shift sign bit right or left if the two operands have different types.
11450   if (SrcVT.bitsGT(VT)) {
11451     // Op0 is MVT::f32, Op1 is MVT::f64.
11452     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11453     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11454                           DAG.getConstant(32, MVT::i32));
11455     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11456     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11457                           DAG.getIntPtrConstant(0));
11458   }
11459
11460   // Clear first operand sign bit.
11461   CV.clear();
11462   if (VT == MVT::f64) {
11463     const fltSemantics &Sem = APFloat::IEEEdouble;
11464     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11465                                                    APInt(64, ~(1ULL << 63)))));
11466     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11467   } else {
11468     const fltSemantics &Sem = APFloat::IEEEsingle;
11469     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11470                                                    APInt(32, ~(1U << 31)))));
11471     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11472     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11473     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11474   }
11475   C = ConstantVector::get(CV);
11476   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11477   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11478                               MachinePointerInfo::getConstantPool(),
11479                               false, false, false, 16);
11480   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11481
11482   // Or the value with the sign bit.
11483   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11484 }
11485
11486 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11487   SDValue N0 = Op.getOperand(0);
11488   SDLoc dl(Op);
11489   MVT VT = Op.getSimpleValueType();
11490
11491   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11492   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11493                                   DAG.getConstant(1, VT));
11494   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11495 }
11496
11497 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11498 //
11499 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11500                                       SelectionDAG &DAG) {
11501   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11502
11503   if (!Subtarget->hasSSE41())
11504     return SDValue();
11505
11506   if (!Op->hasOneUse())
11507     return SDValue();
11508
11509   SDNode *N = Op.getNode();
11510   SDLoc DL(N);
11511
11512   SmallVector<SDValue, 8> Opnds;
11513   DenseMap<SDValue, unsigned> VecInMap;
11514   SmallVector<SDValue, 8> VecIns;
11515   EVT VT = MVT::Other;
11516
11517   // Recognize a special case where a vector is casted into wide integer to
11518   // test all 0s.
11519   Opnds.push_back(N->getOperand(0));
11520   Opnds.push_back(N->getOperand(1));
11521
11522   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11523     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11524     // BFS traverse all OR'd operands.
11525     if (I->getOpcode() == ISD::OR) {
11526       Opnds.push_back(I->getOperand(0));
11527       Opnds.push_back(I->getOperand(1));
11528       // Re-evaluate the number of nodes to be traversed.
11529       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11530       continue;
11531     }
11532
11533     // Quit if a non-EXTRACT_VECTOR_ELT
11534     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11535       return SDValue();
11536
11537     // Quit if without a constant index.
11538     SDValue Idx = I->getOperand(1);
11539     if (!isa<ConstantSDNode>(Idx))
11540       return SDValue();
11541
11542     SDValue ExtractedFromVec = I->getOperand(0);
11543     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11544     if (M == VecInMap.end()) {
11545       VT = ExtractedFromVec.getValueType();
11546       // Quit if not 128/256-bit vector.
11547       if (!VT.is128BitVector() && !VT.is256BitVector())
11548         return SDValue();
11549       // Quit if not the same type.
11550       if (VecInMap.begin() != VecInMap.end() &&
11551           VT != VecInMap.begin()->first.getValueType())
11552         return SDValue();
11553       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11554       VecIns.push_back(ExtractedFromVec);
11555     }
11556     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11557   }
11558
11559   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11560          "Not extracted from 128-/256-bit vector.");
11561
11562   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11563
11564   for (DenseMap<SDValue, unsigned>::const_iterator
11565         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11566     // Quit if not all elements are used.
11567     if (I->second != FullMask)
11568       return SDValue();
11569   }
11570
11571   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11572
11573   // Cast all vectors into TestVT for PTEST.
11574   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11575     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11576
11577   // If more than one full vectors are evaluated, OR them first before PTEST.
11578   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11579     // Each iteration will OR 2 nodes and append the result until there is only
11580     // 1 node left, i.e. the final OR'd value of all vectors.
11581     SDValue LHS = VecIns[Slot];
11582     SDValue RHS = VecIns[Slot + 1];
11583     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11584   }
11585
11586   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11587                      VecIns.back(), VecIns.back());
11588 }
11589
11590 /// \brief return true if \c Op has a use that doesn't just read flags.
11591 static bool hasNonFlagsUse(SDValue Op) {
11592   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11593        ++UI) {
11594     SDNode *User = *UI;
11595     unsigned UOpNo = UI.getOperandNo();
11596     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11597       // Look pass truncate.
11598       UOpNo = User->use_begin().getOperandNo();
11599       User = *User->use_begin();
11600     }
11601
11602     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11603         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11604       return true;
11605   }
11606   return false;
11607 }
11608
11609 /// Emit nodes that will be selected as "test Op0,Op0", or something
11610 /// equivalent.
11611 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11612                                     SelectionDAG &DAG) const {
11613   if (Op.getValueType() == MVT::i1)
11614     // KORTEST instruction should be selected
11615     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11616                        DAG.getConstant(0, Op.getValueType()));
11617
11618   // CF and OF aren't always set the way we want. Determine which
11619   // of these we need.
11620   bool NeedCF = false;
11621   bool NeedOF = false;
11622   switch (X86CC) {
11623   default: break;
11624   case X86::COND_A: case X86::COND_AE:
11625   case X86::COND_B: case X86::COND_BE:
11626     NeedCF = true;
11627     break;
11628   case X86::COND_G: case X86::COND_GE:
11629   case X86::COND_L: case X86::COND_LE:
11630   case X86::COND_O: case X86::COND_NO: {
11631     // Check if we really need to set the
11632     // Overflow flag. If NoSignedWrap is present
11633     // that is not actually needed.
11634     switch (Op->getOpcode()) {
11635     case ISD::ADD:
11636     case ISD::SUB:
11637     case ISD::MUL:
11638     case ISD::SHL: {
11639       const BinaryWithFlagsSDNode *BinNode =
11640           cast<BinaryWithFlagsSDNode>(Op.getNode());
11641       if (BinNode->hasNoSignedWrap())
11642         break;
11643     }
11644     default:
11645       NeedOF = true;
11646       break;
11647     }
11648     break;
11649   }
11650   }
11651   // See if we can use the EFLAGS value from the operand instead of
11652   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11653   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11654   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11655     // Emit a CMP with 0, which is the TEST pattern.
11656     //if (Op.getValueType() == MVT::i1)
11657     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11658     //                     DAG.getConstant(0, MVT::i1));
11659     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11660                        DAG.getConstant(0, Op.getValueType()));
11661   }
11662   unsigned Opcode = 0;
11663   unsigned NumOperands = 0;
11664
11665   // Truncate operations may prevent the merge of the SETCC instruction
11666   // and the arithmetic instruction before it. Attempt to truncate the operands
11667   // of the arithmetic instruction and use a reduced bit-width instruction.
11668   bool NeedTruncation = false;
11669   SDValue ArithOp = Op;
11670   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11671     SDValue Arith = Op->getOperand(0);
11672     // Both the trunc and the arithmetic op need to have one user each.
11673     if (Arith->hasOneUse())
11674       switch (Arith.getOpcode()) {
11675         default: break;
11676         case ISD::ADD:
11677         case ISD::SUB:
11678         case ISD::AND:
11679         case ISD::OR:
11680         case ISD::XOR: {
11681           NeedTruncation = true;
11682           ArithOp = Arith;
11683         }
11684       }
11685   }
11686
11687   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11688   // which may be the result of a CAST.  We use the variable 'Op', which is the
11689   // non-casted variable when we check for possible users.
11690   switch (ArithOp.getOpcode()) {
11691   case ISD::ADD:
11692     // Due to an isel shortcoming, be conservative if this add is likely to be
11693     // selected as part of a load-modify-store instruction. When the root node
11694     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11695     // uses of other nodes in the match, such as the ADD in this case. This
11696     // leads to the ADD being left around and reselected, with the result being
11697     // two adds in the output.  Alas, even if none our users are stores, that
11698     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11699     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11700     // climbing the DAG back to the root, and it doesn't seem to be worth the
11701     // effort.
11702     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11703          UE = Op.getNode()->use_end(); UI != UE; ++UI)
11704       if (UI->getOpcode() != ISD::CopyToReg &&
11705           UI->getOpcode() != ISD::SETCC &&
11706           UI->getOpcode() != ISD::STORE)
11707         goto default_case;
11708
11709     if (ConstantSDNode *C =
11710         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11711       // An add of one will be selected as an INC.
11712       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11713         Opcode = X86ISD::INC;
11714         NumOperands = 1;
11715         break;
11716       }
11717
11718       // An add of negative one (subtract of one) will be selected as a DEC.
11719       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11720         Opcode = X86ISD::DEC;
11721         NumOperands = 1;
11722         break;
11723       }
11724     }
11725
11726     // Otherwise use a regular EFLAGS-setting add.
11727     Opcode = X86ISD::ADD;
11728     NumOperands = 2;
11729     break;
11730   case ISD::SHL:
11731   case ISD::SRL:
11732     // If we have a constant logical shift that's only used in a comparison
11733     // against zero turn it into an equivalent AND. This allows turning it into
11734     // a TEST instruction later.
11735     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11736         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11737       EVT VT = Op.getValueType();
11738       unsigned BitWidth = VT.getSizeInBits();
11739       unsigned ShAmt = Op->getConstantOperandVal(1);
11740       if (ShAmt >= BitWidth) // Avoid undefined shifts.
11741         break;
11742       APInt Mask = ArithOp.getOpcode() == ISD::SRL
11743                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11744                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11745       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11746         break;
11747       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11748                                 DAG.getConstant(Mask, VT));
11749       DAG.ReplaceAllUsesWith(Op, New);
11750       Op = New;
11751     }
11752     break;
11753
11754   case ISD::AND:
11755     // If the primary and result isn't used, don't bother using X86ISD::AND,
11756     // because a TEST instruction will be better.
11757     if (!hasNonFlagsUse(Op))
11758       break;
11759     // FALL THROUGH
11760   case ISD::SUB:
11761   case ISD::OR:
11762   case ISD::XOR:
11763     // Due to the ISEL shortcoming noted above, be conservative if this op is
11764     // likely to be selected as part of a load-modify-store instruction.
11765     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11766            UE = Op.getNode()->use_end(); UI != UE; ++UI)
11767       if (UI->getOpcode() == ISD::STORE)
11768         goto default_case;
11769
11770     // Otherwise use a regular EFLAGS-setting instruction.
11771     switch (ArithOp.getOpcode()) {
11772     default: llvm_unreachable("unexpected operator!");
11773     case ISD::SUB: Opcode = X86ISD::SUB; break;
11774     case ISD::XOR: Opcode = X86ISD::XOR; break;
11775     case ISD::AND: Opcode = X86ISD::AND; break;
11776     case ISD::OR: {
11777       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11778         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11779         if (EFLAGS.getNode())
11780           return EFLAGS;
11781       }
11782       Opcode = X86ISD::OR;
11783       break;
11784     }
11785     }
11786
11787     NumOperands = 2;
11788     break;
11789   case X86ISD::ADD:
11790   case X86ISD::SUB:
11791   case X86ISD::INC:
11792   case X86ISD::DEC:
11793   case X86ISD::OR:
11794   case X86ISD::XOR:
11795   case X86ISD::AND:
11796     return SDValue(Op.getNode(), 1);
11797   default:
11798   default_case:
11799     break;
11800   }
11801
11802   // If we found that truncation is beneficial, perform the truncation and
11803   // update 'Op'.
11804   if (NeedTruncation) {
11805     EVT VT = Op.getValueType();
11806     SDValue WideVal = Op->getOperand(0);
11807     EVT WideVT = WideVal.getValueType();
11808     unsigned ConvertedOp = 0;
11809     // Use a target machine opcode to prevent further DAGCombine
11810     // optimizations that may separate the arithmetic operations
11811     // from the setcc node.
11812     switch (WideVal.getOpcode()) {
11813       default: break;
11814       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11815       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11816       case ISD::AND: ConvertedOp = X86ISD::AND; break;
11817       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
11818       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11819     }
11820
11821     if (ConvertedOp) {
11822       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11823       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11824         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11825         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11826         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11827       }
11828     }
11829   }
11830
11831   if (Opcode == 0)
11832     // Emit a CMP with 0, which is the TEST pattern.
11833     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11834                        DAG.getConstant(0, Op.getValueType()));
11835
11836   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11837   SmallVector<SDValue, 4> Ops;
11838   for (unsigned i = 0; i != NumOperands; ++i)
11839     Ops.push_back(Op.getOperand(i));
11840
11841   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11842   DAG.ReplaceAllUsesWith(Op, New);
11843   return SDValue(New.getNode(), 1);
11844 }
11845
11846 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11847 /// equivalent.
11848 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11849                                    SDLoc dl, SelectionDAG &DAG) const {
11850   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11851     if (C->getAPIntValue() == 0)
11852       return EmitTest(Op0, X86CC, dl, DAG);
11853
11854      if (Op0.getValueType() == MVT::i1)
11855        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11856   }
11857  
11858   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11859        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11860     // Do the comparison at i32 if it's smaller, besides the Atom case. 
11861     // This avoids subregister aliasing issues. Keep the smaller reference 
11862     // if we're optimizing for size, however, as that'll allow better folding 
11863     // of memory operations.
11864     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11865         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11866              AttributeSet::FunctionIndex, Attribute::MinSize) &&
11867         !Subtarget->isAtom()) {
11868       unsigned ExtendOp =
11869           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11870       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11871       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11872     }
11873     // Use SUB instead of CMP to enable CSE between SUB and CMP.
11874     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11875     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11876                               Op0, Op1);
11877     return SDValue(Sub.getNode(), 1);
11878   }
11879   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11880 }
11881
11882 /// Convert a comparison if required by the subtarget.
11883 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11884                                                  SelectionDAG &DAG) const {
11885   // If the subtarget does not support the FUCOMI instruction, floating-point
11886   // comparisons have to be converted.
11887   if (Subtarget->hasCMov() ||
11888       Cmp.getOpcode() != X86ISD::CMP ||
11889       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11890       !Cmp.getOperand(1).getValueType().isFloatingPoint())
11891     return Cmp;
11892
11893   // The instruction selector will select an FUCOM instruction instead of
11894   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11895   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11896   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11897   SDLoc dl(Cmp);
11898   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11899   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11900   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11901                             DAG.getConstant(8, MVT::i8));
11902   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11903   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11904 }
11905
11906 static bool isAllOnes(SDValue V) {
11907   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11908   return C && C->isAllOnesValue();
11909 }
11910
11911 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11912 /// if it's possible.
11913 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11914                                      SDLoc dl, SelectionDAG &DAG) const {
11915   SDValue Op0 = And.getOperand(0);
11916   SDValue Op1 = And.getOperand(1);
11917   if (Op0.getOpcode() == ISD::TRUNCATE)
11918     Op0 = Op0.getOperand(0);
11919   if (Op1.getOpcode() == ISD::TRUNCATE)
11920     Op1 = Op1.getOperand(0);
11921
11922   SDValue LHS, RHS;
11923   if (Op1.getOpcode() == ISD::SHL)
11924     std::swap(Op0, Op1);
11925   if (Op0.getOpcode() == ISD::SHL) {
11926     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11927       if (And00C->getZExtValue() == 1) {
11928         // If we looked past a truncate, check that it's only truncating away
11929         // known zeros.
11930         unsigned BitWidth = Op0.getValueSizeInBits();
11931         unsigned AndBitWidth = And.getValueSizeInBits();
11932         if (BitWidth > AndBitWidth) {
11933           APInt Zeros, Ones;
11934           DAG.computeKnownBits(Op0, Zeros, Ones);
11935           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11936             return SDValue();
11937         }
11938         LHS = Op1;
11939         RHS = Op0.getOperand(1);
11940       }
11941   } else if (Op1.getOpcode() == ISD::Constant) {
11942     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11943     uint64_t AndRHSVal = AndRHS->getZExtValue();
11944     SDValue AndLHS = Op0;
11945
11946     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11947       LHS = AndLHS.getOperand(0);
11948       RHS = AndLHS.getOperand(1);
11949     }
11950
11951     // Use BT if the immediate can't be encoded in a TEST instruction.
11952     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
11953       LHS = AndLHS;
11954       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
11955     }
11956   }
11957
11958   if (LHS.getNode()) {
11959     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
11960     // instruction.  Since the shift amount is in-range-or-undefined, we know
11961     // that doing a bittest on the i32 value is ok.  We extend to i32 because
11962     // the encoding for the i16 version is larger than the i32 version.
11963     // Also promote i16 to i32 for performance / code size reason.
11964     if (LHS.getValueType() == MVT::i8 ||
11965         LHS.getValueType() == MVT::i16)
11966       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
11967
11968     // If the operand types disagree, extend the shift amount to match.  Since
11969     // BT ignores high bits (like shifts) we can use anyextend.
11970     if (LHS.getValueType() != RHS.getValueType())
11971       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
11972
11973     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
11974     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
11975     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11976                        DAG.getConstant(Cond, MVT::i8), BT);
11977   }
11978
11979   return SDValue();
11980 }
11981
11982 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
11983 /// mask CMPs.
11984 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
11985                               SDValue &Op1) {
11986   unsigned SSECC;
11987   bool Swap = false;
11988
11989   // SSE Condition code mapping:
11990   //  0 - EQ
11991   //  1 - LT
11992   //  2 - LE
11993   //  3 - UNORD
11994   //  4 - NEQ
11995   //  5 - NLT
11996   //  6 - NLE
11997   //  7 - ORD
11998   switch (SetCCOpcode) {
11999   default: llvm_unreachable("Unexpected SETCC condition");
12000   case ISD::SETOEQ:
12001   case ISD::SETEQ:  SSECC = 0; break;
12002   case ISD::SETOGT:
12003   case ISD::SETGT:  Swap = true; // Fallthrough
12004   case ISD::SETLT:
12005   case ISD::SETOLT: SSECC = 1; break;
12006   case ISD::SETOGE:
12007   case ISD::SETGE:  Swap = true; // Fallthrough
12008   case ISD::SETLE:
12009   case ISD::SETOLE: SSECC = 2; break;
12010   case ISD::SETUO:  SSECC = 3; break;
12011   case ISD::SETUNE:
12012   case ISD::SETNE:  SSECC = 4; break;
12013   case ISD::SETULE: Swap = true; // Fallthrough
12014   case ISD::SETUGE: SSECC = 5; break;
12015   case ISD::SETULT: Swap = true; // Fallthrough
12016   case ISD::SETUGT: SSECC = 6; break;
12017   case ISD::SETO:   SSECC = 7; break;
12018   case ISD::SETUEQ:
12019   case ISD::SETONE: SSECC = 8; break;
12020   }
12021   if (Swap)
12022     std::swap(Op0, Op1);
12023
12024   return SSECC;
12025 }
12026
12027 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12028 // ones, and then concatenate the result back.
12029 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12030   MVT VT = Op.getSimpleValueType();
12031
12032   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12033          "Unsupported value type for operation");
12034
12035   unsigned NumElems = VT.getVectorNumElements();
12036   SDLoc dl(Op);
12037   SDValue CC = Op.getOperand(2);
12038
12039   // Extract the LHS vectors
12040   SDValue LHS = Op.getOperand(0);
12041   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12042   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12043
12044   // Extract the RHS vectors
12045   SDValue RHS = Op.getOperand(1);
12046   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12047   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12048
12049   // Issue the operation on the smaller types and concatenate the result back
12050   MVT EltVT = VT.getVectorElementType();
12051   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12052   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12053                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12054                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12055 }
12056
12057 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12058                                      const X86Subtarget *Subtarget) {
12059   SDValue Op0 = Op.getOperand(0);
12060   SDValue Op1 = Op.getOperand(1);
12061   SDValue CC = Op.getOperand(2);
12062   MVT VT = Op.getSimpleValueType();
12063   SDLoc dl(Op);
12064
12065   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12066          Op.getValueType().getScalarType() == MVT::i1 &&
12067          "Cannot set masked compare for this operation");
12068
12069   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12070   unsigned  Opc = 0;
12071   bool Unsigned = false;
12072   bool Swap = false;
12073   unsigned SSECC;
12074   switch (SetCCOpcode) {
12075   default: llvm_unreachable("Unexpected SETCC condition");
12076   case ISD::SETNE:  SSECC = 4; break;
12077   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12078   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12079   case ISD::SETLT:  Swap = true; //fall-through
12080   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12081   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12082   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12083   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12084   case ISD::SETULE: Unsigned = true; //fall-through
12085   case ISD::SETLE:  SSECC = 2; break;
12086   }
12087
12088   if (Swap)
12089     std::swap(Op0, Op1);
12090   if (Opc)
12091     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12092   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12093   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12094                      DAG.getConstant(SSECC, MVT::i8));
12095 }
12096
12097 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12098 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12099 /// return an empty value.
12100 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12101 {
12102   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12103   if (!BV)
12104     return SDValue();
12105
12106   MVT VT = Op1.getSimpleValueType();
12107   MVT EVT = VT.getVectorElementType();
12108   unsigned n = VT.getVectorNumElements();
12109   SmallVector<SDValue, 8> ULTOp1;
12110
12111   for (unsigned i = 0; i < n; ++i) {
12112     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12113     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12114       return SDValue();
12115
12116     // Avoid underflow.
12117     APInt Val = Elt->getAPIntValue();
12118     if (Val == 0)
12119       return SDValue();
12120
12121     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12122   }
12123
12124   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12125 }
12126
12127 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12128                            SelectionDAG &DAG) {
12129   SDValue Op0 = Op.getOperand(0);
12130   SDValue Op1 = Op.getOperand(1);
12131   SDValue CC = Op.getOperand(2);
12132   MVT VT = Op.getSimpleValueType();
12133   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12134   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12135   SDLoc dl(Op);
12136
12137   if (isFP) {
12138 #ifndef NDEBUG
12139     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12140     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12141 #endif
12142
12143     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12144     unsigned Opc = X86ISD::CMPP;
12145     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12146       assert(VT.getVectorNumElements() <= 16);
12147       Opc = X86ISD::CMPM;
12148     }
12149     // In the two special cases we can't handle, emit two comparisons.
12150     if (SSECC == 8) {
12151       unsigned CC0, CC1;
12152       unsigned CombineOpc;
12153       if (SetCCOpcode == ISD::SETUEQ) {
12154         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12155       } else {
12156         assert(SetCCOpcode == ISD::SETONE);
12157         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12158       }
12159
12160       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12161                                  DAG.getConstant(CC0, MVT::i8));
12162       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12163                                  DAG.getConstant(CC1, MVT::i8));
12164       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12165     }
12166     // Handle all other FP comparisons here.
12167     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12168                        DAG.getConstant(SSECC, MVT::i8));
12169   }
12170
12171   // Break 256-bit integer vector compare into smaller ones.
12172   if (VT.is256BitVector() && !Subtarget->hasInt256())
12173     return Lower256IntVSETCC(Op, DAG);
12174
12175   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12176   EVT OpVT = Op1.getValueType();
12177   if (Subtarget->hasAVX512()) {
12178     if (Op1.getValueType().is512BitVector() ||
12179         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12180       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12181
12182     // In AVX-512 architecture setcc returns mask with i1 elements,
12183     // But there is no compare instruction for i8 and i16 elements.
12184     // We are not talking about 512-bit operands in this case, these
12185     // types are illegal.
12186     if (MaskResult &&
12187         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12188          OpVT.getVectorElementType().getSizeInBits() >= 8))
12189       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12190                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12191   }
12192
12193   // We are handling one of the integer comparisons here.  Since SSE only has
12194   // GT and EQ comparisons for integer, swapping operands and multiple
12195   // operations may be required for some comparisons.
12196   unsigned Opc;
12197   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12198   bool Subus = false;
12199
12200   switch (SetCCOpcode) {
12201   default: llvm_unreachable("Unexpected SETCC condition");
12202   case ISD::SETNE:  Invert = true;
12203   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12204   case ISD::SETLT:  Swap = true;
12205   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12206   case ISD::SETGE:  Swap = true;
12207   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12208                     Invert = true; break;
12209   case ISD::SETULT: Swap = true;
12210   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12211                     FlipSigns = true; break;
12212   case ISD::SETUGE: Swap = true;
12213   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12214                     FlipSigns = true; Invert = true; break;
12215   }
12216
12217   // Special case: Use min/max operations for SETULE/SETUGE
12218   MVT VET = VT.getVectorElementType();
12219   bool hasMinMax =
12220        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12221     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12222
12223   if (hasMinMax) {
12224     switch (SetCCOpcode) {
12225     default: break;
12226     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12227     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12228     }
12229
12230     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12231   }
12232
12233   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12234   if (!MinMax && hasSubus) {
12235     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12236     // Op0 u<= Op1:
12237     //   t = psubus Op0, Op1
12238     //   pcmpeq t, <0..0>
12239     switch (SetCCOpcode) {
12240     default: break;
12241     case ISD::SETULT: {
12242       // If the comparison is against a constant we can turn this into a
12243       // setule.  With psubus, setule does not require a swap.  This is
12244       // beneficial because the constant in the register is no longer
12245       // destructed as the destination so it can be hoisted out of a loop.
12246       // Only do this pre-AVX since vpcmp* is no longer destructive.
12247       if (Subtarget->hasAVX())
12248         break;
12249       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12250       if (ULEOp1.getNode()) {
12251         Op1 = ULEOp1;
12252         Subus = true; Invert = false; Swap = false;
12253       }
12254       break;
12255     }
12256     // Psubus is better than flip-sign because it requires no inversion.
12257     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12258     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12259     }
12260
12261     if (Subus) {
12262       Opc = X86ISD::SUBUS;
12263       FlipSigns = false;
12264     }
12265   }
12266
12267   if (Swap)
12268     std::swap(Op0, Op1);
12269
12270   // Check that the operation in question is available (most are plain SSE2,
12271   // but PCMPGTQ and PCMPEQQ have different requirements).
12272   if (VT == MVT::v2i64) {
12273     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12274       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12275
12276       // First cast everything to the right type.
12277       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12278       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12279
12280       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12281       // bits of the inputs before performing those operations. The lower
12282       // compare is always unsigned.
12283       SDValue SB;
12284       if (FlipSigns) {
12285         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12286       } else {
12287         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12288         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12289         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12290                          Sign, Zero, Sign, Zero);
12291       }
12292       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12293       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12294
12295       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12296       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12297       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12298
12299       // Create masks for only the low parts/high parts of the 64 bit integers.
12300       static const int MaskHi[] = { 1, 1, 3, 3 };
12301       static const int MaskLo[] = { 0, 0, 2, 2 };
12302       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12303       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12304       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12305
12306       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12307       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12308
12309       if (Invert)
12310         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12311
12312       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12313     }
12314
12315     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12316       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12317       // pcmpeqd + pshufd + pand.
12318       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12319
12320       // First cast everything to the right type.
12321       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12322       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12323
12324       // Do the compare.
12325       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12326
12327       // Make sure the lower and upper halves are both all-ones.
12328       static const int Mask[] = { 1, 0, 3, 2 };
12329       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12330       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12331
12332       if (Invert)
12333         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12334
12335       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12336     }
12337   }
12338
12339   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12340   // bits of the inputs before performing those operations.
12341   if (FlipSigns) {
12342     EVT EltVT = VT.getVectorElementType();
12343     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12344     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12345     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12346   }
12347
12348   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12349
12350   // If the logical-not of the result is required, perform that now.
12351   if (Invert)
12352     Result = DAG.getNOT(dl, Result, VT);
12353
12354   if (MinMax)
12355     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12356
12357   if (Subus)
12358     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12359                          getZeroVector(VT, Subtarget, DAG, dl));
12360
12361   return Result;
12362 }
12363
12364 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12365
12366   MVT VT = Op.getSimpleValueType();
12367
12368   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12369
12370   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12371          && "SetCC type must be 8-bit or 1-bit integer");
12372   SDValue Op0 = Op.getOperand(0);
12373   SDValue Op1 = Op.getOperand(1);
12374   SDLoc dl(Op);
12375   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12376
12377   // Optimize to BT if possible.
12378   // Lower (X & (1 << N)) == 0 to BT(X, N).
12379   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12380   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12381   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12382       Op1.getOpcode() == ISD::Constant &&
12383       cast<ConstantSDNode>(Op1)->isNullValue() &&
12384       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12385     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12386     if (NewSetCC.getNode())
12387       return NewSetCC;
12388   }
12389
12390   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12391   // these.
12392   if (Op1.getOpcode() == ISD::Constant &&
12393       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12394        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12395       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12396
12397     // If the input is a setcc, then reuse the input setcc or use a new one with
12398     // the inverted condition.
12399     if (Op0.getOpcode() == X86ISD::SETCC) {
12400       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12401       bool Invert = (CC == ISD::SETNE) ^
12402         cast<ConstantSDNode>(Op1)->isNullValue();
12403       if (!Invert)
12404         return Op0;
12405
12406       CCode = X86::GetOppositeBranchCondition(CCode);
12407       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12408                                   DAG.getConstant(CCode, MVT::i8),
12409                                   Op0.getOperand(1));
12410       if (VT == MVT::i1)
12411         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12412       return SetCC;
12413     }
12414   }
12415   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12416       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12417       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12418
12419     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12420     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12421   }
12422
12423   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12424   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12425   if (X86CC == X86::COND_INVALID)
12426     return SDValue();
12427
12428   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12429   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12430   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12431                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12432   if (VT == MVT::i1)
12433     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12434   return SetCC;
12435 }
12436
12437 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12438 static bool isX86LogicalCmp(SDValue Op) {
12439   unsigned Opc = Op.getNode()->getOpcode();
12440   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12441       Opc == X86ISD::SAHF)
12442     return true;
12443   if (Op.getResNo() == 1 &&
12444       (Opc == X86ISD::ADD ||
12445        Opc == X86ISD::SUB ||
12446        Opc == X86ISD::ADC ||
12447        Opc == X86ISD::SBB ||
12448        Opc == X86ISD::SMUL ||
12449        Opc == X86ISD::UMUL ||
12450        Opc == X86ISD::INC ||
12451        Opc == X86ISD::DEC ||
12452        Opc == X86ISD::OR ||
12453        Opc == X86ISD::XOR ||
12454        Opc == X86ISD::AND))
12455     return true;
12456
12457   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12458     return true;
12459
12460   return false;
12461 }
12462
12463 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12464   if (V.getOpcode() != ISD::TRUNCATE)
12465     return false;
12466
12467   SDValue VOp0 = V.getOperand(0);
12468   unsigned InBits = VOp0.getValueSizeInBits();
12469   unsigned Bits = V.getValueSizeInBits();
12470   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12471 }
12472
12473 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12474   bool addTest = true;
12475   SDValue Cond  = Op.getOperand(0);
12476   SDValue Op1 = Op.getOperand(1);
12477   SDValue Op2 = Op.getOperand(2);
12478   SDLoc DL(Op);
12479   EVT VT = Op1.getValueType();
12480   SDValue CC;
12481
12482   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12483   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12484   // sequence later on.
12485   if (Cond.getOpcode() == ISD::SETCC &&
12486       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12487        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12488       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12489     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12490     int SSECC = translateX86FSETCC(
12491         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12492
12493     if (SSECC != 8) {
12494       if (Subtarget->hasAVX512()) {
12495         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12496                                   DAG.getConstant(SSECC, MVT::i8));
12497         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12498       }
12499       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12500                                 DAG.getConstant(SSECC, MVT::i8));
12501       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12502       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12503       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12504     }
12505   }
12506
12507   if (Cond.getOpcode() == ISD::SETCC) {
12508     SDValue NewCond = LowerSETCC(Cond, DAG);
12509     if (NewCond.getNode())
12510       Cond = NewCond;
12511   }
12512
12513   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12514   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12515   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12516   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12517   if (Cond.getOpcode() == X86ISD::SETCC &&
12518       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12519       isZero(Cond.getOperand(1).getOperand(1))) {
12520     SDValue Cmp = Cond.getOperand(1);
12521
12522     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12523
12524     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12525         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12526       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12527
12528       SDValue CmpOp0 = Cmp.getOperand(0);
12529       // Apply further optimizations for special cases
12530       // (select (x != 0), -1, 0) -> neg & sbb
12531       // (select (x == 0), 0, -1) -> neg & sbb
12532       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12533         if (YC->isNullValue() &&
12534             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12535           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12536           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12537                                     DAG.getConstant(0, CmpOp0.getValueType()),
12538                                     CmpOp0);
12539           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12540                                     DAG.getConstant(X86::COND_B, MVT::i8),
12541                                     SDValue(Neg.getNode(), 1));
12542           return Res;
12543         }
12544
12545       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12546                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12547       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12548
12549       SDValue Res =   // Res = 0 or -1.
12550         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12551                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12552
12553       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12554         Res = DAG.getNOT(DL, Res, Res.getValueType());
12555
12556       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12557       if (!N2C || !N2C->isNullValue())
12558         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12559       return Res;
12560     }
12561   }
12562
12563   // Look past (and (setcc_carry (cmp ...)), 1).
12564   if (Cond.getOpcode() == ISD::AND &&
12565       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12566     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12567     if (C && C->getAPIntValue() == 1)
12568       Cond = Cond.getOperand(0);
12569   }
12570
12571   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12572   // setting operand in place of the X86ISD::SETCC.
12573   unsigned CondOpcode = Cond.getOpcode();
12574   if (CondOpcode == X86ISD::SETCC ||
12575       CondOpcode == X86ISD::SETCC_CARRY) {
12576     CC = Cond.getOperand(0);
12577
12578     SDValue Cmp = Cond.getOperand(1);
12579     unsigned Opc = Cmp.getOpcode();
12580     MVT VT = Op.getSimpleValueType();
12581
12582     bool IllegalFPCMov = false;
12583     if (VT.isFloatingPoint() && !VT.isVector() &&
12584         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12585       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12586
12587     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12588         Opc == X86ISD::BT) { // FIXME
12589       Cond = Cmp;
12590       addTest = false;
12591     }
12592   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12593              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12594              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12595               Cond.getOperand(0).getValueType() != MVT::i8)) {
12596     SDValue LHS = Cond.getOperand(0);
12597     SDValue RHS = Cond.getOperand(1);
12598     unsigned X86Opcode;
12599     unsigned X86Cond;
12600     SDVTList VTs;
12601     switch (CondOpcode) {
12602     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12603     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12604     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12605     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12606     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12607     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12608     default: llvm_unreachable("unexpected overflowing operator");
12609     }
12610     if (CondOpcode == ISD::UMULO)
12611       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12612                           MVT::i32);
12613     else
12614       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12615
12616     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12617
12618     if (CondOpcode == ISD::UMULO)
12619       Cond = X86Op.getValue(2);
12620     else
12621       Cond = X86Op.getValue(1);
12622
12623     CC = DAG.getConstant(X86Cond, MVT::i8);
12624     addTest = false;
12625   }
12626
12627   if (addTest) {
12628     // Look pass the truncate if the high bits are known zero.
12629     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12630         Cond = Cond.getOperand(0);
12631
12632     // We know the result of AND is compared against zero. Try to match
12633     // it to BT.
12634     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12635       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12636       if (NewSetCC.getNode()) {
12637         CC = NewSetCC.getOperand(0);
12638         Cond = NewSetCC.getOperand(1);
12639         addTest = false;
12640       }
12641     }
12642   }
12643
12644   if (addTest) {
12645     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12646     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12647   }
12648
12649   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12650   // a <  b ?  0 : -1 -> RES = setcc_carry
12651   // a >= b ? -1 :  0 -> RES = setcc_carry
12652   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12653   if (Cond.getOpcode() == X86ISD::SUB) {
12654     Cond = ConvertCmpIfNecessary(Cond, DAG);
12655     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12656
12657     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12658         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12659       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12660                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12661       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12662         return DAG.getNOT(DL, Res, Res.getValueType());
12663       return Res;
12664     }
12665   }
12666
12667   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12668   // widen the cmov and push the truncate through. This avoids introducing a new
12669   // branch during isel and doesn't add any extensions.
12670   if (Op.getValueType() == MVT::i8 &&
12671       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12672     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12673     if (T1.getValueType() == T2.getValueType() &&
12674         // Blacklist CopyFromReg to avoid partial register stalls.
12675         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12676       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12677       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12678       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12679     }
12680   }
12681
12682   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12683   // condition is true.
12684   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12685   SDValue Ops[] = { Op2, Op1, CC, Cond };
12686   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12687 }
12688
12689 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12690   MVT VT = Op->getSimpleValueType(0);
12691   SDValue In = Op->getOperand(0);
12692   MVT InVT = In.getSimpleValueType();
12693   SDLoc dl(Op);
12694
12695   unsigned int NumElts = VT.getVectorNumElements();
12696   if (NumElts != 8 && NumElts != 16)
12697     return SDValue();
12698
12699   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12700     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12701
12702   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12703   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12704
12705   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12706   Constant *C = ConstantInt::get(*DAG.getContext(),
12707     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12708
12709   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12710   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12711   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12712                           MachinePointerInfo::getConstantPool(),
12713                           false, false, false, Alignment);
12714   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12715   if (VT.is512BitVector())
12716     return Brcst;
12717   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12718 }
12719
12720 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12721                                 SelectionDAG &DAG) {
12722   MVT VT = Op->getSimpleValueType(0);
12723   SDValue In = Op->getOperand(0);
12724   MVT InVT = In.getSimpleValueType();
12725   SDLoc dl(Op);
12726
12727   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12728     return LowerSIGN_EXTEND_AVX512(Op, DAG);
12729
12730   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12731       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12732       (VT != MVT::v16i16 || InVT != MVT::v16i8))
12733     return SDValue();
12734
12735   if (Subtarget->hasInt256())
12736     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12737
12738   // Optimize vectors in AVX mode
12739   // Sign extend  v8i16 to v8i32 and
12740   //              v4i32 to v4i64
12741   //
12742   // Divide input vector into two parts
12743   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12744   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12745   // concat the vectors to original VT
12746
12747   unsigned NumElems = InVT.getVectorNumElements();
12748   SDValue Undef = DAG.getUNDEF(InVT);
12749
12750   SmallVector<int,8> ShufMask1(NumElems, -1);
12751   for (unsigned i = 0; i != NumElems/2; ++i)
12752     ShufMask1[i] = i;
12753
12754   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12755
12756   SmallVector<int,8> ShufMask2(NumElems, -1);
12757   for (unsigned i = 0; i != NumElems/2; ++i)
12758     ShufMask2[i] = i + NumElems/2;
12759
12760   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12761
12762   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12763                                 VT.getVectorNumElements()/2);
12764
12765   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12766   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12767
12768   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12769 }
12770
12771 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12772 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12773 // from the AND / OR.
12774 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12775   Opc = Op.getOpcode();
12776   if (Opc != ISD::OR && Opc != ISD::AND)
12777     return false;
12778   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12779           Op.getOperand(0).hasOneUse() &&
12780           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12781           Op.getOperand(1).hasOneUse());
12782 }
12783
12784 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12785 // 1 and that the SETCC node has a single use.
12786 static bool isXor1OfSetCC(SDValue Op) {
12787   if (Op.getOpcode() != ISD::XOR)
12788     return false;
12789   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12790   if (N1C && N1C->getAPIntValue() == 1) {
12791     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12792       Op.getOperand(0).hasOneUse();
12793   }
12794   return false;
12795 }
12796
12797 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12798   bool addTest = true;
12799   SDValue Chain = Op.getOperand(0);
12800   SDValue Cond  = Op.getOperand(1);
12801   SDValue Dest  = Op.getOperand(2);
12802   SDLoc dl(Op);
12803   SDValue CC;
12804   bool Inverted = false;
12805
12806   if (Cond.getOpcode() == ISD::SETCC) {
12807     // Check for setcc([su]{add,sub,mul}o == 0).
12808     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12809         isa<ConstantSDNode>(Cond.getOperand(1)) &&
12810         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12811         Cond.getOperand(0).getResNo() == 1 &&
12812         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12813          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12814          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12815          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12816          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12817          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12818       Inverted = true;
12819       Cond = Cond.getOperand(0);
12820     } else {
12821       SDValue NewCond = LowerSETCC(Cond, DAG);
12822       if (NewCond.getNode())
12823         Cond = NewCond;
12824     }
12825   }
12826 #if 0
12827   // FIXME: LowerXALUO doesn't handle these!!
12828   else if (Cond.getOpcode() == X86ISD::ADD  ||
12829            Cond.getOpcode() == X86ISD::SUB  ||
12830            Cond.getOpcode() == X86ISD::SMUL ||
12831            Cond.getOpcode() == X86ISD::UMUL)
12832     Cond = LowerXALUO(Cond, DAG);
12833 #endif
12834
12835   // Look pass (and (setcc_carry (cmp ...)), 1).
12836   if (Cond.getOpcode() == ISD::AND &&
12837       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12838     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12839     if (C && C->getAPIntValue() == 1)
12840       Cond = Cond.getOperand(0);
12841   }
12842
12843   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12844   // setting operand in place of the X86ISD::SETCC.
12845   unsigned CondOpcode = Cond.getOpcode();
12846   if (CondOpcode == X86ISD::SETCC ||
12847       CondOpcode == X86ISD::SETCC_CARRY) {
12848     CC = Cond.getOperand(0);
12849
12850     SDValue Cmp = Cond.getOperand(1);
12851     unsigned Opc = Cmp.getOpcode();
12852     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12853     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12854       Cond = Cmp;
12855       addTest = false;
12856     } else {
12857       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12858       default: break;
12859       case X86::COND_O:
12860       case X86::COND_B:
12861         // These can only come from an arithmetic instruction with overflow,
12862         // e.g. SADDO, UADDO.
12863         Cond = Cond.getNode()->getOperand(1);
12864         addTest = false;
12865         break;
12866       }
12867     }
12868   }
12869   CondOpcode = Cond.getOpcode();
12870   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12871       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12872       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12873        Cond.getOperand(0).getValueType() != MVT::i8)) {
12874     SDValue LHS = Cond.getOperand(0);
12875     SDValue RHS = Cond.getOperand(1);
12876     unsigned X86Opcode;
12877     unsigned X86Cond;
12878     SDVTList VTs;
12879     // Keep this in sync with LowerXALUO, otherwise we might create redundant
12880     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12881     // X86ISD::INC).
12882     switch (CondOpcode) {
12883     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12884     case ISD::SADDO:
12885       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12886         if (C->isOne()) {
12887           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12888           break;
12889         }
12890       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12891     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12892     case ISD::SSUBO:
12893       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12894         if (C->isOne()) {
12895           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12896           break;
12897         }
12898       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12899     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12900     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12901     default: llvm_unreachable("unexpected overflowing operator");
12902     }
12903     if (Inverted)
12904       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12905     if (CondOpcode == ISD::UMULO)
12906       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12907                           MVT::i32);
12908     else
12909       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12910
12911     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12912
12913     if (CondOpcode == ISD::UMULO)
12914       Cond = X86Op.getValue(2);
12915     else
12916       Cond = X86Op.getValue(1);
12917
12918     CC = DAG.getConstant(X86Cond, MVT::i8);
12919     addTest = false;
12920   } else {
12921     unsigned CondOpc;
12922     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12923       SDValue Cmp = Cond.getOperand(0).getOperand(1);
12924       if (CondOpc == ISD::OR) {
12925         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12926         // two branches instead of an explicit OR instruction with a
12927         // separate test.
12928         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12929             isX86LogicalCmp(Cmp)) {
12930           CC = Cond.getOperand(0).getOperand(0);
12931           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12932                               Chain, Dest, CC, Cmp);
12933           CC = Cond.getOperand(1).getOperand(0);
12934           Cond = Cmp;
12935           addTest = false;
12936         }
12937       } else { // ISD::AND
12938         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12939         // two branches instead of an explicit AND instruction with a
12940         // separate test. However, we only do this if this block doesn't
12941         // have a fall-through edge, because this requires an explicit
12942         // jmp when the condition is false.
12943         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12944             isX86LogicalCmp(Cmp) &&
12945             Op.getNode()->hasOneUse()) {
12946           X86::CondCode CCode =
12947             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12948           CCode = X86::GetOppositeBranchCondition(CCode);
12949           CC = DAG.getConstant(CCode, MVT::i8);
12950           SDNode *User = *Op.getNode()->use_begin();
12951           // Look for an unconditional branch following this conditional branch.
12952           // We need this because we need to reverse the successors in order
12953           // to implement FCMP_OEQ.
12954           if (User->getOpcode() == ISD::BR) {
12955             SDValue FalseBB = User->getOperand(1);
12956             SDNode *NewBR =
12957               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12958             assert(NewBR == User);
12959             (void)NewBR;
12960             Dest = FalseBB;
12961
12962             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12963                                 Chain, Dest, CC, Cmp);
12964             X86::CondCode CCode =
12965               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
12966             CCode = X86::GetOppositeBranchCondition(CCode);
12967             CC = DAG.getConstant(CCode, MVT::i8);
12968             Cond = Cmp;
12969             addTest = false;
12970           }
12971         }
12972       }
12973     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
12974       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
12975       // It should be transformed during dag combiner except when the condition
12976       // is set by a arithmetics with overflow node.
12977       X86::CondCode CCode =
12978         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12979       CCode = X86::GetOppositeBranchCondition(CCode);
12980       CC = DAG.getConstant(CCode, MVT::i8);
12981       Cond = Cond.getOperand(0).getOperand(1);
12982       addTest = false;
12983     } else if (Cond.getOpcode() == ISD::SETCC &&
12984                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
12985       // For FCMP_OEQ, we can emit
12986       // two branches instead of an explicit AND instruction with a
12987       // separate test. However, we only do this if this block doesn't
12988       // have a fall-through edge, because this requires an explicit
12989       // jmp when the condition is false.
12990       if (Op.getNode()->hasOneUse()) {
12991         SDNode *User = *Op.getNode()->use_begin();
12992         // Look for an unconditional branch following this conditional branch.
12993         // We need this because we need to reverse the successors in order
12994         // to implement FCMP_OEQ.
12995         if (User->getOpcode() == ISD::BR) {
12996           SDValue FalseBB = User->getOperand(1);
12997           SDNode *NewBR =
12998             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12999           assert(NewBR == User);
13000           (void)NewBR;
13001           Dest = FalseBB;
13002
13003           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13004                                     Cond.getOperand(0), Cond.getOperand(1));
13005           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13006           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13007           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13008                               Chain, Dest, CC, Cmp);
13009           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13010           Cond = Cmp;
13011           addTest = false;
13012         }
13013       }
13014     } else if (Cond.getOpcode() == ISD::SETCC &&
13015                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13016       // For FCMP_UNE, we can emit
13017       // two branches instead of an explicit AND instruction with a
13018       // separate test. However, we only do this if this block doesn't
13019       // have a fall-through edge, because this requires an explicit
13020       // jmp when the condition is false.
13021       if (Op.getNode()->hasOneUse()) {
13022         SDNode *User = *Op.getNode()->use_begin();
13023         // Look for an unconditional branch following this conditional branch.
13024         // We need this because we need to reverse the successors in order
13025         // to implement FCMP_UNE.
13026         if (User->getOpcode() == ISD::BR) {
13027           SDValue FalseBB = User->getOperand(1);
13028           SDNode *NewBR =
13029             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13030           assert(NewBR == User);
13031           (void)NewBR;
13032
13033           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13034                                     Cond.getOperand(0), Cond.getOperand(1));
13035           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13036           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13037           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13038                               Chain, Dest, CC, Cmp);
13039           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13040           Cond = Cmp;
13041           addTest = false;
13042           Dest = FalseBB;
13043         }
13044       }
13045     }
13046   }
13047
13048   if (addTest) {
13049     // Look pass the truncate if the high bits are known zero.
13050     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13051         Cond = Cond.getOperand(0);
13052
13053     // We know the result of AND is compared against zero. Try to match
13054     // it to BT.
13055     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13056       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13057       if (NewSetCC.getNode()) {
13058         CC = NewSetCC.getOperand(0);
13059         Cond = NewSetCC.getOperand(1);
13060         addTest = false;
13061       }
13062     }
13063   }
13064
13065   if (addTest) {
13066     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13067     CC = DAG.getConstant(X86Cond, MVT::i8);
13068     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13069   }
13070   Cond = ConvertCmpIfNecessary(Cond, DAG);
13071   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13072                      Chain, Dest, CC, Cond);
13073 }
13074
13075 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13076 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13077 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13078 // that the guard pages used by the OS virtual memory manager are allocated in
13079 // correct sequence.
13080 SDValue
13081 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13082                                            SelectionDAG &DAG) const {
13083   MachineFunction &MF = DAG.getMachineFunction();
13084   bool SplitStack = MF.shouldSplitStack();
13085   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13086                SplitStack;
13087   SDLoc dl(Op);
13088
13089   if (!Lower) {
13090     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13091     SDNode* Node = Op.getNode();
13092
13093     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13094     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13095         " not tell us which reg is the stack pointer!");
13096     EVT VT = Node->getValueType(0);
13097     SDValue Tmp1 = SDValue(Node, 0);
13098     SDValue Tmp2 = SDValue(Node, 1);
13099     SDValue Tmp3 = Node->getOperand(2);
13100     SDValue Chain = Tmp1.getOperand(0);
13101
13102     // Chain the dynamic stack allocation so that it doesn't modify the stack
13103     // pointer when other instructions are using the stack.
13104     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13105         SDLoc(Node));
13106
13107     SDValue Size = Tmp2.getOperand(1);
13108     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13109     Chain = SP.getValue(1);
13110     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13111     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13112     unsigned StackAlign = TFI.getStackAlignment();
13113     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13114     if (Align > StackAlign)
13115       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13116           DAG.getConstant(-(uint64_t)Align, VT));
13117     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13118
13119     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13120         DAG.getIntPtrConstant(0, true), SDValue(),
13121         SDLoc(Node));
13122
13123     SDValue Ops[2] = { Tmp1, Tmp2 };
13124     return DAG.getMergeValues(Ops, dl);
13125   }
13126
13127   // Get the inputs.
13128   SDValue Chain = Op.getOperand(0);
13129   SDValue Size  = Op.getOperand(1);
13130   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13131   EVT VT = Op.getNode()->getValueType(0);
13132
13133   bool Is64Bit = Subtarget->is64Bit();
13134   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13135
13136   if (SplitStack) {
13137     MachineRegisterInfo &MRI = MF.getRegInfo();
13138
13139     if (Is64Bit) {
13140       // The 64 bit implementation of segmented stacks needs to clobber both r10
13141       // r11. This makes it impossible to use it along with nested parameters.
13142       const Function *F = MF.getFunction();
13143
13144       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13145            I != E; ++I)
13146         if (I->hasNestAttr())
13147           report_fatal_error("Cannot use segmented stacks with functions that "
13148                              "have nested arguments.");
13149     }
13150
13151     const TargetRegisterClass *AddrRegClass =
13152       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13153     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13154     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13155     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13156                                 DAG.getRegister(Vreg, SPTy));
13157     SDValue Ops1[2] = { Value, Chain };
13158     return DAG.getMergeValues(Ops1, dl);
13159   } else {
13160     SDValue Flag;
13161     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13162
13163     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13164     Flag = Chain.getValue(1);
13165     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13166
13167     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13168
13169     const X86RegisterInfo *RegInfo =
13170       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13171     unsigned SPReg = RegInfo->getStackRegister();
13172     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13173     Chain = SP.getValue(1);
13174
13175     if (Align) {
13176       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13177                        DAG.getConstant(-(uint64_t)Align, VT));
13178       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13179     }
13180
13181     SDValue Ops1[2] = { SP, Chain };
13182     return DAG.getMergeValues(Ops1, dl);
13183   }
13184 }
13185
13186 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13187   MachineFunction &MF = DAG.getMachineFunction();
13188   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13189
13190   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13191   SDLoc DL(Op);
13192
13193   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13194     // vastart just stores the address of the VarArgsFrameIndex slot into the
13195     // memory location argument.
13196     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13197                                    getPointerTy());
13198     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13199                         MachinePointerInfo(SV), false, false, 0);
13200   }
13201
13202   // __va_list_tag:
13203   //   gp_offset         (0 - 6 * 8)
13204   //   fp_offset         (48 - 48 + 8 * 16)
13205   //   overflow_arg_area (point to parameters coming in memory).
13206   //   reg_save_area
13207   SmallVector<SDValue, 8> MemOps;
13208   SDValue FIN = Op.getOperand(1);
13209   // Store gp_offset
13210   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13211                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13212                                                MVT::i32),
13213                                FIN, MachinePointerInfo(SV), false, false, 0);
13214   MemOps.push_back(Store);
13215
13216   // Store fp_offset
13217   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13218                     FIN, DAG.getIntPtrConstant(4));
13219   Store = DAG.getStore(Op.getOperand(0), DL,
13220                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13221                                        MVT::i32),
13222                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13223   MemOps.push_back(Store);
13224
13225   // Store ptr to overflow_arg_area
13226   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13227                     FIN, DAG.getIntPtrConstant(4));
13228   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13229                                     getPointerTy());
13230   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13231                        MachinePointerInfo(SV, 8),
13232                        false, false, 0);
13233   MemOps.push_back(Store);
13234
13235   // Store ptr to reg_save_area.
13236   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13237                     FIN, DAG.getIntPtrConstant(8));
13238   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13239                                     getPointerTy());
13240   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13241                        MachinePointerInfo(SV, 16), false, false, 0);
13242   MemOps.push_back(Store);
13243   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13244 }
13245
13246 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13247   assert(Subtarget->is64Bit() &&
13248          "LowerVAARG only handles 64-bit va_arg!");
13249   assert((Subtarget->isTargetLinux() ||
13250           Subtarget->isTargetDarwin()) &&
13251           "Unhandled target in LowerVAARG");
13252   assert(Op.getNode()->getNumOperands() == 4);
13253   SDValue Chain = Op.getOperand(0);
13254   SDValue SrcPtr = Op.getOperand(1);
13255   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13256   unsigned Align = Op.getConstantOperandVal(3);
13257   SDLoc dl(Op);
13258
13259   EVT ArgVT = Op.getNode()->getValueType(0);
13260   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13261   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13262   uint8_t ArgMode;
13263
13264   // Decide which area this value should be read from.
13265   // TODO: Implement the AMD64 ABI in its entirety. This simple
13266   // selection mechanism works only for the basic types.
13267   if (ArgVT == MVT::f80) {
13268     llvm_unreachable("va_arg for f80 not yet implemented");
13269   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13270     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13271   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13272     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13273   } else {
13274     llvm_unreachable("Unhandled argument type in LowerVAARG");
13275   }
13276
13277   if (ArgMode == 2) {
13278     // Sanity Check: Make sure using fp_offset makes sense.
13279     assert(!DAG.getTarget().Options.UseSoftFloat &&
13280            !(DAG.getMachineFunction()
13281                 .getFunction()->getAttributes()
13282                 .hasAttribute(AttributeSet::FunctionIndex,
13283                               Attribute::NoImplicitFloat)) &&
13284            Subtarget->hasSSE1());
13285   }
13286
13287   // Insert VAARG_64 node into the DAG
13288   // VAARG_64 returns two values: Variable Argument Address, Chain
13289   SmallVector<SDValue, 11> InstOps;
13290   InstOps.push_back(Chain);
13291   InstOps.push_back(SrcPtr);
13292   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13293   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13294   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13295   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13296   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13297                                           VTs, InstOps, MVT::i64,
13298                                           MachinePointerInfo(SV),
13299                                           /*Align=*/0,
13300                                           /*Volatile=*/false,
13301                                           /*ReadMem=*/true,
13302                                           /*WriteMem=*/true);
13303   Chain = VAARG.getValue(1);
13304
13305   // Load the next argument and return it
13306   return DAG.getLoad(ArgVT, dl,
13307                      Chain,
13308                      VAARG,
13309                      MachinePointerInfo(),
13310                      false, false, false, 0);
13311 }
13312
13313 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13314                            SelectionDAG &DAG) {
13315   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13316   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13317   SDValue Chain = Op.getOperand(0);
13318   SDValue DstPtr = Op.getOperand(1);
13319   SDValue SrcPtr = Op.getOperand(2);
13320   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13321   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13322   SDLoc DL(Op);
13323
13324   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13325                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13326                        false,
13327                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13328 }
13329
13330 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13331 // amount is a constant. Takes immediate version of shift as input.
13332 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13333                                           SDValue SrcOp, uint64_t ShiftAmt,
13334                                           SelectionDAG &DAG) {
13335   MVT ElementType = VT.getVectorElementType();
13336
13337   // Fold this packed shift into its first operand if ShiftAmt is 0.
13338   if (ShiftAmt == 0)
13339     return SrcOp;
13340
13341   // Check for ShiftAmt >= element width
13342   if (ShiftAmt >= ElementType.getSizeInBits()) {
13343     if (Opc == X86ISD::VSRAI)
13344       ShiftAmt = ElementType.getSizeInBits() - 1;
13345     else
13346       return DAG.getConstant(0, VT);
13347   }
13348
13349   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13350          && "Unknown target vector shift-by-constant node");
13351
13352   // Fold this packed vector shift into a build vector if SrcOp is a
13353   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13354   if (VT == SrcOp.getSimpleValueType() &&
13355       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13356     SmallVector<SDValue, 8> Elts;
13357     unsigned NumElts = SrcOp->getNumOperands();
13358     ConstantSDNode *ND;
13359
13360     switch(Opc) {
13361     default: llvm_unreachable(nullptr);
13362     case X86ISD::VSHLI:
13363       for (unsigned i=0; i!=NumElts; ++i) {
13364         SDValue CurrentOp = SrcOp->getOperand(i);
13365         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13366           Elts.push_back(CurrentOp);
13367           continue;
13368         }
13369         ND = cast<ConstantSDNode>(CurrentOp);
13370         const APInt &C = ND->getAPIntValue();
13371         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13372       }
13373       break;
13374     case X86ISD::VSRLI:
13375       for (unsigned i=0; i!=NumElts; ++i) {
13376         SDValue CurrentOp = SrcOp->getOperand(i);
13377         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13378           Elts.push_back(CurrentOp);
13379           continue;
13380         }
13381         ND = cast<ConstantSDNode>(CurrentOp);
13382         const APInt &C = ND->getAPIntValue();
13383         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13384       }
13385       break;
13386     case X86ISD::VSRAI:
13387       for (unsigned i=0; i!=NumElts; ++i) {
13388         SDValue CurrentOp = SrcOp->getOperand(i);
13389         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13390           Elts.push_back(CurrentOp);
13391           continue;
13392         }
13393         ND = cast<ConstantSDNode>(CurrentOp);
13394         const APInt &C = ND->getAPIntValue();
13395         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13396       }
13397       break;
13398     }
13399
13400     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13401   }
13402
13403   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13404 }
13405
13406 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13407 // may or may not be a constant. Takes immediate version of shift as input.
13408 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13409                                    SDValue SrcOp, SDValue ShAmt,
13410                                    SelectionDAG &DAG) {
13411   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13412
13413   // Catch shift-by-constant.
13414   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13415     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13416                                       CShAmt->getZExtValue(), DAG);
13417
13418   // Change opcode to non-immediate version
13419   switch (Opc) {
13420     default: llvm_unreachable("Unknown target vector shift node");
13421     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13422     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13423     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13424   }
13425
13426   // Need to build a vector containing shift amount
13427   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13428   SDValue ShOps[4];
13429   ShOps[0] = ShAmt;
13430   ShOps[1] = DAG.getConstant(0, MVT::i32);
13431   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13432   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13433
13434   // The return type has to be a 128-bit type with the same element
13435   // type as the input type.
13436   MVT EltVT = VT.getVectorElementType();
13437   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13438
13439   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13440   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13441 }
13442
13443 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13444   SDLoc dl(Op);
13445   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13446   switch (IntNo) {
13447   default: return SDValue();    // Don't custom lower most intrinsics.
13448   // Comparison intrinsics.
13449   case Intrinsic::x86_sse_comieq_ss:
13450   case Intrinsic::x86_sse_comilt_ss:
13451   case Intrinsic::x86_sse_comile_ss:
13452   case Intrinsic::x86_sse_comigt_ss:
13453   case Intrinsic::x86_sse_comige_ss:
13454   case Intrinsic::x86_sse_comineq_ss:
13455   case Intrinsic::x86_sse_ucomieq_ss:
13456   case Intrinsic::x86_sse_ucomilt_ss:
13457   case Intrinsic::x86_sse_ucomile_ss:
13458   case Intrinsic::x86_sse_ucomigt_ss:
13459   case Intrinsic::x86_sse_ucomige_ss:
13460   case Intrinsic::x86_sse_ucomineq_ss:
13461   case Intrinsic::x86_sse2_comieq_sd:
13462   case Intrinsic::x86_sse2_comilt_sd:
13463   case Intrinsic::x86_sse2_comile_sd:
13464   case Intrinsic::x86_sse2_comigt_sd:
13465   case Intrinsic::x86_sse2_comige_sd:
13466   case Intrinsic::x86_sse2_comineq_sd:
13467   case Intrinsic::x86_sse2_ucomieq_sd:
13468   case Intrinsic::x86_sse2_ucomilt_sd:
13469   case Intrinsic::x86_sse2_ucomile_sd:
13470   case Intrinsic::x86_sse2_ucomigt_sd:
13471   case Intrinsic::x86_sse2_ucomige_sd:
13472   case Intrinsic::x86_sse2_ucomineq_sd: {
13473     unsigned Opc;
13474     ISD::CondCode CC;
13475     switch (IntNo) {
13476     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13477     case Intrinsic::x86_sse_comieq_ss:
13478     case Intrinsic::x86_sse2_comieq_sd:
13479       Opc = X86ISD::COMI;
13480       CC = ISD::SETEQ;
13481       break;
13482     case Intrinsic::x86_sse_comilt_ss:
13483     case Intrinsic::x86_sse2_comilt_sd:
13484       Opc = X86ISD::COMI;
13485       CC = ISD::SETLT;
13486       break;
13487     case Intrinsic::x86_sse_comile_ss:
13488     case Intrinsic::x86_sse2_comile_sd:
13489       Opc = X86ISD::COMI;
13490       CC = ISD::SETLE;
13491       break;
13492     case Intrinsic::x86_sse_comigt_ss:
13493     case Intrinsic::x86_sse2_comigt_sd:
13494       Opc = X86ISD::COMI;
13495       CC = ISD::SETGT;
13496       break;
13497     case Intrinsic::x86_sse_comige_ss:
13498     case Intrinsic::x86_sse2_comige_sd:
13499       Opc = X86ISD::COMI;
13500       CC = ISD::SETGE;
13501       break;
13502     case Intrinsic::x86_sse_comineq_ss:
13503     case Intrinsic::x86_sse2_comineq_sd:
13504       Opc = X86ISD::COMI;
13505       CC = ISD::SETNE;
13506       break;
13507     case Intrinsic::x86_sse_ucomieq_ss:
13508     case Intrinsic::x86_sse2_ucomieq_sd:
13509       Opc = X86ISD::UCOMI;
13510       CC = ISD::SETEQ;
13511       break;
13512     case Intrinsic::x86_sse_ucomilt_ss:
13513     case Intrinsic::x86_sse2_ucomilt_sd:
13514       Opc = X86ISD::UCOMI;
13515       CC = ISD::SETLT;
13516       break;
13517     case Intrinsic::x86_sse_ucomile_ss:
13518     case Intrinsic::x86_sse2_ucomile_sd:
13519       Opc = X86ISD::UCOMI;
13520       CC = ISD::SETLE;
13521       break;
13522     case Intrinsic::x86_sse_ucomigt_ss:
13523     case Intrinsic::x86_sse2_ucomigt_sd:
13524       Opc = X86ISD::UCOMI;
13525       CC = ISD::SETGT;
13526       break;
13527     case Intrinsic::x86_sse_ucomige_ss:
13528     case Intrinsic::x86_sse2_ucomige_sd:
13529       Opc = X86ISD::UCOMI;
13530       CC = ISD::SETGE;
13531       break;
13532     case Intrinsic::x86_sse_ucomineq_ss:
13533     case Intrinsic::x86_sse2_ucomineq_sd:
13534       Opc = X86ISD::UCOMI;
13535       CC = ISD::SETNE;
13536       break;
13537     }
13538
13539     SDValue LHS = Op.getOperand(1);
13540     SDValue RHS = Op.getOperand(2);
13541     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13542     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13543     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13544     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13545                                 DAG.getConstant(X86CC, MVT::i8), Cond);
13546     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13547   }
13548
13549   // Arithmetic intrinsics.
13550   case Intrinsic::x86_sse2_pmulu_dq:
13551   case Intrinsic::x86_avx2_pmulu_dq:
13552     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13553                        Op.getOperand(1), Op.getOperand(2));
13554
13555   case Intrinsic::x86_sse41_pmuldq:
13556   case Intrinsic::x86_avx2_pmul_dq:
13557     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13558                        Op.getOperand(1), Op.getOperand(2));
13559
13560   case Intrinsic::x86_sse2_pmulhu_w:
13561   case Intrinsic::x86_avx2_pmulhu_w:
13562     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13563                        Op.getOperand(1), Op.getOperand(2));
13564
13565   case Intrinsic::x86_sse2_pmulh_w:
13566   case Intrinsic::x86_avx2_pmulh_w:
13567     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13568                        Op.getOperand(1), Op.getOperand(2));
13569
13570   // SSE2/AVX2 sub with unsigned saturation intrinsics
13571   case Intrinsic::x86_sse2_psubus_b:
13572   case Intrinsic::x86_sse2_psubus_w:
13573   case Intrinsic::x86_avx2_psubus_b:
13574   case Intrinsic::x86_avx2_psubus_w:
13575     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13576                        Op.getOperand(1), Op.getOperand(2));
13577
13578   // SSE3/AVX horizontal add/sub intrinsics
13579   case Intrinsic::x86_sse3_hadd_ps:
13580   case Intrinsic::x86_sse3_hadd_pd:
13581   case Intrinsic::x86_avx_hadd_ps_256:
13582   case Intrinsic::x86_avx_hadd_pd_256:
13583   case Intrinsic::x86_sse3_hsub_ps:
13584   case Intrinsic::x86_sse3_hsub_pd:
13585   case Intrinsic::x86_avx_hsub_ps_256:
13586   case Intrinsic::x86_avx_hsub_pd_256:
13587   case Intrinsic::x86_ssse3_phadd_w_128:
13588   case Intrinsic::x86_ssse3_phadd_d_128:
13589   case Intrinsic::x86_avx2_phadd_w:
13590   case Intrinsic::x86_avx2_phadd_d:
13591   case Intrinsic::x86_ssse3_phsub_w_128:
13592   case Intrinsic::x86_ssse3_phsub_d_128:
13593   case Intrinsic::x86_avx2_phsub_w:
13594   case Intrinsic::x86_avx2_phsub_d: {
13595     unsigned Opcode;
13596     switch (IntNo) {
13597     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13598     case Intrinsic::x86_sse3_hadd_ps:
13599     case Intrinsic::x86_sse3_hadd_pd:
13600     case Intrinsic::x86_avx_hadd_ps_256:
13601     case Intrinsic::x86_avx_hadd_pd_256:
13602       Opcode = X86ISD::FHADD;
13603       break;
13604     case Intrinsic::x86_sse3_hsub_ps:
13605     case Intrinsic::x86_sse3_hsub_pd:
13606     case Intrinsic::x86_avx_hsub_ps_256:
13607     case Intrinsic::x86_avx_hsub_pd_256:
13608       Opcode = X86ISD::FHSUB;
13609       break;
13610     case Intrinsic::x86_ssse3_phadd_w_128:
13611     case Intrinsic::x86_ssse3_phadd_d_128:
13612     case Intrinsic::x86_avx2_phadd_w:
13613     case Intrinsic::x86_avx2_phadd_d:
13614       Opcode = X86ISD::HADD;
13615       break;
13616     case Intrinsic::x86_ssse3_phsub_w_128:
13617     case Intrinsic::x86_ssse3_phsub_d_128:
13618     case Intrinsic::x86_avx2_phsub_w:
13619     case Intrinsic::x86_avx2_phsub_d:
13620       Opcode = X86ISD::HSUB;
13621       break;
13622     }
13623     return DAG.getNode(Opcode, dl, Op.getValueType(),
13624                        Op.getOperand(1), Op.getOperand(2));
13625   }
13626
13627   // SSE2/SSE41/AVX2 integer max/min intrinsics.
13628   case Intrinsic::x86_sse2_pmaxu_b:
13629   case Intrinsic::x86_sse41_pmaxuw:
13630   case Intrinsic::x86_sse41_pmaxud:
13631   case Intrinsic::x86_avx2_pmaxu_b:
13632   case Intrinsic::x86_avx2_pmaxu_w:
13633   case Intrinsic::x86_avx2_pmaxu_d:
13634   case Intrinsic::x86_sse2_pminu_b:
13635   case Intrinsic::x86_sse41_pminuw:
13636   case Intrinsic::x86_sse41_pminud:
13637   case Intrinsic::x86_avx2_pminu_b:
13638   case Intrinsic::x86_avx2_pminu_w:
13639   case Intrinsic::x86_avx2_pminu_d:
13640   case Intrinsic::x86_sse41_pmaxsb:
13641   case Intrinsic::x86_sse2_pmaxs_w:
13642   case Intrinsic::x86_sse41_pmaxsd:
13643   case Intrinsic::x86_avx2_pmaxs_b:
13644   case Intrinsic::x86_avx2_pmaxs_w:
13645   case Intrinsic::x86_avx2_pmaxs_d:
13646   case Intrinsic::x86_sse41_pminsb:
13647   case Intrinsic::x86_sse2_pmins_w:
13648   case Intrinsic::x86_sse41_pminsd:
13649   case Intrinsic::x86_avx2_pmins_b:
13650   case Intrinsic::x86_avx2_pmins_w:
13651   case Intrinsic::x86_avx2_pmins_d: {
13652     unsigned Opcode;
13653     switch (IntNo) {
13654     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13655     case Intrinsic::x86_sse2_pmaxu_b:
13656     case Intrinsic::x86_sse41_pmaxuw:
13657     case Intrinsic::x86_sse41_pmaxud:
13658     case Intrinsic::x86_avx2_pmaxu_b:
13659     case Intrinsic::x86_avx2_pmaxu_w:
13660     case Intrinsic::x86_avx2_pmaxu_d:
13661       Opcode = X86ISD::UMAX;
13662       break;
13663     case Intrinsic::x86_sse2_pminu_b:
13664     case Intrinsic::x86_sse41_pminuw:
13665     case Intrinsic::x86_sse41_pminud:
13666     case Intrinsic::x86_avx2_pminu_b:
13667     case Intrinsic::x86_avx2_pminu_w:
13668     case Intrinsic::x86_avx2_pminu_d:
13669       Opcode = X86ISD::UMIN;
13670       break;
13671     case Intrinsic::x86_sse41_pmaxsb:
13672     case Intrinsic::x86_sse2_pmaxs_w:
13673     case Intrinsic::x86_sse41_pmaxsd:
13674     case Intrinsic::x86_avx2_pmaxs_b:
13675     case Intrinsic::x86_avx2_pmaxs_w:
13676     case Intrinsic::x86_avx2_pmaxs_d:
13677       Opcode = X86ISD::SMAX;
13678       break;
13679     case Intrinsic::x86_sse41_pminsb:
13680     case Intrinsic::x86_sse2_pmins_w:
13681     case Intrinsic::x86_sse41_pminsd:
13682     case Intrinsic::x86_avx2_pmins_b:
13683     case Intrinsic::x86_avx2_pmins_w:
13684     case Intrinsic::x86_avx2_pmins_d:
13685       Opcode = X86ISD::SMIN;
13686       break;
13687     }
13688     return DAG.getNode(Opcode, dl, Op.getValueType(),
13689                        Op.getOperand(1), Op.getOperand(2));
13690   }
13691
13692   // SSE/SSE2/AVX floating point max/min intrinsics.
13693   case Intrinsic::x86_sse_max_ps:
13694   case Intrinsic::x86_sse2_max_pd:
13695   case Intrinsic::x86_avx_max_ps_256:
13696   case Intrinsic::x86_avx_max_pd_256:
13697   case Intrinsic::x86_sse_min_ps:
13698   case Intrinsic::x86_sse2_min_pd:
13699   case Intrinsic::x86_avx_min_ps_256:
13700   case Intrinsic::x86_avx_min_pd_256: {
13701     unsigned Opcode;
13702     switch (IntNo) {
13703     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13704     case Intrinsic::x86_sse_max_ps:
13705     case Intrinsic::x86_sse2_max_pd:
13706     case Intrinsic::x86_avx_max_ps_256:
13707     case Intrinsic::x86_avx_max_pd_256:
13708       Opcode = X86ISD::FMAX;
13709       break;
13710     case Intrinsic::x86_sse_min_ps:
13711     case Intrinsic::x86_sse2_min_pd:
13712     case Intrinsic::x86_avx_min_ps_256:
13713     case Intrinsic::x86_avx_min_pd_256:
13714       Opcode = X86ISD::FMIN;
13715       break;
13716     }
13717     return DAG.getNode(Opcode, dl, Op.getValueType(),
13718                        Op.getOperand(1), Op.getOperand(2));
13719   }
13720
13721   // AVX2 variable shift intrinsics
13722   case Intrinsic::x86_avx2_psllv_d:
13723   case Intrinsic::x86_avx2_psllv_q:
13724   case Intrinsic::x86_avx2_psllv_d_256:
13725   case Intrinsic::x86_avx2_psllv_q_256:
13726   case Intrinsic::x86_avx2_psrlv_d:
13727   case Intrinsic::x86_avx2_psrlv_q:
13728   case Intrinsic::x86_avx2_psrlv_d_256:
13729   case Intrinsic::x86_avx2_psrlv_q_256:
13730   case Intrinsic::x86_avx2_psrav_d:
13731   case Intrinsic::x86_avx2_psrav_d_256: {
13732     unsigned Opcode;
13733     switch (IntNo) {
13734     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13735     case Intrinsic::x86_avx2_psllv_d:
13736     case Intrinsic::x86_avx2_psllv_q:
13737     case Intrinsic::x86_avx2_psllv_d_256:
13738     case Intrinsic::x86_avx2_psllv_q_256:
13739       Opcode = ISD::SHL;
13740       break;
13741     case Intrinsic::x86_avx2_psrlv_d:
13742     case Intrinsic::x86_avx2_psrlv_q:
13743     case Intrinsic::x86_avx2_psrlv_d_256:
13744     case Intrinsic::x86_avx2_psrlv_q_256:
13745       Opcode = ISD::SRL;
13746       break;
13747     case Intrinsic::x86_avx2_psrav_d:
13748     case Intrinsic::x86_avx2_psrav_d_256:
13749       Opcode = ISD::SRA;
13750       break;
13751     }
13752     return DAG.getNode(Opcode, dl, Op.getValueType(),
13753                        Op.getOperand(1), Op.getOperand(2));
13754   }
13755
13756   case Intrinsic::x86_sse2_packssdw_128:
13757   case Intrinsic::x86_sse2_packsswb_128:
13758   case Intrinsic::x86_avx2_packssdw:
13759   case Intrinsic::x86_avx2_packsswb:
13760     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13761                        Op.getOperand(1), Op.getOperand(2));
13762
13763   case Intrinsic::x86_sse2_packuswb_128:
13764   case Intrinsic::x86_sse41_packusdw:
13765   case Intrinsic::x86_avx2_packuswb:
13766   case Intrinsic::x86_avx2_packusdw:
13767     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13768                        Op.getOperand(1), Op.getOperand(2));
13769
13770   case Intrinsic::x86_ssse3_pshuf_b_128:
13771   case Intrinsic::x86_avx2_pshuf_b:
13772     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13773                        Op.getOperand(1), Op.getOperand(2));
13774
13775   case Intrinsic::x86_sse2_pshuf_d:
13776     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13777                        Op.getOperand(1), Op.getOperand(2));
13778
13779   case Intrinsic::x86_sse2_pshufl_w:
13780     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13781                        Op.getOperand(1), Op.getOperand(2));
13782
13783   case Intrinsic::x86_sse2_pshufh_w:
13784     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13785                        Op.getOperand(1), Op.getOperand(2));
13786
13787   case Intrinsic::x86_ssse3_psign_b_128:
13788   case Intrinsic::x86_ssse3_psign_w_128:
13789   case Intrinsic::x86_ssse3_psign_d_128:
13790   case Intrinsic::x86_avx2_psign_b:
13791   case Intrinsic::x86_avx2_psign_w:
13792   case Intrinsic::x86_avx2_psign_d:
13793     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13794                        Op.getOperand(1), Op.getOperand(2));
13795
13796   case Intrinsic::x86_sse41_insertps:
13797     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13798                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13799
13800   case Intrinsic::x86_avx_vperm2f128_ps_256:
13801   case Intrinsic::x86_avx_vperm2f128_pd_256:
13802   case Intrinsic::x86_avx_vperm2f128_si_256:
13803   case Intrinsic::x86_avx2_vperm2i128:
13804     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13805                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13806
13807   case Intrinsic::x86_avx2_permd:
13808   case Intrinsic::x86_avx2_permps:
13809     // Operands intentionally swapped. Mask is last operand to intrinsic,
13810     // but second operand for node/instruction.
13811     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13812                        Op.getOperand(2), Op.getOperand(1));
13813
13814   case Intrinsic::x86_sse_sqrt_ps:
13815   case Intrinsic::x86_sse2_sqrt_pd:
13816   case Intrinsic::x86_avx_sqrt_ps_256:
13817   case Intrinsic::x86_avx_sqrt_pd_256:
13818     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13819
13820   // ptest and testp intrinsics. The intrinsic these come from are designed to
13821   // return an integer value, not just an instruction so lower it to the ptest
13822   // or testp pattern and a setcc for the result.
13823   case Intrinsic::x86_sse41_ptestz:
13824   case Intrinsic::x86_sse41_ptestc:
13825   case Intrinsic::x86_sse41_ptestnzc:
13826   case Intrinsic::x86_avx_ptestz_256:
13827   case Intrinsic::x86_avx_ptestc_256:
13828   case Intrinsic::x86_avx_ptestnzc_256:
13829   case Intrinsic::x86_avx_vtestz_ps:
13830   case Intrinsic::x86_avx_vtestc_ps:
13831   case Intrinsic::x86_avx_vtestnzc_ps:
13832   case Intrinsic::x86_avx_vtestz_pd:
13833   case Intrinsic::x86_avx_vtestc_pd:
13834   case Intrinsic::x86_avx_vtestnzc_pd:
13835   case Intrinsic::x86_avx_vtestz_ps_256:
13836   case Intrinsic::x86_avx_vtestc_ps_256:
13837   case Intrinsic::x86_avx_vtestnzc_ps_256:
13838   case Intrinsic::x86_avx_vtestz_pd_256:
13839   case Intrinsic::x86_avx_vtestc_pd_256:
13840   case Intrinsic::x86_avx_vtestnzc_pd_256: {
13841     bool IsTestPacked = false;
13842     unsigned X86CC;
13843     switch (IntNo) {
13844     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13845     case Intrinsic::x86_avx_vtestz_ps:
13846     case Intrinsic::x86_avx_vtestz_pd:
13847     case Intrinsic::x86_avx_vtestz_ps_256:
13848     case Intrinsic::x86_avx_vtestz_pd_256:
13849       IsTestPacked = true; // Fallthrough
13850     case Intrinsic::x86_sse41_ptestz:
13851     case Intrinsic::x86_avx_ptestz_256:
13852       // ZF = 1
13853       X86CC = X86::COND_E;
13854       break;
13855     case Intrinsic::x86_avx_vtestc_ps:
13856     case Intrinsic::x86_avx_vtestc_pd:
13857     case Intrinsic::x86_avx_vtestc_ps_256:
13858     case Intrinsic::x86_avx_vtestc_pd_256:
13859       IsTestPacked = true; // Fallthrough
13860     case Intrinsic::x86_sse41_ptestc:
13861     case Intrinsic::x86_avx_ptestc_256:
13862       // CF = 1
13863       X86CC = X86::COND_B;
13864       break;
13865     case Intrinsic::x86_avx_vtestnzc_ps:
13866     case Intrinsic::x86_avx_vtestnzc_pd:
13867     case Intrinsic::x86_avx_vtestnzc_ps_256:
13868     case Intrinsic::x86_avx_vtestnzc_pd_256:
13869       IsTestPacked = true; // Fallthrough
13870     case Intrinsic::x86_sse41_ptestnzc:
13871     case Intrinsic::x86_avx_ptestnzc_256:
13872       // ZF and CF = 0
13873       X86CC = X86::COND_A;
13874       break;
13875     }
13876
13877     SDValue LHS = Op.getOperand(1);
13878     SDValue RHS = Op.getOperand(2);
13879     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13880     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13881     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13882     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13883     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13884   }
13885   case Intrinsic::x86_avx512_kortestz_w:
13886   case Intrinsic::x86_avx512_kortestc_w: {
13887     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13888     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13889     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13890     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13891     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13892     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13893     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13894   }
13895
13896   // SSE/AVX shift intrinsics
13897   case Intrinsic::x86_sse2_psll_w:
13898   case Intrinsic::x86_sse2_psll_d:
13899   case Intrinsic::x86_sse2_psll_q:
13900   case Intrinsic::x86_avx2_psll_w:
13901   case Intrinsic::x86_avx2_psll_d:
13902   case Intrinsic::x86_avx2_psll_q:
13903   case Intrinsic::x86_sse2_psrl_w:
13904   case Intrinsic::x86_sse2_psrl_d:
13905   case Intrinsic::x86_sse2_psrl_q:
13906   case Intrinsic::x86_avx2_psrl_w:
13907   case Intrinsic::x86_avx2_psrl_d:
13908   case Intrinsic::x86_avx2_psrl_q:
13909   case Intrinsic::x86_sse2_psra_w:
13910   case Intrinsic::x86_sse2_psra_d:
13911   case Intrinsic::x86_avx2_psra_w:
13912   case Intrinsic::x86_avx2_psra_d: {
13913     unsigned Opcode;
13914     switch (IntNo) {
13915     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13916     case Intrinsic::x86_sse2_psll_w:
13917     case Intrinsic::x86_sse2_psll_d:
13918     case Intrinsic::x86_sse2_psll_q:
13919     case Intrinsic::x86_avx2_psll_w:
13920     case Intrinsic::x86_avx2_psll_d:
13921     case Intrinsic::x86_avx2_psll_q:
13922       Opcode = X86ISD::VSHL;
13923       break;
13924     case Intrinsic::x86_sse2_psrl_w:
13925     case Intrinsic::x86_sse2_psrl_d:
13926     case Intrinsic::x86_sse2_psrl_q:
13927     case Intrinsic::x86_avx2_psrl_w:
13928     case Intrinsic::x86_avx2_psrl_d:
13929     case Intrinsic::x86_avx2_psrl_q:
13930       Opcode = X86ISD::VSRL;
13931       break;
13932     case Intrinsic::x86_sse2_psra_w:
13933     case Intrinsic::x86_sse2_psra_d:
13934     case Intrinsic::x86_avx2_psra_w:
13935     case Intrinsic::x86_avx2_psra_d:
13936       Opcode = X86ISD::VSRA;
13937       break;
13938     }
13939     return DAG.getNode(Opcode, dl, Op.getValueType(),
13940                        Op.getOperand(1), Op.getOperand(2));
13941   }
13942
13943   // SSE/AVX immediate shift intrinsics
13944   case Intrinsic::x86_sse2_pslli_w:
13945   case Intrinsic::x86_sse2_pslli_d:
13946   case Intrinsic::x86_sse2_pslli_q:
13947   case Intrinsic::x86_avx2_pslli_w:
13948   case Intrinsic::x86_avx2_pslli_d:
13949   case Intrinsic::x86_avx2_pslli_q:
13950   case Intrinsic::x86_sse2_psrli_w:
13951   case Intrinsic::x86_sse2_psrli_d:
13952   case Intrinsic::x86_sse2_psrli_q:
13953   case Intrinsic::x86_avx2_psrli_w:
13954   case Intrinsic::x86_avx2_psrli_d:
13955   case Intrinsic::x86_avx2_psrli_q:
13956   case Intrinsic::x86_sse2_psrai_w:
13957   case Intrinsic::x86_sse2_psrai_d:
13958   case Intrinsic::x86_avx2_psrai_w:
13959   case Intrinsic::x86_avx2_psrai_d: {
13960     unsigned Opcode;
13961     switch (IntNo) {
13962     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13963     case Intrinsic::x86_sse2_pslli_w:
13964     case Intrinsic::x86_sse2_pslli_d:
13965     case Intrinsic::x86_sse2_pslli_q:
13966     case Intrinsic::x86_avx2_pslli_w:
13967     case Intrinsic::x86_avx2_pslli_d:
13968     case Intrinsic::x86_avx2_pslli_q:
13969       Opcode = X86ISD::VSHLI;
13970       break;
13971     case Intrinsic::x86_sse2_psrli_w:
13972     case Intrinsic::x86_sse2_psrli_d:
13973     case Intrinsic::x86_sse2_psrli_q:
13974     case Intrinsic::x86_avx2_psrli_w:
13975     case Intrinsic::x86_avx2_psrli_d:
13976     case Intrinsic::x86_avx2_psrli_q:
13977       Opcode = X86ISD::VSRLI;
13978       break;
13979     case Intrinsic::x86_sse2_psrai_w:
13980     case Intrinsic::x86_sse2_psrai_d:
13981     case Intrinsic::x86_avx2_psrai_w:
13982     case Intrinsic::x86_avx2_psrai_d:
13983       Opcode = X86ISD::VSRAI;
13984       break;
13985     }
13986     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
13987                                Op.getOperand(1), Op.getOperand(2), DAG);
13988   }
13989
13990   case Intrinsic::x86_sse42_pcmpistria128:
13991   case Intrinsic::x86_sse42_pcmpestria128:
13992   case Intrinsic::x86_sse42_pcmpistric128:
13993   case Intrinsic::x86_sse42_pcmpestric128:
13994   case Intrinsic::x86_sse42_pcmpistrio128:
13995   case Intrinsic::x86_sse42_pcmpestrio128:
13996   case Intrinsic::x86_sse42_pcmpistris128:
13997   case Intrinsic::x86_sse42_pcmpestris128:
13998   case Intrinsic::x86_sse42_pcmpistriz128:
13999   case Intrinsic::x86_sse42_pcmpestriz128: {
14000     unsigned Opcode;
14001     unsigned X86CC;
14002     switch (IntNo) {
14003     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14004     case Intrinsic::x86_sse42_pcmpistria128:
14005       Opcode = X86ISD::PCMPISTRI;
14006       X86CC = X86::COND_A;
14007       break;
14008     case Intrinsic::x86_sse42_pcmpestria128:
14009       Opcode = X86ISD::PCMPESTRI;
14010       X86CC = X86::COND_A;
14011       break;
14012     case Intrinsic::x86_sse42_pcmpistric128:
14013       Opcode = X86ISD::PCMPISTRI;
14014       X86CC = X86::COND_B;
14015       break;
14016     case Intrinsic::x86_sse42_pcmpestric128:
14017       Opcode = X86ISD::PCMPESTRI;
14018       X86CC = X86::COND_B;
14019       break;
14020     case Intrinsic::x86_sse42_pcmpistrio128:
14021       Opcode = X86ISD::PCMPISTRI;
14022       X86CC = X86::COND_O;
14023       break;
14024     case Intrinsic::x86_sse42_pcmpestrio128:
14025       Opcode = X86ISD::PCMPESTRI;
14026       X86CC = X86::COND_O;
14027       break;
14028     case Intrinsic::x86_sse42_pcmpistris128:
14029       Opcode = X86ISD::PCMPISTRI;
14030       X86CC = X86::COND_S;
14031       break;
14032     case Intrinsic::x86_sse42_pcmpestris128:
14033       Opcode = X86ISD::PCMPESTRI;
14034       X86CC = X86::COND_S;
14035       break;
14036     case Intrinsic::x86_sse42_pcmpistriz128:
14037       Opcode = X86ISD::PCMPISTRI;
14038       X86CC = X86::COND_E;
14039       break;
14040     case Intrinsic::x86_sse42_pcmpestriz128:
14041       Opcode = X86ISD::PCMPESTRI;
14042       X86CC = X86::COND_E;
14043       break;
14044     }
14045     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14046     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14047     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14048     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14049                                 DAG.getConstant(X86CC, MVT::i8),
14050                                 SDValue(PCMP.getNode(), 1));
14051     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14052   }
14053
14054   case Intrinsic::x86_sse42_pcmpistri128:
14055   case Intrinsic::x86_sse42_pcmpestri128: {
14056     unsigned Opcode;
14057     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14058       Opcode = X86ISD::PCMPISTRI;
14059     else
14060       Opcode = X86ISD::PCMPESTRI;
14061
14062     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14063     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14064     return DAG.getNode(Opcode, dl, VTs, NewOps);
14065   }
14066   case Intrinsic::x86_fma_vfmadd_ps:
14067   case Intrinsic::x86_fma_vfmadd_pd:
14068   case Intrinsic::x86_fma_vfmsub_ps:
14069   case Intrinsic::x86_fma_vfmsub_pd:
14070   case Intrinsic::x86_fma_vfnmadd_ps:
14071   case Intrinsic::x86_fma_vfnmadd_pd:
14072   case Intrinsic::x86_fma_vfnmsub_ps:
14073   case Intrinsic::x86_fma_vfnmsub_pd:
14074   case Intrinsic::x86_fma_vfmaddsub_ps:
14075   case Intrinsic::x86_fma_vfmaddsub_pd:
14076   case Intrinsic::x86_fma_vfmsubadd_ps:
14077   case Intrinsic::x86_fma_vfmsubadd_pd:
14078   case Intrinsic::x86_fma_vfmadd_ps_256:
14079   case Intrinsic::x86_fma_vfmadd_pd_256:
14080   case Intrinsic::x86_fma_vfmsub_ps_256:
14081   case Intrinsic::x86_fma_vfmsub_pd_256:
14082   case Intrinsic::x86_fma_vfnmadd_ps_256:
14083   case Intrinsic::x86_fma_vfnmadd_pd_256:
14084   case Intrinsic::x86_fma_vfnmsub_ps_256:
14085   case Intrinsic::x86_fma_vfnmsub_pd_256:
14086   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14087   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14088   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14089   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14090   case Intrinsic::x86_fma_vfmadd_ps_512:
14091   case Intrinsic::x86_fma_vfmadd_pd_512:
14092   case Intrinsic::x86_fma_vfmsub_ps_512:
14093   case Intrinsic::x86_fma_vfmsub_pd_512:
14094   case Intrinsic::x86_fma_vfnmadd_ps_512:
14095   case Intrinsic::x86_fma_vfnmadd_pd_512:
14096   case Intrinsic::x86_fma_vfnmsub_ps_512:
14097   case Intrinsic::x86_fma_vfnmsub_pd_512:
14098   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14099   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14100   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14101   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14102     unsigned Opc;
14103     switch (IntNo) {
14104     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14105     case Intrinsic::x86_fma_vfmadd_ps:
14106     case Intrinsic::x86_fma_vfmadd_pd:
14107     case Intrinsic::x86_fma_vfmadd_ps_256:
14108     case Intrinsic::x86_fma_vfmadd_pd_256:
14109     case Intrinsic::x86_fma_vfmadd_ps_512:
14110     case Intrinsic::x86_fma_vfmadd_pd_512:
14111       Opc = X86ISD::FMADD;
14112       break;
14113     case Intrinsic::x86_fma_vfmsub_ps:
14114     case Intrinsic::x86_fma_vfmsub_pd:
14115     case Intrinsic::x86_fma_vfmsub_ps_256:
14116     case Intrinsic::x86_fma_vfmsub_pd_256:
14117     case Intrinsic::x86_fma_vfmsub_ps_512:
14118     case Intrinsic::x86_fma_vfmsub_pd_512:
14119       Opc = X86ISD::FMSUB;
14120       break;
14121     case Intrinsic::x86_fma_vfnmadd_ps:
14122     case Intrinsic::x86_fma_vfnmadd_pd:
14123     case Intrinsic::x86_fma_vfnmadd_ps_256:
14124     case Intrinsic::x86_fma_vfnmadd_pd_256:
14125     case Intrinsic::x86_fma_vfnmadd_ps_512:
14126     case Intrinsic::x86_fma_vfnmadd_pd_512:
14127       Opc = X86ISD::FNMADD;
14128       break;
14129     case Intrinsic::x86_fma_vfnmsub_ps:
14130     case Intrinsic::x86_fma_vfnmsub_pd:
14131     case Intrinsic::x86_fma_vfnmsub_ps_256:
14132     case Intrinsic::x86_fma_vfnmsub_pd_256:
14133     case Intrinsic::x86_fma_vfnmsub_ps_512:
14134     case Intrinsic::x86_fma_vfnmsub_pd_512:
14135       Opc = X86ISD::FNMSUB;
14136       break;
14137     case Intrinsic::x86_fma_vfmaddsub_ps:
14138     case Intrinsic::x86_fma_vfmaddsub_pd:
14139     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14140     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14141     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14142     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14143       Opc = X86ISD::FMADDSUB;
14144       break;
14145     case Intrinsic::x86_fma_vfmsubadd_ps:
14146     case Intrinsic::x86_fma_vfmsubadd_pd:
14147     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14148     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14149     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14150     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14151       Opc = X86ISD::FMSUBADD;
14152       break;
14153     }
14154
14155     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14156                        Op.getOperand(2), Op.getOperand(3));
14157   }
14158   }
14159 }
14160
14161 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14162                               SDValue Src, SDValue Mask, SDValue Base,
14163                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14164                               const X86Subtarget * Subtarget) {
14165   SDLoc dl(Op);
14166   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14167   assert(C && "Invalid scale type");
14168   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14169   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14170                              Index.getSimpleValueType().getVectorNumElements());
14171   SDValue MaskInReg;
14172   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14173   if (MaskC)
14174     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14175   else
14176     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14177   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14178   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14179   SDValue Segment = DAG.getRegister(0, MVT::i32);
14180   if (Src.getOpcode() == ISD::UNDEF)
14181     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14182   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14183   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14184   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14185   return DAG.getMergeValues(RetOps, dl);
14186 }
14187
14188 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14189                                SDValue Src, SDValue Mask, SDValue Base,
14190                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14191   SDLoc dl(Op);
14192   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14193   assert(C && "Invalid scale type");
14194   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14195   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14196   SDValue Segment = DAG.getRegister(0, MVT::i32);
14197   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14198                              Index.getSimpleValueType().getVectorNumElements());
14199   SDValue MaskInReg;
14200   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14201   if (MaskC)
14202     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14203   else
14204     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14205   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14206   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14207   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14208   return SDValue(Res, 1);
14209 }
14210
14211 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14212                                SDValue Mask, SDValue Base, SDValue Index,
14213                                SDValue ScaleOp, SDValue Chain) {
14214   SDLoc dl(Op);
14215   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14216   assert(C && "Invalid scale type");
14217   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14218   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14219   SDValue Segment = DAG.getRegister(0, MVT::i32);
14220   EVT MaskVT =
14221     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14222   SDValue MaskInReg;
14223   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14224   if (MaskC)
14225     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14226   else
14227     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14228   //SDVTList VTs = DAG.getVTList(MVT::Other);
14229   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14230   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14231   return SDValue(Res, 0);
14232 }
14233
14234 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14235 // read performance monitor counters (x86_rdpmc).
14236 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14237                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14238                               SmallVectorImpl<SDValue> &Results) {
14239   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14240   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14241   SDValue LO, HI;
14242
14243   // The ECX register is used to select the index of the performance counter
14244   // to read.
14245   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14246                                    N->getOperand(2));
14247   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14248
14249   // Reads the content of a 64-bit performance counter and returns it in the
14250   // registers EDX:EAX.
14251   if (Subtarget->is64Bit()) {
14252     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14253     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14254                             LO.getValue(2));
14255   } else {
14256     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14257     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14258                             LO.getValue(2));
14259   }
14260   Chain = HI.getValue(1);
14261
14262   if (Subtarget->is64Bit()) {
14263     // The EAX register is loaded with the low-order 32 bits. The EDX register
14264     // is loaded with the supported high-order bits of the counter.
14265     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14266                               DAG.getConstant(32, MVT::i8));
14267     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14268     Results.push_back(Chain);
14269     return;
14270   }
14271
14272   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14273   SDValue Ops[] = { LO, HI };
14274   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14275   Results.push_back(Pair);
14276   Results.push_back(Chain);
14277 }
14278
14279 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14280 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14281 // also used to custom lower READCYCLECOUNTER nodes.
14282 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14283                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14284                               SmallVectorImpl<SDValue> &Results) {
14285   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14286   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14287   SDValue LO, HI;
14288
14289   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14290   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14291   // and the EAX register is loaded with the low-order 32 bits.
14292   if (Subtarget->is64Bit()) {
14293     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14294     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14295                             LO.getValue(2));
14296   } else {
14297     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14298     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14299                             LO.getValue(2));
14300   }
14301   SDValue Chain = HI.getValue(1);
14302
14303   if (Opcode == X86ISD::RDTSCP_DAG) {
14304     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14305
14306     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14307     // the ECX register. Add 'ecx' explicitly to the chain.
14308     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14309                                      HI.getValue(2));
14310     // Explicitly store the content of ECX at the location passed in input
14311     // to the 'rdtscp' intrinsic.
14312     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14313                          MachinePointerInfo(), false, false, 0);
14314   }
14315
14316   if (Subtarget->is64Bit()) {
14317     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14318     // the EAX register is loaded with the low-order 32 bits.
14319     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14320                               DAG.getConstant(32, MVT::i8));
14321     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14322     Results.push_back(Chain);
14323     return;
14324   }
14325
14326   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14327   SDValue Ops[] = { LO, HI };
14328   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14329   Results.push_back(Pair);
14330   Results.push_back(Chain);
14331 }
14332
14333 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14334                                      SelectionDAG &DAG) {
14335   SmallVector<SDValue, 2> Results;
14336   SDLoc DL(Op);
14337   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14338                           Results);
14339   return DAG.getMergeValues(Results, DL);
14340 }
14341
14342 enum IntrinsicType {
14343   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14344 };
14345
14346 struct IntrinsicData {
14347   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14348     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14349   IntrinsicType Type;
14350   unsigned      Opc0;
14351   unsigned      Opc1;
14352 };
14353
14354 std::map < unsigned, IntrinsicData> IntrMap;
14355 static void InitIntinsicsMap() {
14356   static bool Initialized = false;
14357   if (Initialized) 
14358     return;
14359   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14360                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14361   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14362                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14363   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14364                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14365   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14366                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14367   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14368                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14369   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14370                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14371   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14372                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14373   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14374                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14375   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14376                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14377
14378   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14379                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14380   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14381                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14382   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14383                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14384   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14385                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14386   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14387                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14388   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14389                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14390   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14391                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14392   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14393                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14394    
14395   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14396                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14397                                                         X86::VGATHERPF1QPSm)));
14398   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14399                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14400                                                         X86::VGATHERPF1QPDm)));
14401   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14402                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14403                                                         X86::VGATHERPF1DPDm)));
14404   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14405                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14406                                                         X86::VGATHERPF1DPSm)));
14407   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14408                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14409                                                         X86::VSCATTERPF1QPSm)));
14410   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14411                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14412                                                         X86::VSCATTERPF1QPDm)));
14413   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14414                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14415                                                         X86::VSCATTERPF1DPDm)));
14416   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14417                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14418                                                         X86::VSCATTERPF1DPSm)));
14419   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14420                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14421   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14422                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14423   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14424                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14425   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14426                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14427   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14428                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14429   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14430                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14431   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14432                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14433   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14434                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14435   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14436                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14437   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14438                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
14439   Initialized = true;
14440 }
14441
14442 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14443                                       SelectionDAG &DAG) {
14444   InitIntinsicsMap();
14445   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14446   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14447   if (itr == IntrMap.end())
14448     return SDValue();
14449
14450   SDLoc dl(Op);
14451   IntrinsicData Intr = itr->second;
14452   switch(Intr.Type) {
14453   case RDSEED:
14454   case RDRAND: {
14455     // Emit the node with the right value type.
14456     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14457     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14458
14459     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14460     // Otherwise return the value from Rand, which is always 0, casted to i32.
14461     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14462                       DAG.getConstant(1, Op->getValueType(1)),
14463                       DAG.getConstant(X86::COND_B, MVT::i32),
14464                       SDValue(Result.getNode(), 1) };
14465     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14466                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14467                                   Ops);
14468
14469     // Return { result, isValid, chain }.
14470     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14471                        SDValue(Result.getNode(), 2));
14472   }
14473   case GATHER: {
14474   //gather(v1, mask, index, base, scale);
14475     SDValue Chain = Op.getOperand(0);
14476     SDValue Src   = Op.getOperand(2);
14477     SDValue Base  = Op.getOperand(3);
14478     SDValue Index = Op.getOperand(4);
14479     SDValue Mask  = Op.getOperand(5);
14480     SDValue Scale = Op.getOperand(6);
14481     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14482                           Subtarget);
14483   }
14484   case SCATTER: {
14485   //scatter(base, mask, index, v1, scale);
14486     SDValue Chain = Op.getOperand(0);
14487     SDValue Base  = Op.getOperand(2);
14488     SDValue Mask  = Op.getOperand(3);
14489     SDValue Index = Op.getOperand(4);
14490     SDValue Src   = Op.getOperand(5);
14491     SDValue Scale = Op.getOperand(6);
14492     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14493   }
14494   case PREFETCH: {
14495     SDValue Hint = Op.getOperand(6);
14496     unsigned HintVal;
14497     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14498         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14499       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14500     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14501     SDValue Chain = Op.getOperand(0);
14502     SDValue Mask  = Op.getOperand(2);
14503     SDValue Index = Op.getOperand(3);
14504     SDValue Base  = Op.getOperand(4);
14505     SDValue Scale = Op.getOperand(5);
14506     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14507   }
14508   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14509   case RDTSC: {
14510     SmallVector<SDValue, 2> Results;
14511     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14512     return DAG.getMergeValues(Results, dl);
14513   }
14514   // Read Performance Monitoring Counters.
14515   case RDPMC: {
14516     SmallVector<SDValue, 2> Results;
14517     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14518     return DAG.getMergeValues(Results, dl);
14519   }
14520   // XTEST intrinsics.
14521   case XTEST: {
14522     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14523     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14524     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14525                                 DAG.getConstant(X86::COND_NE, MVT::i8),
14526                                 InTrans);
14527     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14528     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14529                        Ret, SDValue(InTrans.getNode(), 1));
14530   }
14531   }
14532   llvm_unreachable("Unknown Intrinsic Type");
14533 }
14534
14535 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14536                                            SelectionDAG &DAG) const {
14537   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14538   MFI->setReturnAddressIsTaken(true);
14539
14540   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14541     return SDValue();
14542
14543   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14544   SDLoc dl(Op);
14545   EVT PtrVT = getPointerTy();
14546
14547   if (Depth > 0) {
14548     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14549     const X86RegisterInfo *RegInfo =
14550       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14551     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14552     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14553                        DAG.getNode(ISD::ADD, dl, PtrVT,
14554                                    FrameAddr, Offset),
14555                        MachinePointerInfo(), false, false, false, 0);
14556   }
14557
14558   // Just load the return address.
14559   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14560   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14561                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14562 }
14563
14564 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14565   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14566   MFI->setFrameAddressIsTaken(true);
14567
14568   EVT VT = Op.getValueType();
14569   SDLoc dl(Op);  // FIXME probably not meaningful
14570   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14571   const X86RegisterInfo *RegInfo =
14572     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14573   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14574   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14575           (FrameReg == X86::EBP && VT == MVT::i32)) &&
14576          "Invalid Frame Register!");
14577   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14578   while (Depth--)
14579     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14580                             MachinePointerInfo(),
14581                             false, false, false, 0);
14582   return FrameAddr;
14583 }
14584
14585 // FIXME? Maybe this could be a TableGen attribute on some registers and
14586 // this table could be generated automatically from RegInfo.
14587 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14588                                               EVT VT) const {
14589   unsigned Reg = StringSwitch<unsigned>(RegName)
14590                        .Case("esp", X86::ESP)
14591                        .Case("rsp", X86::RSP)
14592                        .Default(0);
14593   if (Reg)
14594     return Reg;
14595   report_fatal_error("Invalid register name global variable");
14596 }
14597
14598 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14599                                                      SelectionDAG &DAG) const {
14600   const X86RegisterInfo *RegInfo =
14601     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14602   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14603 }
14604
14605 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14606   SDValue Chain     = Op.getOperand(0);
14607   SDValue Offset    = Op.getOperand(1);
14608   SDValue Handler   = Op.getOperand(2);
14609   SDLoc dl      (Op);
14610
14611   EVT PtrVT = getPointerTy();
14612   const X86RegisterInfo *RegInfo =
14613     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14614   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14615   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14616           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14617          "Invalid Frame Register!");
14618   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14619   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14620
14621   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14622                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14623   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14624   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14625                        false, false, 0);
14626   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14627
14628   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14629                      DAG.getRegister(StoreAddrReg, PtrVT));
14630 }
14631
14632 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14633                                                SelectionDAG &DAG) const {
14634   SDLoc DL(Op);
14635   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14636                      DAG.getVTList(MVT::i32, MVT::Other),
14637                      Op.getOperand(0), Op.getOperand(1));
14638 }
14639
14640 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14641                                                 SelectionDAG &DAG) const {
14642   SDLoc DL(Op);
14643   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14644                      Op.getOperand(0), Op.getOperand(1));
14645 }
14646
14647 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14648   return Op.getOperand(0);
14649 }
14650
14651 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14652                                                 SelectionDAG &DAG) const {
14653   SDValue Root = Op.getOperand(0);
14654   SDValue Trmp = Op.getOperand(1); // trampoline
14655   SDValue FPtr = Op.getOperand(2); // nested function
14656   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14657   SDLoc dl (Op);
14658
14659   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14660   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14661
14662   if (Subtarget->is64Bit()) {
14663     SDValue OutChains[6];
14664
14665     // Large code-model.
14666     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
14667     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14668
14669     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14670     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14671
14672     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14673
14674     // Load the pointer to the nested function into R11.
14675     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14676     SDValue Addr = Trmp;
14677     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14678                                 Addr, MachinePointerInfo(TrmpAddr),
14679                                 false, false, 0);
14680
14681     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14682                        DAG.getConstant(2, MVT::i64));
14683     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14684                                 MachinePointerInfo(TrmpAddr, 2),
14685                                 false, false, 2);
14686
14687     // Load the 'nest' parameter value into R10.
14688     // R10 is specified in X86CallingConv.td
14689     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14690     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14691                        DAG.getConstant(10, MVT::i64));
14692     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14693                                 Addr, MachinePointerInfo(TrmpAddr, 10),
14694                                 false, false, 0);
14695
14696     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14697                        DAG.getConstant(12, MVT::i64));
14698     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14699                                 MachinePointerInfo(TrmpAddr, 12),
14700                                 false, false, 2);
14701
14702     // Jump to the nested function.
14703     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14704     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14705                        DAG.getConstant(20, MVT::i64));
14706     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14707                                 Addr, MachinePointerInfo(TrmpAddr, 20),
14708                                 false, false, 0);
14709
14710     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14711     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14712                        DAG.getConstant(22, MVT::i64));
14713     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14714                                 MachinePointerInfo(TrmpAddr, 22),
14715                                 false, false, 0);
14716
14717     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14718   } else {
14719     const Function *Func =
14720       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14721     CallingConv::ID CC = Func->getCallingConv();
14722     unsigned NestReg;
14723
14724     switch (CC) {
14725     default:
14726       llvm_unreachable("Unsupported calling convention");
14727     case CallingConv::C:
14728     case CallingConv::X86_StdCall: {
14729       // Pass 'nest' parameter in ECX.
14730       // Must be kept in sync with X86CallingConv.td
14731       NestReg = X86::ECX;
14732
14733       // Check that ECX wasn't needed by an 'inreg' parameter.
14734       FunctionType *FTy = Func->getFunctionType();
14735       const AttributeSet &Attrs = Func->getAttributes();
14736
14737       if (!Attrs.isEmpty() && !Func->isVarArg()) {
14738         unsigned InRegCount = 0;
14739         unsigned Idx = 1;
14740
14741         for (FunctionType::param_iterator I = FTy->param_begin(),
14742              E = FTy->param_end(); I != E; ++I, ++Idx)
14743           if (Attrs.hasAttribute(Idx, Attribute::InReg))
14744             // FIXME: should only count parameters that are lowered to integers.
14745             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14746
14747         if (InRegCount > 2) {
14748           report_fatal_error("Nest register in use - reduce number of inreg"
14749                              " parameters!");
14750         }
14751       }
14752       break;
14753     }
14754     case CallingConv::X86_FastCall:
14755     case CallingConv::X86_ThisCall:
14756     case CallingConv::Fast:
14757       // Pass 'nest' parameter in EAX.
14758       // Must be kept in sync with X86CallingConv.td
14759       NestReg = X86::EAX;
14760       break;
14761     }
14762
14763     SDValue OutChains[4];
14764     SDValue Addr, Disp;
14765
14766     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14767                        DAG.getConstant(10, MVT::i32));
14768     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14769
14770     // This is storing the opcode for MOV32ri.
14771     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14772     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14773     OutChains[0] = DAG.getStore(Root, dl,
14774                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14775                                 Trmp, MachinePointerInfo(TrmpAddr),
14776                                 false, false, 0);
14777
14778     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14779                        DAG.getConstant(1, MVT::i32));
14780     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14781                                 MachinePointerInfo(TrmpAddr, 1),
14782                                 false, false, 1);
14783
14784     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14785     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14786                        DAG.getConstant(5, MVT::i32));
14787     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14788                                 MachinePointerInfo(TrmpAddr, 5),
14789                                 false, false, 1);
14790
14791     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14792                        DAG.getConstant(6, MVT::i32));
14793     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14794                                 MachinePointerInfo(TrmpAddr, 6),
14795                                 false, false, 1);
14796
14797     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14798   }
14799 }
14800
14801 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14802                                             SelectionDAG &DAG) const {
14803   /*
14804    The rounding mode is in bits 11:10 of FPSR, and has the following
14805    settings:
14806      00 Round to nearest
14807      01 Round to -inf
14808      10 Round to +inf
14809      11 Round to 0
14810
14811   FLT_ROUNDS, on the other hand, expects the following:
14812     -1 Undefined
14813      0 Round to 0
14814      1 Round to nearest
14815      2 Round to +inf
14816      3 Round to -inf
14817
14818   To perform the conversion, we do:
14819     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14820   */
14821
14822   MachineFunction &MF = DAG.getMachineFunction();
14823   const TargetMachine &TM = MF.getTarget();
14824   const TargetFrameLowering &TFI = *TM.getFrameLowering();
14825   unsigned StackAlignment = TFI.getStackAlignment();
14826   MVT VT = Op.getSimpleValueType();
14827   SDLoc DL(Op);
14828
14829   // Save FP Control Word to stack slot
14830   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14831   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14832
14833   MachineMemOperand *MMO =
14834    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14835                            MachineMemOperand::MOStore, 2, 2);
14836
14837   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14838   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14839                                           DAG.getVTList(MVT::Other),
14840                                           Ops, MVT::i16, MMO);
14841
14842   // Load FP Control Word from stack slot
14843   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14844                             MachinePointerInfo(), false, false, false, 0);
14845
14846   // Transform as necessary
14847   SDValue CWD1 =
14848     DAG.getNode(ISD::SRL, DL, MVT::i16,
14849                 DAG.getNode(ISD::AND, DL, MVT::i16,
14850                             CWD, DAG.getConstant(0x800, MVT::i16)),
14851                 DAG.getConstant(11, MVT::i8));
14852   SDValue CWD2 =
14853     DAG.getNode(ISD::SRL, DL, MVT::i16,
14854                 DAG.getNode(ISD::AND, DL, MVT::i16,
14855                             CWD, DAG.getConstant(0x400, MVT::i16)),
14856                 DAG.getConstant(9, MVT::i8));
14857
14858   SDValue RetVal =
14859     DAG.getNode(ISD::AND, DL, MVT::i16,
14860                 DAG.getNode(ISD::ADD, DL, MVT::i16,
14861                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14862                             DAG.getConstant(1, MVT::i16)),
14863                 DAG.getConstant(3, MVT::i16));
14864
14865   return DAG.getNode((VT.getSizeInBits() < 16 ?
14866                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14867 }
14868
14869 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14870   MVT VT = Op.getSimpleValueType();
14871   EVT OpVT = VT;
14872   unsigned NumBits = VT.getSizeInBits();
14873   SDLoc dl(Op);
14874
14875   Op = Op.getOperand(0);
14876   if (VT == MVT::i8) {
14877     // Zero extend to i32 since there is not an i8 bsr.
14878     OpVT = MVT::i32;
14879     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14880   }
14881
14882   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14883   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14884   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14885
14886   // If src is zero (i.e. bsr sets ZF), returns NumBits.
14887   SDValue Ops[] = {
14888     Op,
14889     DAG.getConstant(NumBits+NumBits-1, OpVT),
14890     DAG.getConstant(X86::COND_E, MVT::i8),
14891     Op.getValue(1)
14892   };
14893   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14894
14895   // Finally xor with NumBits-1.
14896   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14897
14898   if (VT == MVT::i8)
14899     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14900   return Op;
14901 }
14902
14903 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14904   MVT VT = Op.getSimpleValueType();
14905   EVT OpVT = VT;
14906   unsigned NumBits = VT.getSizeInBits();
14907   SDLoc dl(Op);
14908
14909   Op = Op.getOperand(0);
14910   if (VT == MVT::i8) {
14911     // Zero extend to i32 since there is not an i8 bsr.
14912     OpVT = MVT::i32;
14913     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14914   }
14915
14916   // Issue a bsr (scan bits in reverse).
14917   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14918   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14919
14920   // And xor with NumBits-1.
14921   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14922
14923   if (VT == MVT::i8)
14924     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14925   return Op;
14926 }
14927
14928 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14929   MVT VT = Op.getSimpleValueType();
14930   unsigned NumBits = VT.getSizeInBits();
14931   SDLoc dl(Op);
14932   Op = Op.getOperand(0);
14933
14934   // Issue a bsf (scan bits forward) which also sets EFLAGS.
14935   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14936   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14937
14938   // If src is zero (i.e. bsf sets ZF), returns NumBits.
14939   SDValue Ops[] = {
14940     Op,
14941     DAG.getConstant(NumBits, VT),
14942     DAG.getConstant(X86::COND_E, MVT::i8),
14943     Op.getValue(1)
14944   };
14945   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14946 }
14947
14948 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
14949 // ones, and then concatenate the result back.
14950 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
14951   MVT VT = Op.getSimpleValueType();
14952
14953   assert(VT.is256BitVector() && VT.isInteger() &&
14954          "Unsupported value type for operation");
14955
14956   unsigned NumElems = VT.getVectorNumElements();
14957   SDLoc dl(Op);
14958
14959   // Extract the LHS vectors
14960   SDValue LHS = Op.getOperand(0);
14961   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14962   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14963
14964   // Extract the RHS vectors
14965   SDValue RHS = Op.getOperand(1);
14966   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14967   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14968
14969   MVT EltVT = VT.getVectorElementType();
14970   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14971
14972   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14973                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
14974                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
14975 }
14976
14977 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
14978   assert(Op.getSimpleValueType().is256BitVector() &&
14979          Op.getSimpleValueType().isInteger() &&
14980          "Only handle AVX 256-bit vector integer operation");
14981   return Lower256IntArith(Op, DAG);
14982 }
14983
14984 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
14985   assert(Op.getSimpleValueType().is256BitVector() &&
14986          Op.getSimpleValueType().isInteger() &&
14987          "Only handle AVX 256-bit vector integer operation");
14988   return Lower256IntArith(Op, DAG);
14989 }
14990
14991 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
14992                         SelectionDAG &DAG) {
14993   SDLoc dl(Op);
14994   MVT VT = Op.getSimpleValueType();
14995
14996   // Decompose 256-bit ops into smaller 128-bit ops.
14997   if (VT.is256BitVector() && !Subtarget->hasInt256())
14998     return Lower256IntArith(Op, DAG);
14999
15000   SDValue A = Op.getOperand(0);
15001   SDValue B = Op.getOperand(1);
15002
15003   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15004   if (VT == MVT::v4i32) {
15005     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15006            "Should not custom lower when pmuldq is available!");
15007
15008     // Extract the odd parts.
15009     static const int UnpackMask[] = { 1, -1, 3, -1 };
15010     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15011     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15012
15013     // Multiply the even parts.
15014     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15015     // Now multiply odd parts.
15016     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15017
15018     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15019     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15020
15021     // Merge the two vectors back together with a shuffle. This expands into 2
15022     // shuffles.
15023     static const int ShufMask[] = { 0, 4, 2, 6 };
15024     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15025   }
15026
15027   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15028          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15029
15030   //  Ahi = psrlqi(a, 32);
15031   //  Bhi = psrlqi(b, 32);
15032   //
15033   //  AloBlo = pmuludq(a, b);
15034   //  AloBhi = pmuludq(a, Bhi);
15035   //  AhiBlo = pmuludq(Ahi, b);
15036
15037   //  AloBhi = psllqi(AloBhi, 32);
15038   //  AhiBlo = psllqi(AhiBlo, 32);
15039   //  return AloBlo + AloBhi + AhiBlo;
15040
15041   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15042   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15043
15044   // Bit cast to 32-bit vectors for MULUDQ
15045   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15046                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15047   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15048   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15049   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15050   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15051
15052   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15053   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15054   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15055
15056   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15057   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15058
15059   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15060   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15061 }
15062
15063 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15064   assert(Subtarget->isTargetWin64() && "Unexpected target");
15065   EVT VT = Op.getValueType();
15066   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15067          "Unexpected return type for lowering");
15068
15069   RTLIB::Libcall LC;
15070   bool isSigned;
15071   switch (Op->getOpcode()) {
15072   default: llvm_unreachable("Unexpected request for libcall!");
15073   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15074   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15075   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15076   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15077   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15078   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15079   }
15080
15081   SDLoc dl(Op);
15082   SDValue InChain = DAG.getEntryNode();
15083
15084   TargetLowering::ArgListTy Args;
15085   TargetLowering::ArgListEntry Entry;
15086   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15087     EVT ArgVT = Op->getOperand(i).getValueType();
15088     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15089            "Unexpected argument type for lowering");
15090     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15091     Entry.Node = StackPtr;
15092     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15093                            false, false, 16);
15094     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15095     Entry.Ty = PointerType::get(ArgTy,0);
15096     Entry.isSExt = false;
15097     Entry.isZExt = false;
15098     Args.push_back(Entry);
15099   }
15100
15101   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15102                                          getPointerTy());
15103
15104   TargetLowering::CallLoweringInfo CLI(DAG);
15105   CLI.setDebugLoc(dl).setChain(InChain)
15106     .setCallee(getLibcallCallingConv(LC),
15107                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15108                Callee, std::move(Args), 0)
15109     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15110
15111   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15112   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15113 }
15114
15115 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15116                              SelectionDAG &DAG) {
15117   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15118   EVT VT = Op0.getValueType();
15119   SDLoc dl(Op);
15120
15121   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15122          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15123
15124   // Get the high parts.
15125   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15126   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15127   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15128
15129   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15130   // ints.
15131   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15132   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15133   unsigned Opcode =
15134       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15135   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15136                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15137   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15138                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
15139
15140   // Shuffle it back into the right order.
15141   SDValue Highs, Lows;
15142   if (VT == MVT::v8i32) {
15143     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15144     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15145     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15146     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15147   } else {
15148     const int HighMask[] = {1, 5, 3, 7};
15149     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15150     const int LowMask[] = {0, 4, 2, 6};
15151     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15152   }
15153
15154   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15155   // unsigned multiply.
15156   if (IsSigned && !Subtarget->hasSSE41()) {
15157     SDValue ShAmt =
15158         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15159     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15160                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15161     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15162                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15163
15164     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15165     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15166   }
15167
15168   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
15169 }
15170
15171 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15172                                          const X86Subtarget *Subtarget) {
15173   MVT VT = Op.getSimpleValueType();
15174   SDLoc dl(Op);
15175   SDValue R = Op.getOperand(0);
15176   SDValue Amt = Op.getOperand(1);
15177
15178   // Optimize shl/srl/sra with constant shift amount.
15179   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15180     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15181       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15182
15183       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15184           (Subtarget->hasInt256() &&
15185            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15186           (Subtarget->hasAVX512() &&
15187            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15188         if (Op.getOpcode() == ISD::SHL)
15189           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15190                                             DAG);
15191         if (Op.getOpcode() == ISD::SRL)
15192           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15193                                             DAG);
15194         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15195           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15196                                             DAG);
15197       }
15198
15199       if (VT == MVT::v16i8) {
15200         if (Op.getOpcode() == ISD::SHL) {
15201           // Make a large shift.
15202           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15203                                                    MVT::v8i16, R, ShiftAmt,
15204                                                    DAG);
15205           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15206           // Zero out the rightmost bits.
15207           SmallVector<SDValue, 16> V(16,
15208                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15209                                                      MVT::i8));
15210           return DAG.getNode(ISD::AND, dl, VT, SHL,
15211                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15212         }
15213         if (Op.getOpcode() == ISD::SRL) {
15214           // Make a large shift.
15215           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15216                                                    MVT::v8i16, R, ShiftAmt,
15217                                                    DAG);
15218           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15219           // Zero out the leftmost bits.
15220           SmallVector<SDValue, 16> V(16,
15221                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15222                                                      MVT::i8));
15223           return DAG.getNode(ISD::AND, dl, VT, SRL,
15224                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15225         }
15226         if (Op.getOpcode() == ISD::SRA) {
15227           if (ShiftAmt == 7) {
15228             // R s>> 7  ===  R s< 0
15229             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15230             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15231           }
15232
15233           // R s>> a === ((R u>> a) ^ m) - m
15234           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15235           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15236                                                          MVT::i8));
15237           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15238           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15239           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15240           return Res;
15241         }
15242         llvm_unreachable("Unknown shift opcode.");
15243       }
15244
15245       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15246         if (Op.getOpcode() == ISD::SHL) {
15247           // Make a large shift.
15248           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15249                                                    MVT::v16i16, R, ShiftAmt,
15250                                                    DAG);
15251           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15252           // Zero out the rightmost bits.
15253           SmallVector<SDValue, 32> V(32,
15254                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15255                                                      MVT::i8));
15256           return DAG.getNode(ISD::AND, dl, VT, SHL,
15257                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15258         }
15259         if (Op.getOpcode() == ISD::SRL) {
15260           // Make a large shift.
15261           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15262                                                    MVT::v16i16, R, ShiftAmt,
15263                                                    DAG);
15264           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15265           // Zero out the leftmost bits.
15266           SmallVector<SDValue, 32> V(32,
15267                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15268                                                      MVT::i8));
15269           return DAG.getNode(ISD::AND, dl, VT, SRL,
15270                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15271         }
15272         if (Op.getOpcode() == ISD::SRA) {
15273           if (ShiftAmt == 7) {
15274             // R s>> 7  ===  R s< 0
15275             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15276             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15277           }
15278
15279           // R s>> a === ((R u>> a) ^ m) - m
15280           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15281           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15282                                                          MVT::i8));
15283           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15284           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15285           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15286           return Res;
15287         }
15288         llvm_unreachable("Unknown shift opcode.");
15289       }
15290     }
15291   }
15292
15293   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15294   if (!Subtarget->is64Bit() &&
15295       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15296       Amt.getOpcode() == ISD::BITCAST &&
15297       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15298     Amt = Amt.getOperand(0);
15299     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15300                      VT.getVectorNumElements();
15301     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15302     uint64_t ShiftAmt = 0;
15303     for (unsigned i = 0; i != Ratio; ++i) {
15304       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15305       if (!C)
15306         return SDValue();
15307       // 6 == Log2(64)
15308       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15309     }
15310     // Check remaining shift amounts.
15311     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15312       uint64_t ShAmt = 0;
15313       for (unsigned j = 0; j != Ratio; ++j) {
15314         ConstantSDNode *C =
15315           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15316         if (!C)
15317           return SDValue();
15318         // 6 == Log2(64)
15319         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15320       }
15321       if (ShAmt != ShiftAmt)
15322         return SDValue();
15323     }
15324     switch (Op.getOpcode()) {
15325     default:
15326       llvm_unreachable("Unknown shift opcode!");
15327     case ISD::SHL:
15328       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15329                                         DAG);
15330     case ISD::SRL:
15331       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15332                                         DAG);
15333     case ISD::SRA:
15334       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15335                                         DAG);
15336     }
15337   }
15338
15339   return SDValue();
15340 }
15341
15342 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15343                                         const X86Subtarget* Subtarget) {
15344   MVT VT = Op.getSimpleValueType();
15345   SDLoc dl(Op);
15346   SDValue R = Op.getOperand(0);
15347   SDValue Amt = Op.getOperand(1);
15348
15349   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15350       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15351       (Subtarget->hasInt256() &&
15352        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15353         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15354        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15355     SDValue BaseShAmt;
15356     EVT EltVT = VT.getVectorElementType();
15357
15358     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15359       unsigned NumElts = VT.getVectorNumElements();
15360       unsigned i, j;
15361       for (i = 0; i != NumElts; ++i) {
15362         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15363           continue;
15364         break;
15365       }
15366       for (j = i; j != NumElts; ++j) {
15367         SDValue Arg = Amt.getOperand(j);
15368         if (Arg.getOpcode() == ISD::UNDEF) continue;
15369         if (Arg != Amt.getOperand(i))
15370           break;
15371       }
15372       if (i != NumElts && j == NumElts)
15373         BaseShAmt = Amt.getOperand(i);
15374     } else {
15375       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15376         Amt = Amt.getOperand(0);
15377       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15378                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15379         SDValue InVec = Amt.getOperand(0);
15380         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15381           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15382           unsigned i = 0;
15383           for (; i != NumElts; ++i) {
15384             SDValue Arg = InVec.getOperand(i);
15385             if (Arg.getOpcode() == ISD::UNDEF) continue;
15386             BaseShAmt = Arg;
15387             break;
15388           }
15389         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15390            if (ConstantSDNode *C =
15391                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15392              unsigned SplatIdx =
15393                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15394              if (C->getZExtValue() == SplatIdx)
15395                BaseShAmt = InVec.getOperand(1);
15396            }
15397         }
15398         if (!BaseShAmt.getNode())
15399           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15400                                   DAG.getIntPtrConstant(0));
15401       }
15402     }
15403
15404     if (BaseShAmt.getNode()) {
15405       if (EltVT.bitsGT(MVT::i32))
15406         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15407       else if (EltVT.bitsLT(MVT::i32))
15408         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15409
15410       switch (Op.getOpcode()) {
15411       default:
15412         llvm_unreachable("Unknown shift opcode!");
15413       case ISD::SHL:
15414         switch (VT.SimpleTy) {
15415         default: return SDValue();
15416         case MVT::v2i64:
15417         case MVT::v4i32:
15418         case MVT::v8i16:
15419         case MVT::v4i64:
15420         case MVT::v8i32:
15421         case MVT::v16i16:
15422         case MVT::v16i32:
15423         case MVT::v8i64:
15424           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15425         }
15426       case ISD::SRA:
15427         switch (VT.SimpleTy) {
15428         default: return SDValue();
15429         case MVT::v4i32:
15430         case MVT::v8i16:
15431         case MVT::v8i32:
15432         case MVT::v16i16:
15433         case MVT::v16i32:
15434         case MVT::v8i64:
15435           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15436         }
15437       case ISD::SRL:
15438         switch (VT.SimpleTy) {
15439         default: return SDValue();
15440         case MVT::v2i64:
15441         case MVT::v4i32:
15442         case MVT::v8i16:
15443         case MVT::v4i64:
15444         case MVT::v8i32:
15445         case MVT::v16i16:
15446         case MVT::v16i32:
15447         case MVT::v8i64:
15448           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15449         }
15450       }
15451     }
15452   }
15453
15454   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15455   if (!Subtarget->is64Bit() &&
15456       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15457       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15458       Amt.getOpcode() == ISD::BITCAST &&
15459       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15460     Amt = Amt.getOperand(0);
15461     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15462                      VT.getVectorNumElements();
15463     std::vector<SDValue> Vals(Ratio);
15464     for (unsigned i = 0; i != Ratio; ++i)
15465       Vals[i] = Amt.getOperand(i);
15466     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15467       for (unsigned j = 0; j != Ratio; ++j)
15468         if (Vals[j] != Amt.getOperand(i + j))
15469           return SDValue();
15470     }
15471     switch (Op.getOpcode()) {
15472     default:
15473       llvm_unreachable("Unknown shift opcode!");
15474     case ISD::SHL:
15475       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15476     case ISD::SRL:
15477       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15478     case ISD::SRA:
15479       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15480     }
15481   }
15482
15483   return SDValue();
15484 }
15485
15486 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15487                           SelectionDAG &DAG) {
15488   MVT VT = Op.getSimpleValueType();
15489   SDLoc dl(Op);
15490   SDValue R = Op.getOperand(0);
15491   SDValue Amt = Op.getOperand(1);
15492   SDValue V;
15493
15494   assert(VT.isVector() && "Custom lowering only for vector shifts!");
15495   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15496
15497   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15498   if (V.getNode())
15499     return V;
15500
15501   V = LowerScalarVariableShift(Op, DAG, Subtarget);
15502   if (V.getNode())
15503       return V;
15504
15505   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15506     return Op;
15507   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15508   if (Subtarget->hasInt256()) {
15509     if (Op.getOpcode() == ISD::SRL &&
15510         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15511          VT == MVT::v4i64 || VT == MVT::v8i32))
15512       return Op;
15513     if (Op.getOpcode() == ISD::SHL &&
15514         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15515          VT == MVT::v4i64 || VT == MVT::v8i32))
15516       return Op;
15517     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15518       return Op;
15519   }
15520
15521   // If possible, lower this packed shift into a vector multiply instead of
15522   // expanding it into a sequence of scalar shifts.
15523   // Do this only if the vector shift count is a constant build_vector.
15524   if (Op.getOpcode() == ISD::SHL && 
15525       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15526        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15527       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15528     SmallVector<SDValue, 8> Elts;
15529     EVT SVT = VT.getScalarType();
15530     unsigned SVTBits = SVT.getSizeInBits();
15531     const APInt &One = APInt(SVTBits, 1);
15532     unsigned NumElems = VT.getVectorNumElements();
15533
15534     for (unsigned i=0; i !=NumElems; ++i) {
15535       SDValue Op = Amt->getOperand(i);
15536       if (Op->getOpcode() == ISD::UNDEF) {
15537         Elts.push_back(Op);
15538         continue;
15539       }
15540
15541       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15542       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15543       uint64_t ShAmt = C.getZExtValue();
15544       if (ShAmt >= SVTBits) {
15545         Elts.push_back(DAG.getUNDEF(SVT));
15546         continue;
15547       }
15548       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15549     }
15550     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15551     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15552   }
15553
15554   // Lower SHL with variable shift amount.
15555   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15556     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15557
15558     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15559     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15560     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15561     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15562   }
15563
15564   // If possible, lower this shift as a sequence of two shifts by
15565   // constant plus a MOVSS/MOVSD instead of scalarizing it.
15566   // Example:
15567   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15568   //
15569   // Could be rewritten as:
15570   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15571   //
15572   // The advantage is that the two shifts from the example would be
15573   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15574   // the vector shift into four scalar shifts plus four pairs of vector
15575   // insert/extract.
15576   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15577       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15578     unsigned TargetOpcode = X86ISD::MOVSS;
15579     bool CanBeSimplified;
15580     // The splat value for the first packed shift (the 'X' from the example).
15581     SDValue Amt1 = Amt->getOperand(0);
15582     // The splat value for the second packed shift (the 'Y' from the example).
15583     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15584                                         Amt->getOperand(2);
15585
15586     // See if it is possible to replace this node with a sequence of
15587     // two shifts followed by a MOVSS/MOVSD
15588     if (VT == MVT::v4i32) {
15589       // Check if it is legal to use a MOVSS.
15590       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15591                         Amt2 == Amt->getOperand(3);
15592       if (!CanBeSimplified) {
15593         // Otherwise, check if we can still simplify this node using a MOVSD.
15594         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15595                           Amt->getOperand(2) == Amt->getOperand(3);
15596         TargetOpcode = X86ISD::MOVSD;
15597         Amt2 = Amt->getOperand(2);
15598       }
15599     } else {
15600       // Do similar checks for the case where the machine value type
15601       // is MVT::v8i16.
15602       CanBeSimplified = Amt1 == Amt->getOperand(1);
15603       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15604         CanBeSimplified = Amt2 == Amt->getOperand(i);
15605
15606       if (!CanBeSimplified) {
15607         TargetOpcode = X86ISD::MOVSD;
15608         CanBeSimplified = true;
15609         Amt2 = Amt->getOperand(4);
15610         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15611           CanBeSimplified = Amt1 == Amt->getOperand(i);
15612         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15613           CanBeSimplified = Amt2 == Amt->getOperand(j);
15614       }
15615     }
15616     
15617     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15618         isa<ConstantSDNode>(Amt2)) {
15619       // Replace this node with two shifts followed by a MOVSS/MOVSD.
15620       EVT CastVT = MVT::v4i32;
15621       SDValue Splat1 = 
15622         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15623       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15624       SDValue Splat2 = 
15625         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15626       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15627       if (TargetOpcode == X86ISD::MOVSD)
15628         CastVT = MVT::v2i64;
15629       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15630       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15631       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15632                                             BitCast1, DAG);
15633       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15634     }
15635   }
15636
15637   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15638     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15639
15640     // a = a << 5;
15641     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15642     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15643
15644     // Turn 'a' into a mask suitable for VSELECT
15645     SDValue VSelM = DAG.getConstant(0x80, VT);
15646     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15647     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15648
15649     SDValue CM1 = DAG.getConstant(0x0f, VT);
15650     SDValue CM2 = DAG.getConstant(0x3f, VT);
15651
15652     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15653     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15654     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15655     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15656     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15657
15658     // a += a
15659     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15660     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15661     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15662
15663     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15664     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15665     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15666     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15667     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15668
15669     // a += a
15670     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15671     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15672     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15673
15674     // return VSELECT(r, r+r, a);
15675     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15676                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15677     return R;
15678   }
15679
15680   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15681   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15682   // solution better.
15683   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15684     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15685     unsigned ExtOpc =
15686         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15687     R = DAG.getNode(ExtOpc, dl, NewVT, R);
15688     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15689     return DAG.getNode(ISD::TRUNCATE, dl, VT,
15690                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15691     }
15692
15693   // Decompose 256-bit shifts into smaller 128-bit shifts.
15694   if (VT.is256BitVector()) {
15695     unsigned NumElems = VT.getVectorNumElements();
15696     MVT EltVT = VT.getVectorElementType();
15697     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15698
15699     // Extract the two vectors
15700     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15701     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15702
15703     // Recreate the shift amount vectors
15704     SDValue Amt1, Amt2;
15705     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15706       // Constant shift amount
15707       SmallVector<SDValue, 4> Amt1Csts;
15708       SmallVector<SDValue, 4> Amt2Csts;
15709       for (unsigned i = 0; i != NumElems/2; ++i)
15710         Amt1Csts.push_back(Amt->getOperand(i));
15711       for (unsigned i = NumElems/2; i != NumElems; ++i)
15712         Amt2Csts.push_back(Amt->getOperand(i));
15713
15714       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15715       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15716     } else {
15717       // Variable shift amount
15718       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15719       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15720     }
15721
15722     // Issue new vector shifts for the smaller types
15723     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15724     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15725
15726     // Concatenate the result back
15727     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15728   }
15729
15730   return SDValue();
15731 }
15732
15733 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15734   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15735   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15736   // looks for this combo and may remove the "setcc" instruction if the "setcc"
15737   // has only one use.
15738   SDNode *N = Op.getNode();
15739   SDValue LHS = N->getOperand(0);
15740   SDValue RHS = N->getOperand(1);
15741   unsigned BaseOp = 0;
15742   unsigned Cond = 0;
15743   SDLoc DL(Op);
15744   switch (Op.getOpcode()) {
15745   default: llvm_unreachable("Unknown ovf instruction!");
15746   case ISD::SADDO:
15747     // A subtract of one will be selected as a INC. Note that INC doesn't
15748     // set CF, so we can't do this for UADDO.
15749     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15750       if (C->isOne()) {
15751         BaseOp = X86ISD::INC;
15752         Cond = X86::COND_O;
15753         break;
15754       }
15755     BaseOp = X86ISD::ADD;
15756     Cond = X86::COND_O;
15757     break;
15758   case ISD::UADDO:
15759     BaseOp = X86ISD::ADD;
15760     Cond = X86::COND_B;
15761     break;
15762   case ISD::SSUBO:
15763     // A subtract of one will be selected as a DEC. Note that DEC doesn't
15764     // set CF, so we can't do this for USUBO.
15765     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15766       if (C->isOne()) {
15767         BaseOp = X86ISD::DEC;
15768         Cond = X86::COND_O;
15769         break;
15770       }
15771     BaseOp = X86ISD::SUB;
15772     Cond = X86::COND_O;
15773     break;
15774   case ISD::USUBO:
15775     BaseOp = X86ISD::SUB;
15776     Cond = X86::COND_B;
15777     break;
15778   case ISD::SMULO:
15779     BaseOp = X86ISD::SMUL;
15780     Cond = X86::COND_O;
15781     break;
15782   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15783     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15784                                  MVT::i32);
15785     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15786
15787     SDValue SetCC =
15788       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15789                   DAG.getConstant(X86::COND_O, MVT::i32),
15790                   SDValue(Sum.getNode(), 2));
15791
15792     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15793   }
15794   }
15795
15796   // Also sets EFLAGS.
15797   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15798   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15799
15800   SDValue SetCC =
15801     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15802                 DAG.getConstant(Cond, MVT::i32),
15803                 SDValue(Sum.getNode(), 1));
15804
15805   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15806 }
15807
15808 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15809                                                   SelectionDAG &DAG) const {
15810   SDLoc dl(Op);
15811   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15812   MVT VT = Op.getSimpleValueType();
15813
15814   if (!Subtarget->hasSSE2() || !VT.isVector())
15815     return SDValue();
15816
15817   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15818                       ExtraVT.getScalarType().getSizeInBits();
15819
15820   switch (VT.SimpleTy) {
15821     default: return SDValue();
15822     case MVT::v8i32:
15823     case MVT::v16i16:
15824       if (!Subtarget->hasFp256())
15825         return SDValue();
15826       if (!Subtarget->hasInt256()) {
15827         // needs to be split
15828         unsigned NumElems = VT.getVectorNumElements();
15829
15830         // Extract the LHS vectors
15831         SDValue LHS = Op.getOperand(0);
15832         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15833         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15834
15835         MVT EltVT = VT.getVectorElementType();
15836         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15837
15838         EVT ExtraEltVT = ExtraVT.getVectorElementType();
15839         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15840         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15841                                    ExtraNumElems/2);
15842         SDValue Extra = DAG.getValueType(ExtraVT);
15843
15844         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15845         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15846
15847         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15848       }
15849       // fall through
15850     case MVT::v4i32:
15851     case MVT::v8i16: {
15852       SDValue Op0 = Op.getOperand(0);
15853       SDValue Op00 = Op0.getOperand(0);
15854       SDValue Tmp1;
15855       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15856       if (Op0.getOpcode() == ISD::BITCAST &&
15857           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15858         // (sext (vzext x)) -> (vsext x)
15859         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15860         if (Tmp1.getNode()) {
15861           EVT ExtraEltVT = ExtraVT.getVectorElementType();
15862           // This folding is only valid when the in-reg type is a vector of i8,
15863           // i16, or i32.
15864           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15865               ExtraEltVT == MVT::i32) {
15866             SDValue Tmp1Op0 = Tmp1.getOperand(0);
15867             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15868                    "This optimization is invalid without a VZEXT.");
15869             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15870           }
15871           Op0 = Tmp1;
15872         }
15873       }
15874
15875       // If the above didn't work, then just use Shift-Left + Shift-Right.
15876       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15877                                         DAG);
15878       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15879                                         DAG);
15880     }
15881   }
15882 }
15883
15884 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15885                                  SelectionDAG &DAG) {
15886   SDLoc dl(Op);
15887   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15888     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15889   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15890     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15891
15892   // The only fence that needs an instruction is a sequentially-consistent
15893   // cross-thread fence.
15894   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15895     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15896     // no-sse2). There isn't any reason to disable it if the target processor
15897     // supports it.
15898     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15899       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15900
15901     SDValue Chain = Op.getOperand(0);
15902     SDValue Zero = DAG.getConstant(0, MVT::i32);
15903     SDValue Ops[] = {
15904       DAG.getRegister(X86::ESP, MVT::i32), // Base
15905       DAG.getTargetConstant(1, MVT::i8),   // Scale
15906       DAG.getRegister(0, MVT::i32),        // Index
15907       DAG.getTargetConstant(0, MVT::i32),  // Disp
15908       DAG.getRegister(0, MVT::i32),        // Segment.
15909       Zero,
15910       Chain
15911     };
15912     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15913     return SDValue(Res, 0);
15914   }
15915
15916   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
15917   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
15918 }
15919
15920 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
15921                              SelectionDAG &DAG) {
15922   MVT T = Op.getSimpleValueType();
15923   SDLoc DL(Op);
15924   unsigned Reg = 0;
15925   unsigned size = 0;
15926   switch(T.SimpleTy) {
15927   default: llvm_unreachable("Invalid value type!");
15928   case MVT::i8:  Reg = X86::AL;  size = 1; break;
15929   case MVT::i16: Reg = X86::AX;  size = 2; break;
15930   case MVT::i32: Reg = X86::EAX; size = 4; break;
15931   case MVT::i64:
15932     assert(Subtarget->is64Bit() && "Node not type legal!");
15933     Reg = X86::RAX; size = 8;
15934     break;
15935   }
15936   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
15937                                   Op.getOperand(2), SDValue());
15938   SDValue Ops[] = { cpIn.getValue(0),
15939                     Op.getOperand(1),
15940                     Op.getOperand(3),
15941                     DAG.getTargetConstant(size, MVT::i8),
15942                     cpIn.getValue(1) };
15943   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15944   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
15945   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
15946                                            Ops, T, MMO);
15947
15948   SDValue cpOut =
15949     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
15950   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
15951                                       MVT::i32, cpOut.getValue(2));
15952   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
15953                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15954
15955   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
15956   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
15957   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
15958   return SDValue();
15959 }
15960
15961 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
15962                             SelectionDAG &DAG) {
15963   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
15964   MVT DstVT = Op.getSimpleValueType();
15965
15966   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
15967     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15968     if (DstVT != MVT::f64)
15969       // This conversion needs to be expanded.
15970       return SDValue();
15971
15972     SDValue InVec = Op->getOperand(0);
15973     SDLoc dl(Op);
15974     unsigned NumElts = SrcVT.getVectorNumElements();
15975     EVT SVT = SrcVT.getVectorElementType();
15976
15977     // Widen the vector in input in the case of MVT::v2i32.
15978     // Example: from MVT::v2i32 to MVT::v4i32.
15979     SmallVector<SDValue, 16> Elts;
15980     for (unsigned i = 0, e = NumElts; i != e; ++i)
15981       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
15982                                  DAG.getIntPtrConstant(i)));
15983
15984     // Explicitly mark the extra elements as Undef.
15985     SDValue Undef = DAG.getUNDEF(SVT);
15986     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
15987       Elts.push_back(Undef);
15988
15989     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15990     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
15991     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
15992     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
15993                        DAG.getIntPtrConstant(0));
15994   }
15995
15996   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
15997          Subtarget->hasMMX() && "Unexpected custom BITCAST");
15998   assert((DstVT == MVT::i64 ||
15999           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16000          "Unexpected custom BITCAST");
16001   // i64 <=> MMX conversions are Legal.
16002   if (SrcVT==MVT::i64 && DstVT.isVector())
16003     return Op;
16004   if (DstVT==MVT::i64 && SrcVT.isVector())
16005     return Op;
16006   // MMX <=> MMX conversions are Legal.
16007   if (SrcVT.isVector() && DstVT.isVector())
16008     return Op;
16009   // All other conversions need to be expanded.
16010   return SDValue();
16011 }
16012
16013 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16014   SDNode *Node = Op.getNode();
16015   SDLoc dl(Node);
16016   EVT T = Node->getValueType(0);
16017   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16018                               DAG.getConstant(0, T), Node->getOperand(2));
16019   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16020                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16021                        Node->getOperand(0),
16022                        Node->getOperand(1), negOp,
16023                        cast<AtomicSDNode>(Node)->getMemOperand(),
16024                        cast<AtomicSDNode>(Node)->getOrdering(),
16025                        cast<AtomicSDNode>(Node)->getSynchScope());
16026 }
16027
16028 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16029   SDNode *Node = Op.getNode();
16030   SDLoc dl(Node);
16031   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16032
16033   // Convert seq_cst store -> xchg
16034   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16035   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16036   //        (The only way to get a 16-byte store is cmpxchg16b)
16037   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16038   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16039       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16040     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16041                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16042                                  Node->getOperand(0),
16043                                  Node->getOperand(1), Node->getOperand(2),
16044                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16045                                  cast<AtomicSDNode>(Node)->getOrdering(),
16046                                  cast<AtomicSDNode>(Node)->getSynchScope());
16047     return Swap.getValue(1);
16048   }
16049   // Other atomic stores have a simple pattern.
16050   return Op;
16051 }
16052
16053 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16054   EVT VT = Op.getNode()->getSimpleValueType(0);
16055
16056   // Let legalize expand this if it isn't a legal type yet.
16057   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16058     return SDValue();
16059
16060   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16061
16062   unsigned Opc;
16063   bool ExtraOp = false;
16064   switch (Op.getOpcode()) {
16065   default: llvm_unreachable("Invalid code");
16066   case ISD::ADDC: Opc = X86ISD::ADD; break;
16067   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16068   case ISD::SUBC: Opc = X86ISD::SUB; break;
16069   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16070   }
16071
16072   if (!ExtraOp)
16073     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16074                        Op.getOperand(1));
16075   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16076                      Op.getOperand(1), Op.getOperand(2));
16077 }
16078
16079 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16080                             SelectionDAG &DAG) {
16081   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16082
16083   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16084   // which returns the values as { float, float } (in XMM0) or
16085   // { double, double } (which is returned in XMM0, XMM1).
16086   SDLoc dl(Op);
16087   SDValue Arg = Op.getOperand(0);
16088   EVT ArgVT = Arg.getValueType();
16089   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16090
16091   TargetLowering::ArgListTy Args;
16092   TargetLowering::ArgListEntry Entry;
16093
16094   Entry.Node = Arg;
16095   Entry.Ty = ArgTy;
16096   Entry.isSExt = false;
16097   Entry.isZExt = false;
16098   Args.push_back(Entry);
16099
16100   bool isF64 = ArgVT == MVT::f64;
16101   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16102   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16103   // the results are returned via SRet in memory.
16104   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16105   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16106   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16107
16108   Type *RetTy = isF64
16109     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16110     : (Type*)VectorType::get(ArgTy, 4);
16111
16112   TargetLowering::CallLoweringInfo CLI(DAG);
16113   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16114     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16115
16116   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16117
16118   if (isF64)
16119     // Returned in xmm0 and xmm1.
16120     return CallResult.first;
16121
16122   // Returned in bits 0:31 and 32:64 xmm0.
16123   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16124                                CallResult.first, DAG.getIntPtrConstant(0));
16125   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16126                                CallResult.first, DAG.getIntPtrConstant(1));
16127   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16128   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16129 }
16130
16131 /// LowerOperation - Provide custom lowering hooks for some operations.
16132 ///
16133 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16134   switch (Op.getOpcode()) {
16135   default: llvm_unreachable("Should not custom lower this!");
16136   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16137   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16138   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16139     return LowerCMP_SWAP(Op, Subtarget, DAG);
16140   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16141   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16142   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16143   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16144   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16145   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16146   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16147   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16148   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16149   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16150   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16151   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16152   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16153   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16154   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16155   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16156   case ISD::SHL_PARTS:
16157   case ISD::SRA_PARTS:
16158   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16159   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16160   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16161   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16162   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16163   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16164   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16165   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16166   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16167   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16168   case ISD::FABS:               return LowerFABS(Op, DAG);
16169   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16170   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16171   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16172   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16173   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16174   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16175   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16176   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16177   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16178   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16179   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16180   case ISD::INTRINSIC_VOID:
16181   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16182   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16183   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16184   case ISD::FRAME_TO_ARGS_OFFSET:
16185                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16186   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16187   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16188   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16189   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16190   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16191   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16192   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16193   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16194   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16195   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16196   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16197   case ISD::UMUL_LOHI:
16198   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16199   case ISD::SRA:
16200   case ISD::SRL:
16201   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16202   case ISD::SADDO:
16203   case ISD::UADDO:
16204   case ISD::SSUBO:
16205   case ISD::USUBO:
16206   case ISD::SMULO:
16207   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16208   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16209   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16210   case ISD::ADDC:
16211   case ISD::ADDE:
16212   case ISD::SUBC:
16213   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16214   case ISD::ADD:                return LowerADD(Op, DAG);
16215   case ISD::SUB:                return LowerSUB(Op, DAG);
16216   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16217   }
16218 }
16219
16220 static void ReplaceATOMIC_LOAD(SDNode *Node,
16221                                SmallVectorImpl<SDValue> &Results,
16222                                SelectionDAG &DAG) {
16223   SDLoc dl(Node);
16224   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16225
16226   // Convert wide load -> cmpxchg8b/cmpxchg16b
16227   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16228   //        (The only way to get a 16-byte load is cmpxchg16b)
16229   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16230   SDValue Zero = DAG.getConstant(0, VT);
16231   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16232   SDValue Swap =
16233       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16234                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16235                            cast<AtomicSDNode>(Node)->getMemOperand(),
16236                            cast<AtomicSDNode>(Node)->getOrdering(),
16237                            cast<AtomicSDNode>(Node)->getOrdering(),
16238                            cast<AtomicSDNode>(Node)->getSynchScope());
16239   Results.push_back(Swap.getValue(0));
16240   Results.push_back(Swap.getValue(2));
16241 }
16242
16243 /// ReplaceNodeResults - Replace a node with an illegal result type
16244 /// with a new node built out of custom code.
16245 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16246                                            SmallVectorImpl<SDValue>&Results,
16247                                            SelectionDAG &DAG) const {
16248   SDLoc dl(N);
16249   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16250   switch (N->getOpcode()) {
16251   default:
16252     llvm_unreachable("Do not know how to custom type legalize this operation!");
16253   case ISD::SIGN_EXTEND_INREG:
16254   case ISD::ADDC:
16255   case ISD::ADDE:
16256   case ISD::SUBC:
16257   case ISD::SUBE:
16258     // We don't want to expand or promote these.
16259     return;
16260   case ISD::SDIV:
16261   case ISD::UDIV:
16262   case ISD::SREM:
16263   case ISD::UREM:
16264   case ISD::SDIVREM:
16265   case ISD::UDIVREM: {
16266     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16267     Results.push_back(V);
16268     return;
16269   }
16270   case ISD::FP_TO_SINT:
16271   case ISD::FP_TO_UINT: {
16272     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16273
16274     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16275       return;
16276
16277     std::pair<SDValue,SDValue> Vals =
16278         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16279     SDValue FIST = Vals.first, StackSlot = Vals.second;
16280     if (FIST.getNode()) {
16281       EVT VT = N->getValueType(0);
16282       // Return a load from the stack slot.
16283       if (StackSlot.getNode())
16284         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16285                                       MachinePointerInfo(),
16286                                       false, false, false, 0));
16287       else
16288         Results.push_back(FIST);
16289     }
16290     return;
16291   }
16292   case ISD::UINT_TO_FP: {
16293     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16294     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16295         N->getValueType(0) != MVT::v2f32)
16296       return;
16297     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16298                                  N->getOperand(0));
16299     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16300                                      MVT::f64);
16301     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16302     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16303                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16304     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16305     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16306     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16307     return;
16308   }
16309   case ISD::FP_ROUND: {
16310     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16311         return;
16312     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16313     Results.push_back(V);
16314     return;
16315   }
16316   case ISD::INTRINSIC_W_CHAIN: {
16317     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16318     switch (IntNo) {
16319     default : llvm_unreachable("Do not know how to custom type "
16320                                "legalize this intrinsic operation!");
16321     case Intrinsic::x86_rdtsc:
16322       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16323                                      Results);
16324     case Intrinsic::x86_rdtscp:
16325       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16326                                      Results);
16327     case Intrinsic::x86_rdpmc:
16328       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16329     }
16330   }
16331   case ISD::READCYCLECOUNTER: {
16332     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16333                                    Results);
16334   }
16335   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16336     EVT T = N->getValueType(0);
16337     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16338     bool Regs64bit = T == MVT::i128;
16339     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16340     SDValue cpInL, cpInH;
16341     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16342                         DAG.getConstant(0, HalfT));
16343     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16344                         DAG.getConstant(1, HalfT));
16345     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16346                              Regs64bit ? X86::RAX : X86::EAX,
16347                              cpInL, SDValue());
16348     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16349                              Regs64bit ? X86::RDX : X86::EDX,
16350                              cpInH, cpInL.getValue(1));
16351     SDValue swapInL, swapInH;
16352     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16353                           DAG.getConstant(0, HalfT));
16354     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16355                           DAG.getConstant(1, HalfT));
16356     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16357                                Regs64bit ? X86::RBX : X86::EBX,
16358                                swapInL, cpInH.getValue(1));
16359     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16360                                Regs64bit ? X86::RCX : X86::ECX,
16361                                swapInH, swapInL.getValue(1));
16362     SDValue Ops[] = { swapInH.getValue(0),
16363                       N->getOperand(1),
16364                       swapInH.getValue(1) };
16365     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16366     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16367     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16368                                   X86ISD::LCMPXCHG8_DAG;
16369     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16370     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16371                                         Regs64bit ? X86::RAX : X86::EAX,
16372                                         HalfT, Result.getValue(1));
16373     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16374                                         Regs64bit ? X86::RDX : X86::EDX,
16375                                         HalfT, cpOutL.getValue(2));
16376     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16377
16378     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16379                                         MVT::i32, cpOutH.getValue(2));
16380     SDValue Success =
16381         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16382                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16383     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16384
16385     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16386     Results.push_back(Success);
16387     Results.push_back(EFLAGS.getValue(1));
16388     return;
16389   }
16390   case ISD::ATOMIC_SWAP:
16391   case ISD::ATOMIC_LOAD_ADD:
16392   case ISD::ATOMIC_LOAD_SUB:
16393   case ISD::ATOMIC_LOAD_AND:
16394   case ISD::ATOMIC_LOAD_OR:
16395   case ISD::ATOMIC_LOAD_XOR:
16396   case ISD::ATOMIC_LOAD_NAND:
16397   case ISD::ATOMIC_LOAD_MIN:
16398   case ISD::ATOMIC_LOAD_MAX:
16399   case ISD::ATOMIC_LOAD_UMIN:
16400   case ISD::ATOMIC_LOAD_UMAX:
16401     // Delegate to generic TypeLegalization. Situations we can really handle
16402     // should have already been dealt with by X86AtomicExpand.cpp.
16403     break;
16404   case ISD::ATOMIC_LOAD: {
16405     ReplaceATOMIC_LOAD(N, Results, DAG);
16406     return;
16407   }
16408   case ISD::BITCAST: {
16409     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16410     EVT DstVT = N->getValueType(0);
16411     EVT SrcVT = N->getOperand(0)->getValueType(0);
16412
16413     if (SrcVT != MVT::f64 ||
16414         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16415       return;
16416
16417     unsigned NumElts = DstVT.getVectorNumElements();
16418     EVT SVT = DstVT.getVectorElementType();
16419     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16420     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16421                                    MVT::v2f64, N->getOperand(0));
16422     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16423
16424     if (ExperimentalVectorWideningLegalization) {
16425       // If we are legalizing vectors by widening, we already have the desired
16426       // legal vector type, just return it.
16427       Results.push_back(ToVecInt);
16428       return;
16429     }
16430
16431     SmallVector<SDValue, 8> Elts;
16432     for (unsigned i = 0, e = NumElts; i != e; ++i)
16433       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16434                                    ToVecInt, DAG.getIntPtrConstant(i)));
16435
16436     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16437   }
16438   }
16439 }
16440
16441 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16442   switch (Opcode) {
16443   default: return nullptr;
16444   case X86ISD::BSF:                return "X86ISD::BSF";
16445   case X86ISD::BSR:                return "X86ISD::BSR";
16446   case X86ISD::SHLD:               return "X86ISD::SHLD";
16447   case X86ISD::SHRD:               return "X86ISD::SHRD";
16448   case X86ISD::FAND:               return "X86ISD::FAND";
16449   case X86ISD::FANDN:              return "X86ISD::FANDN";
16450   case X86ISD::FOR:                return "X86ISD::FOR";
16451   case X86ISD::FXOR:               return "X86ISD::FXOR";
16452   case X86ISD::FSRL:               return "X86ISD::FSRL";
16453   case X86ISD::FILD:               return "X86ISD::FILD";
16454   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16455   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16456   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16457   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16458   case X86ISD::FLD:                return "X86ISD::FLD";
16459   case X86ISD::FST:                return "X86ISD::FST";
16460   case X86ISD::CALL:               return "X86ISD::CALL";
16461   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16462   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16463   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
16464   case X86ISD::BT:                 return "X86ISD::BT";
16465   case X86ISD::CMP:                return "X86ISD::CMP";
16466   case X86ISD::COMI:               return "X86ISD::COMI";
16467   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16468   case X86ISD::CMPM:               return "X86ISD::CMPM";
16469   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16470   case X86ISD::SETCC:              return "X86ISD::SETCC";
16471   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16472   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16473   case X86ISD::CMOV:               return "X86ISD::CMOV";
16474   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16475   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16476   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
16477   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
16478   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
16479   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
16480   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
16481   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
16482   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
16483   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
16484   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
16485   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
16486   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
16487   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
16488   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
16489   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
16490   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
16491   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
16492   case X86ISD::HADD:               return "X86ISD::HADD";
16493   case X86ISD::HSUB:               return "X86ISD::HSUB";
16494   case X86ISD::FHADD:              return "X86ISD::FHADD";
16495   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
16496   case X86ISD::UMAX:               return "X86ISD::UMAX";
16497   case X86ISD::UMIN:               return "X86ISD::UMIN";
16498   case X86ISD::SMAX:               return "X86ISD::SMAX";
16499   case X86ISD::SMIN:               return "X86ISD::SMIN";
16500   case X86ISD::FMAX:               return "X86ISD::FMAX";
16501   case X86ISD::FMIN:               return "X86ISD::FMIN";
16502   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
16503   case X86ISD::FMINC:              return "X86ISD::FMINC";
16504   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
16505   case X86ISD::FRCP:               return "X86ISD::FRCP";
16506   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
16507   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
16508   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
16509   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
16510   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
16511   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
16512   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
16513   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
16514   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
16515   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
16516   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
16517   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
16518   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
16519   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
16520   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
16521   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
16522   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
16523   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
16524   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
16525   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
16526   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
16527   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
16528   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
16529   case X86ISD::VSHL:               return "X86ISD::VSHL";
16530   case X86ISD::VSRL:               return "X86ISD::VSRL";
16531   case X86ISD::VSRA:               return "X86ISD::VSRA";
16532   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
16533   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
16534   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
16535   case X86ISD::CMPP:               return "X86ISD::CMPP";
16536   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
16537   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
16538   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
16539   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
16540   case X86ISD::ADD:                return "X86ISD::ADD";
16541   case X86ISD::SUB:                return "X86ISD::SUB";
16542   case X86ISD::ADC:                return "X86ISD::ADC";
16543   case X86ISD::SBB:                return "X86ISD::SBB";
16544   case X86ISD::SMUL:               return "X86ISD::SMUL";
16545   case X86ISD::UMUL:               return "X86ISD::UMUL";
16546   case X86ISD::INC:                return "X86ISD::INC";
16547   case X86ISD::DEC:                return "X86ISD::DEC";
16548   case X86ISD::OR:                 return "X86ISD::OR";
16549   case X86ISD::XOR:                return "X86ISD::XOR";
16550   case X86ISD::AND:                return "X86ISD::AND";
16551   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
16552   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
16553   case X86ISD::PTEST:              return "X86ISD::PTEST";
16554   case X86ISD::TESTP:              return "X86ISD::TESTP";
16555   case X86ISD::TESTM:              return "X86ISD::TESTM";
16556   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
16557   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
16558   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
16559   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
16560   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
16561   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
16562   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
16563   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
16564   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
16565   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
16566   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
16567   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
16568   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
16569   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
16570   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
16571   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
16572   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
16573   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
16574   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
16575   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
16576   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
16577   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
16578   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
16579   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
16580   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
16581   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
16582   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
16583   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
16584   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
16585   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
16586   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
16587   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
16588   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16589   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
16590   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
16591   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
16592   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
16593   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
16594   case X86ISD::SAHF:               return "X86ISD::SAHF";
16595   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
16596   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
16597   case X86ISD::FMADD:              return "X86ISD::FMADD";
16598   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
16599   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
16600   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
16601   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
16602   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
16603   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
16604   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
16605   case X86ISD::XTEST:              return "X86ISD::XTEST";
16606   }
16607 }
16608
16609 // isLegalAddressingMode - Return true if the addressing mode represented
16610 // by AM is legal for this target, for a load/store of the specified type.
16611 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16612                                               Type *Ty) const {
16613   // X86 supports extremely general addressing modes.
16614   CodeModel::Model M = getTargetMachine().getCodeModel();
16615   Reloc::Model R = getTargetMachine().getRelocationModel();
16616
16617   // X86 allows a sign-extended 32-bit immediate field as a displacement.
16618   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16619     return false;
16620
16621   if (AM.BaseGV) {
16622     unsigned GVFlags =
16623       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16624
16625     // If a reference to this global requires an extra load, we can't fold it.
16626     if (isGlobalStubReference(GVFlags))
16627       return false;
16628
16629     // If BaseGV requires a register for the PIC base, we cannot also have a
16630     // BaseReg specified.
16631     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16632       return false;
16633
16634     // If lower 4G is not available, then we must use rip-relative addressing.
16635     if ((M != CodeModel::Small || R != Reloc::Static) &&
16636         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16637       return false;
16638   }
16639
16640   switch (AM.Scale) {
16641   case 0:
16642   case 1:
16643   case 2:
16644   case 4:
16645   case 8:
16646     // These scales always work.
16647     break;
16648   case 3:
16649   case 5:
16650   case 9:
16651     // These scales are formed with basereg+scalereg.  Only accept if there is
16652     // no basereg yet.
16653     if (AM.HasBaseReg)
16654       return false;
16655     break;
16656   default:  // Other stuff never works.
16657     return false;
16658   }
16659
16660   return true;
16661 }
16662
16663 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16664   unsigned Bits = Ty->getScalarSizeInBits();
16665
16666   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16667   // particularly cheaper than those without.
16668   if (Bits == 8)
16669     return false;
16670
16671   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16672   // variable shifts just as cheap as scalar ones.
16673   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16674     return false;
16675
16676   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16677   // fully general vector.
16678   return true;
16679 }
16680
16681 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16682   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16683     return false;
16684   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16685   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16686   return NumBits1 > NumBits2;
16687 }
16688
16689 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16690   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16691     return false;
16692
16693   if (!isTypeLegal(EVT::getEVT(Ty1)))
16694     return false;
16695
16696   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16697
16698   // Assuming the caller doesn't have a zeroext or signext return parameter,
16699   // truncation all the way down to i1 is valid.
16700   return true;
16701 }
16702
16703 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16704   return isInt<32>(Imm);
16705 }
16706
16707 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16708   // Can also use sub to handle negated immediates.
16709   return isInt<32>(Imm);
16710 }
16711
16712 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16713   if (!VT1.isInteger() || !VT2.isInteger())
16714     return false;
16715   unsigned NumBits1 = VT1.getSizeInBits();
16716   unsigned NumBits2 = VT2.getSizeInBits();
16717   return NumBits1 > NumBits2;
16718 }
16719
16720 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16721   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16722   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16723 }
16724
16725 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16726   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16727   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16728 }
16729
16730 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16731   EVT VT1 = Val.getValueType();
16732   if (isZExtFree(VT1, VT2))
16733     return true;
16734
16735   if (Val.getOpcode() != ISD::LOAD)
16736     return false;
16737
16738   if (!VT1.isSimple() || !VT1.isInteger() ||
16739       !VT2.isSimple() || !VT2.isInteger())
16740     return false;
16741
16742   switch (VT1.getSimpleVT().SimpleTy) {
16743   default: break;
16744   case MVT::i8:
16745   case MVT::i16:
16746   case MVT::i32:
16747     // X86 has 8, 16, and 32-bit zero-extending loads.
16748     return true;
16749   }
16750
16751   return false;
16752 }
16753
16754 bool
16755 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16756   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16757     return false;
16758
16759   VT = VT.getScalarType();
16760
16761   if (!VT.isSimple())
16762     return false;
16763
16764   switch (VT.getSimpleVT().SimpleTy) {
16765   case MVT::f32:
16766   case MVT::f64:
16767     return true;
16768   default:
16769     break;
16770   }
16771
16772   return false;
16773 }
16774
16775 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16776   // i16 instructions are longer (0x66 prefix) and potentially slower.
16777   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16778 }
16779
16780 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16781 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16782 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16783 /// are assumed to be legal.
16784 bool
16785 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16786                                       EVT VT) const {
16787   if (!VT.isSimple())
16788     return false;
16789
16790   MVT SVT = VT.getSimpleVT();
16791
16792   // Very little shuffling can be done for 64-bit vectors right now.
16793   if (VT.getSizeInBits() == 64)
16794     return false;
16795
16796   // If this is a single-input shuffle with no 128 bit lane crossings we can
16797   // lower it into pshufb.
16798   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16799       (SVT.is256BitVector() && Subtarget->hasInt256())) {
16800     bool isLegal = true;
16801     for (unsigned I = 0, E = M.size(); I != E; ++I) {
16802       if (M[I] >= (int)SVT.getVectorNumElements() ||
16803           ShuffleCrosses128bitLane(SVT, I, M[I])) {
16804         isLegal = false;
16805         break;
16806       }
16807     }
16808     if (isLegal)
16809       return true;
16810   }
16811
16812   // FIXME: blends, shifts.
16813   return (SVT.getVectorNumElements() == 2 ||
16814           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16815           isMOVLMask(M, SVT) ||
16816           isSHUFPMask(M, SVT) ||
16817           isPSHUFDMask(M, SVT) ||
16818           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16819           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16820           isPALIGNRMask(M, SVT, Subtarget) ||
16821           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16822           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16823           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16824           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16825           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16826 }
16827
16828 bool
16829 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16830                                           EVT VT) const {
16831   if (!VT.isSimple())
16832     return false;
16833
16834   MVT SVT = VT.getSimpleVT();
16835   unsigned NumElts = SVT.getVectorNumElements();
16836   // FIXME: This collection of masks seems suspect.
16837   if (NumElts == 2)
16838     return true;
16839   if (NumElts == 4 && SVT.is128BitVector()) {
16840     return (isMOVLMask(Mask, SVT)  ||
16841             isCommutedMOVLMask(Mask, SVT, true) ||
16842             isSHUFPMask(Mask, SVT) ||
16843             isSHUFPMask(Mask, SVT, /* Commuted */ true));
16844   }
16845   return false;
16846 }
16847
16848 //===----------------------------------------------------------------------===//
16849 //                           X86 Scheduler Hooks
16850 //===----------------------------------------------------------------------===//
16851
16852 /// Utility function to emit xbegin specifying the start of an RTM region.
16853 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16854                                      const TargetInstrInfo *TII) {
16855   DebugLoc DL = MI->getDebugLoc();
16856
16857   const BasicBlock *BB = MBB->getBasicBlock();
16858   MachineFunction::iterator I = MBB;
16859   ++I;
16860
16861   // For the v = xbegin(), we generate
16862   //
16863   // thisMBB:
16864   //  xbegin sinkMBB
16865   //
16866   // mainMBB:
16867   //  eax = -1
16868   //
16869   // sinkMBB:
16870   //  v = eax
16871
16872   MachineBasicBlock *thisMBB = MBB;
16873   MachineFunction *MF = MBB->getParent();
16874   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16875   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16876   MF->insert(I, mainMBB);
16877   MF->insert(I, sinkMBB);
16878
16879   // Transfer the remainder of BB and its successor edges to sinkMBB.
16880   sinkMBB->splice(sinkMBB->begin(), MBB,
16881                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16882   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16883
16884   // thisMBB:
16885   //  xbegin sinkMBB
16886   //  # fallthrough to mainMBB
16887   //  # abortion to sinkMBB
16888   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16889   thisMBB->addSuccessor(mainMBB);
16890   thisMBB->addSuccessor(sinkMBB);
16891
16892   // mainMBB:
16893   //  EAX = -1
16894   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16895   mainMBB->addSuccessor(sinkMBB);
16896
16897   // sinkMBB:
16898   // EAX is live into the sinkMBB
16899   sinkMBB->addLiveIn(X86::EAX);
16900   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16901           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16902     .addReg(X86::EAX);
16903
16904   MI->eraseFromParent();
16905   return sinkMBB;
16906 }
16907
16908 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16909 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16910 // in the .td file.
16911 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16912                                        const TargetInstrInfo *TII) {
16913   unsigned Opc;
16914   switch (MI->getOpcode()) {
16915   default: llvm_unreachable("illegal opcode!");
16916   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
16917   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16918   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
16919   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16920   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
16921   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16922   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
16923   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16924   }
16925
16926   DebugLoc dl = MI->getDebugLoc();
16927   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16928
16929   unsigned NumArgs = MI->getNumOperands();
16930   for (unsigned i = 1; i < NumArgs; ++i) {
16931     MachineOperand &Op = MI->getOperand(i);
16932     if (!(Op.isReg() && Op.isImplicit()))
16933       MIB.addOperand(Op);
16934   }
16935   if (MI->hasOneMemOperand())
16936     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16937
16938   BuildMI(*BB, MI, dl,
16939     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16940     .addReg(X86::XMM0);
16941
16942   MI->eraseFromParent();
16943   return BB;
16944 }
16945
16946 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16947 // defs in an instruction pattern
16948 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16949                                        const TargetInstrInfo *TII) {
16950   unsigned Opc;
16951   switch (MI->getOpcode()) {
16952   default: llvm_unreachable("illegal opcode!");
16953   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
16954   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16955   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
16956   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16957   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
16958   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16959   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
16960   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16961   }
16962
16963   DebugLoc dl = MI->getDebugLoc();
16964   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16965
16966   unsigned NumArgs = MI->getNumOperands(); // remove the results
16967   for (unsigned i = 1; i < NumArgs; ++i) {
16968     MachineOperand &Op = MI->getOperand(i);
16969     if (!(Op.isReg() && Op.isImplicit()))
16970       MIB.addOperand(Op);
16971   }
16972   if (MI->hasOneMemOperand())
16973     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16974
16975   BuildMI(*BB, MI, dl,
16976     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16977     .addReg(X86::ECX);
16978
16979   MI->eraseFromParent();
16980   return BB;
16981 }
16982
16983 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16984                                        const TargetInstrInfo *TII,
16985                                        const X86Subtarget* Subtarget) {
16986   DebugLoc dl = MI->getDebugLoc();
16987
16988   // Address into RAX/EAX, other two args into ECX, EDX.
16989   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16990   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16991   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16992   for (int i = 0; i < X86::AddrNumOperands; ++i)
16993     MIB.addOperand(MI->getOperand(i));
16994
16995   unsigned ValOps = X86::AddrNumOperands;
16996   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16997     .addReg(MI->getOperand(ValOps).getReg());
16998   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16999     .addReg(MI->getOperand(ValOps+1).getReg());
17000
17001   // The instruction doesn't actually take any operands though.
17002   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17003
17004   MI->eraseFromParent(); // The pseudo is gone now.
17005   return BB;
17006 }
17007
17008 MachineBasicBlock *
17009 X86TargetLowering::EmitVAARG64WithCustomInserter(
17010                    MachineInstr *MI,
17011                    MachineBasicBlock *MBB) const {
17012   // Emit va_arg instruction on X86-64.
17013
17014   // Operands to this pseudo-instruction:
17015   // 0  ) Output        : destination address (reg)
17016   // 1-5) Input         : va_list address (addr, i64mem)
17017   // 6  ) ArgSize       : Size (in bytes) of vararg type
17018   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17019   // 8  ) Align         : Alignment of type
17020   // 9  ) EFLAGS (implicit-def)
17021
17022   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17023   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17024
17025   unsigned DestReg = MI->getOperand(0).getReg();
17026   MachineOperand &Base = MI->getOperand(1);
17027   MachineOperand &Scale = MI->getOperand(2);
17028   MachineOperand &Index = MI->getOperand(3);
17029   MachineOperand &Disp = MI->getOperand(4);
17030   MachineOperand &Segment = MI->getOperand(5);
17031   unsigned ArgSize = MI->getOperand(6).getImm();
17032   unsigned ArgMode = MI->getOperand(7).getImm();
17033   unsigned Align = MI->getOperand(8).getImm();
17034
17035   // Memory Reference
17036   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17037   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17038   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17039
17040   // Machine Information
17041   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17042   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17043   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17044   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17045   DebugLoc DL = MI->getDebugLoc();
17046
17047   // struct va_list {
17048   //   i32   gp_offset
17049   //   i32   fp_offset
17050   //   i64   overflow_area (address)
17051   //   i64   reg_save_area (address)
17052   // }
17053   // sizeof(va_list) = 24
17054   // alignment(va_list) = 8
17055
17056   unsigned TotalNumIntRegs = 6;
17057   unsigned TotalNumXMMRegs = 8;
17058   bool UseGPOffset = (ArgMode == 1);
17059   bool UseFPOffset = (ArgMode == 2);
17060   unsigned MaxOffset = TotalNumIntRegs * 8 +
17061                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17062
17063   /* Align ArgSize to a multiple of 8 */
17064   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17065   bool NeedsAlign = (Align > 8);
17066
17067   MachineBasicBlock *thisMBB = MBB;
17068   MachineBasicBlock *overflowMBB;
17069   MachineBasicBlock *offsetMBB;
17070   MachineBasicBlock *endMBB;
17071
17072   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17073   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17074   unsigned OffsetReg = 0;
17075
17076   if (!UseGPOffset && !UseFPOffset) {
17077     // If we only pull from the overflow region, we don't create a branch.
17078     // We don't need to alter control flow.
17079     OffsetDestReg = 0; // unused
17080     OverflowDestReg = DestReg;
17081
17082     offsetMBB = nullptr;
17083     overflowMBB = thisMBB;
17084     endMBB = thisMBB;
17085   } else {
17086     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17087     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17088     // If not, pull from overflow_area. (branch to overflowMBB)
17089     //
17090     //       thisMBB
17091     //         |     .
17092     //         |        .
17093     //     offsetMBB   overflowMBB
17094     //         |        .
17095     //         |     .
17096     //        endMBB
17097
17098     // Registers for the PHI in endMBB
17099     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17100     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17101
17102     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17103     MachineFunction *MF = MBB->getParent();
17104     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17105     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17106     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17107
17108     MachineFunction::iterator MBBIter = MBB;
17109     ++MBBIter;
17110
17111     // Insert the new basic blocks
17112     MF->insert(MBBIter, offsetMBB);
17113     MF->insert(MBBIter, overflowMBB);
17114     MF->insert(MBBIter, endMBB);
17115
17116     // Transfer the remainder of MBB and its successor edges to endMBB.
17117     endMBB->splice(endMBB->begin(), thisMBB,
17118                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17119     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17120
17121     // Make offsetMBB and overflowMBB successors of thisMBB
17122     thisMBB->addSuccessor(offsetMBB);
17123     thisMBB->addSuccessor(overflowMBB);
17124
17125     // endMBB is a successor of both offsetMBB and overflowMBB
17126     offsetMBB->addSuccessor(endMBB);
17127     overflowMBB->addSuccessor(endMBB);
17128
17129     // Load the offset value into a register
17130     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17131     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17132       .addOperand(Base)
17133       .addOperand(Scale)
17134       .addOperand(Index)
17135       .addDisp(Disp, UseFPOffset ? 4 : 0)
17136       .addOperand(Segment)
17137       .setMemRefs(MMOBegin, MMOEnd);
17138
17139     // Check if there is enough room left to pull this argument.
17140     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17141       .addReg(OffsetReg)
17142       .addImm(MaxOffset + 8 - ArgSizeA8);
17143
17144     // Branch to "overflowMBB" if offset >= max
17145     // Fall through to "offsetMBB" otherwise
17146     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17147       .addMBB(overflowMBB);
17148   }
17149
17150   // In offsetMBB, emit code to use the reg_save_area.
17151   if (offsetMBB) {
17152     assert(OffsetReg != 0);
17153
17154     // Read the reg_save_area address.
17155     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17156     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17157       .addOperand(Base)
17158       .addOperand(Scale)
17159       .addOperand(Index)
17160       .addDisp(Disp, 16)
17161       .addOperand(Segment)
17162       .setMemRefs(MMOBegin, MMOEnd);
17163
17164     // Zero-extend the offset
17165     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17166       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17167         .addImm(0)
17168         .addReg(OffsetReg)
17169         .addImm(X86::sub_32bit);
17170
17171     // Add the offset to the reg_save_area to get the final address.
17172     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17173       .addReg(OffsetReg64)
17174       .addReg(RegSaveReg);
17175
17176     // Compute the offset for the next argument
17177     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17178     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17179       .addReg(OffsetReg)
17180       .addImm(UseFPOffset ? 16 : 8);
17181
17182     // Store it back into the va_list.
17183     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17184       .addOperand(Base)
17185       .addOperand(Scale)
17186       .addOperand(Index)
17187       .addDisp(Disp, UseFPOffset ? 4 : 0)
17188       .addOperand(Segment)
17189       .addReg(NextOffsetReg)
17190       .setMemRefs(MMOBegin, MMOEnd);
17191
17192     // Jump to endMBB
17193     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17194       .addMBB(endMBB);
17195   }
17196
17197   //
17198   // Emit code to use overflow area
17199   //
17200
17201   // Load the overflow_area address into a register.
17202   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17203   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17204     .addOperand(Base)
17205     .addOperand(Scale)
17206     .addOperand(Index)
17207     .addDisp(Disp, 8)
17208     .addOperand(Segment)
17209     .setMemRefs(MMOBegin, MMOEnd);
17210
17211   // If we need to align it, do so. Otherwise, just copy the address
17212   // to OverflowDestReg.
17213   if (NeedsAlign) {
17214     // Align the overflow address
17215     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17216     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17217
17218     // aligned_addr = (addr + (align-1)) & ~(align-1)
17219     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17220       .addReg(OverflowAddrReg)
17221       .addImm(Align-1);
17222
17223     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17224       .addReg(TmpReg)
17225       .addImm(~(uint64_t)(Align-1));
17226   } else {
17227     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17228       .addReg(OverflowAddrReg);
17229   }
17230
17231   // Compute the next overflow address after this argument.
17232   // (the overflow address should be kept 8-byte aligned)
17233   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17234   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17235     .addReg(OverflowDestReg)
17236     .addImm(ArgSizeA8);
17237
17238   // Store the new overflow address.
17239   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17240     .addOperand(Base)
17241     .addOperand(Scale)
17242     .addOperand(Index)
17243     .addDisp(Disp, 8)
17244     .addOperand(Segment)
17245     .addReg(NextAddrReg)
17246     .setMemRefs(MMOBegin, MMOEnd);
17247
17248   // If we branched, emit the PHI to the front of endMBB.
17249   if (offsetMBB) {
17250     BuildMI(*endMBB, endMBB->begin(), DL,
17251             TII->get(X86::PHI), DestReg)
17252       .addReg(OffsetDestReg).addMBB(offsetMBB)
17253       .addReg(OverflowDestReg).addMBB(overflowMBB);
17254   }
17255
17256   // Erase the pseudo instruction
17257   MI->eraseFromParent();
17258
17259   return endMBB;
17260 }
17261
17262 MachineBasicBlock *
17263 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17264                                                  MachineInstr *MI,
17265                                                  MachineBasicBlock *MBB) const {
17266   // Emit code to save XMM registers to the stack. The ABI says that the
17267   // number of registers to save is given in %al, so it's theoretically
17268   // possible to do an indirect jump trick to avoid saving all of them,
17269   // however this code takes a simpler approach and just executes all
17270   // of the stores if %al is non-zero. It's less code, and it's probably
17271   // easier on the hardware branch predictor, and stores aren't all that
17272   // expensive anyway.
17273
17274   // Create the new basic blocks. One block contains all the XMM stores,
17275   // and one block is the final destination regardless of whether any
17276   // stores were performed.
17277   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17278   MachineFunction *F = MBB->getParent();
17279   MachineFunction::iterator MBBIter = MBB;
17280   ++MBBIter;
17281   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17282   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17283   F->insert(MBBIter, XMMSaveMBB);
17284   F->insert(MBBIter, EndMBB);
17285
17286   // Transfer the remainder of MBB and its successor edges to EndMBB.
17287   EndMBB->splice(EndMBB->begin(), MBB,
17288                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17289   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17290
17291   // The original block will now fall through to the XMM save block.
17292   MBB->addSuccessor(XMMSaveMBB);
17293   // The XMMSaveMBB will fall through to the end block.
17294   XMMSaveMBB->addSuccessor(EndMBB);
17295
17296   // Now add the instructions.
17297   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17298   DebugLoc DL = MI->getDebugLoc();
17299
17300   unsigned CountReg = MI->getOperand(0).getReg();
17301   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17302   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17303
17304   if (!Subtarget->isTargetWin64()) {
17305     // If %al is 0, branch around the XMM save block.
17306     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17307     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17308     MBB->addSuccessor(EndMBB);
17309   }
17310
17311   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17312   // that was just emitted, but clearly shouldn't be "saved".
17313   assert((MI->getNumOperands() <= 3 ||
17314           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17315           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17316          && "Expected last argument to be EFLAGS");
17317   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17318   // In the XMM save block, save all the XMM argument registers.
17319   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17320     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17321     MachineMemOperand *MMO =
17322       F->getMachineMemOperand(
17323           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17324         MachineMemOperand::MOStore,
17325         /*Size=*/16, /*Align=*/16);
17326     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17327       .addFrameIndex(RegSaveFrameIndex)
17328       .addImm(/*Scale=*/1)
17329       .addReg(/*IndexReg=*/0)
17330       .addImm(/*Disp=*/Offset)
17331       .addReg(/*Segment=*/0)
17332       .addReg(MI->getOperand(i).getReg())
17333       .addMemOperand(MMO);
17334   }
17335
17336   MI->eraseFromParent();   // The pseudo instruction is gone now.
17337
17338   return EndMBB;
17339 }
17340
17341 // The EFLAGS operand of SelectItr might be missing a kill marker
17342 // because there were multiple uses of EFLAGS, and ISel didn't know
17343 // which to mark. Figure out whether SelectItr should have had a
17344 // kill marker, and set it if it should. Returns the correct kill
17345 // marker value.
17346 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17347                                      MachineBasicBlock* BB,
17348                                      const TargetRegisterInfo* TRI) {
17349   // Scan forward through BB for a use/def of EFLAGS.
17350   MachineBasicBlock::iterator miI(std::next(SelectItr));
17351   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17352     const MachineInstr& mi = *miI;
17353     if (mi.readsRegister(X86::EFLAGS))
17354       return false;
17355     if (mi.definesRegister(X86::EFLAGS))
17356       break; // Should have kill-flag - update below.
17357   }
17358
17359   // If we hit the end of the block, check whether EFLAGS is live into a
17360   // successor.
17361   if (miI == BB->end()) {
17362     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17363                                           sEnd = BB->succ_end();
17364          sItr != sEnd; ++sItr) {
17365       MachineBasicBlock* succ = *sItr;
17366       if (succ->isLiveIn(X86::EFLAGS))
17367         return false;
17368     }
17369   }
17370
17371   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17372   // out. SelectMI should have a kill flag on EFLAGS.
17373   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17374   return true;
17375 }
17376
17377 MachineBasicBlock *
17378 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17379                                      MachineBasicBlock *BB) const {
17380   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17381   DebugLoc DL = MI->getDebugLoc();
17382
17383   // To "insert" a SELECT_CC instruction, we actually have to insert the
17384   // diamond control-flow pattern.  The incoming instruction knows the
17385   // destination vreg to set, the condition code register to branch on, the
17386   // true/false values to select between, and a branch opcode to use.
17387   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17388   MachineFunction::iterator It = BB;
17389   ++It;
17390
17391   //  thisMBB:
17392   //  ...
17393   //   TrueVal = ...
17394   //   cmpTY ccX, r1, r2
17395   //   bCC copy1MBB
17396   //   fallthrough --> copy0MBB
17397   MachineBasicBlock *thisMBB = BB;
17398   MachineFunction *F = BB->getParent();
17399   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17400   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17401   F->insert(It, copy0MBB);
17402   F->insert(It, sinkMBB);
17403
17404   // If the EFLAGS register isn't dead in the terminator, then claim that it's
17405   // live into the sink and copy blocks.
17406   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17407   if (!MI->killsRegister(X86::EFLAGS) &&
17408       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17409     copy0MBB->addLiveIn(X86::EFLAGS);
17410     sinkMBB->addLiveIn(X86::EFLAGS);
17411   }
17412
17413   // Transfer the remainder of BB and its successor edges to sinkMBB.
17414   sinkMBB->splice(sinkMBB->begin(), BB,
17415                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
17416   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17417
17418   // Add the true and fallthrough blocks as its successors.
17419   BB->addSuccessor(copy0MBB);
17420   BB->addSuccessor(sinkMBB);
17421
17422   // Create the conditional branch instruction.
17423   unsigned Opc =
17424     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17425   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17426
17427   //  copy0MBB:
17428   //   %FalseValue = ...
17429   //   # fallthrough to sinkMBB
17430   copy0MBB->addSuccessor(sinkMBB);
17431
17432   //  sinkMBB:
17433   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17434   //  ...
17435   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17436           TII->get(X86::PHI), MI->getOperand(0).getReg())
17437     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17438     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17439
17440   MI->eraseFromParent();   // The pseudo instruction is gone now.
17441   return sinkMBB;
17442 }
17443
17444 MachineBasicBlock *
17445 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17446                                         bool Is64Bit) const {
17447   MachineFunction *MF = BB->getParent();
17448   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17449   DebugLoc DL = MI->getDebugLoc();
17450   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17451
17452   assert(MF->shouldSplitStack());
17453
17454   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17455   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17456
17457   // BB:
17458   //  ... [Till the alloca]
17459   // If stacklet is not large enough, jump to mallocMBB
17460   //
17461   // bumpMBB:
17462   //  Allocate by subtracting from RSP
17463   //  Jump to continueMBB
17464   //
17465   // mallocMBB:
17466   //  Allocate by call to runtime
17467   //
17468   // continueMBB:
17469   //  ...
17470   //  [rest of original BB]
17471   //
17472
17473   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17474   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17475   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17476
17477   MachineRegisterInfo &MRI = MF->getRegInfo();
17478   const TargetRegisterClass *AddrRegClass =
17479     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17480
17481   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17482     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17483     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17484     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17485     sizeVReg = MI->getOperand(1).getReg(),
17486     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17487
17488   MachineFunction::iterator MBBIter = BB;
17489   ++MBBIter;
17490
17491   MF->insert(MBBIter, bumpMBB);
17492   MF->insert(MBBIter, mallocMBB);
17493   MF->insert(MBBIter, continueMBB);
17494
17495   continueMBB->splice(continueMBB->begin(), BB,
17496                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
17497   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17498
17499   // Add code to the main basic block to check if the stack limit has been hit,
17500   // and if so, jump to mallocMBB otherwise to bumpMBB.
17501   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17502   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17503     .addReg(tmpSPVReg).addReg(sizeVReg);
17504   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17505     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17506     .addReg(SPLimitVReg);
17507   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17508
17509   // bumpMBB simply decreases the stack pointer, since we know the current
17510   // stacklet has enough space.
17511   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17512     .addReg(SPLimitVReg);
17513   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17514     .addReg(SPLimitVReg);
17515   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17516
17517   // Calls into a routine in libgcc to allocate more space from the heap.
17518   const uint32_t *RegMask =
17519     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17520   if (Is64Bit) {
17521     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17522       .addReg(sizeVReg);
17523     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17524       .addExternalSymbol("__morestack_allocate_stack_space")
17525       .addRegMask(RegMask)
17526       .addReg(X86::RDI, RegState::Implicit)
17527       .addReg(X86::RAX, RegState::ImplicitDefine);
17528   } else {
17529     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17530       .addImm(12);
17531     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17532     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17533       .addExternalSymbol("__morestack_allocate_stack_space")
17534       .addRegMask(RegMask)
17535       .addReg(X86::EAX, RegState::ImplicitDefine);
17536   }
17537
17538   if (!Is64Bit)
17539     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17540       .addImm(16);
17541
17542   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17543     .addReg(Is64Bit ? X86::RAX : X86::EAX);
17544   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17545
17546   // Set up the CFG correctly.
17547   BB->addSuccessor(bumpMBB);
17548   BB->addSuccessor(mallocMBB);
17549   mallocMBB->addSuccessor(continueMBB);
17550   bumpMBB->addSuccessor(continueMBB);
17551
17552   // Take care of the PHI nodes.
17553   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17554           MI->getOperand(0).getReg())
17555     .addReg(mallocPtrVReg).addMBB(mallocMBB)
17556     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17557
17558   // Delete the original pseudo instruction.
17559   MI->eraseFromParent();
17560
17561   // And we're done.
17562   return continueMBB;
17563 }
17564
17565 MachineBasicBlock *
17566 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17567                                         MachineBasicBlock *BB) const {
17568   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17569   DebugLoc DL = MI->getDebugLoc();
17570
17571   assert(!Subtarget->isTargetMacho());
17572
17573   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
17574   // non-trivial part is impdef of ESP.
17575
17576   if (Subtarget->isTargetWin64()) {
17577     if (Subtarget->isTargetCygMing()) {
17578       // ___chkstk(Mingw64):
17579       // Clobbers R10, R11, RAX and EFLAGS.
17580       // Updates RSP.
17581       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17582         .addExternalSymbol("___chkstk")
17583         .addReg(X86::RAX, RegState::Implicit)
17584         .addReg(X86::RSP, RegState::Implicit)
17585         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17586         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17587         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17588     } else {
17589       // __chkstk(MSVCRT): does not update stack pointer.
17590       // Clobbers R10, R11 and EFLAGS.
17591       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17592         .addExternalSymbol("__chkstk")
17593         .addReg(X86::RAX, RegState::Implicit)
17594         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17595       // RAX has the offset to be subtracted from RSP.
17596       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17597         .addReg(X86::RSP)
17598         .addReg(X86::RAX);
17599     }
17600   } else {
17601     const char *StackProbeSymbol =
17602       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17603
17604     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17605       .addExternalSymbol(StackProbeSymbol)
17606       .addReg(X86::EAX, RegState::Implicit)
17607       .addReg(X86::ESP, RegState::Implicit)
17608       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17609       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17610       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17611   }
17612
17613   MI->eraseFromParent();   // The pseudo instruction is gone now.
17614   return BB;
17615 }
17616
17617 MachineBasicBlock *
17618 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17619                                       MachineBasicBlock *BB) const {
17620   // This is pretty easy.  We're taking the value that we received from
17621   // our load from the relocation, sticking it in either RDI (x86-64)
17622   // or EAX and doing an indirect call.  The return value will then
17623   // be in the normal return register.
17624   MachineFunction *F = BB->getParent();
17625   const X86InstrInfo *TII
17626     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17627   DebugLoc DL = MI->getDebugLoc();
17628
17629   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17630   assert(MI->getOperand(3).isGlobal() && "This should be a global");
17631
17632   // Get a register mask for the lowered call.
17633   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17634   // proper register mask.
17635   const uint32_t *RegMask =
17636     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17637   if (Subtarget->is64Bit()) {
17638     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17639                                       TII->get(X86::MOV64rm), X86::RDI)
17640     .addReg(X86::RIP)
17641     .addImm(0).addReg(0)
17642     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17643                       MI->getOperand(3).getTargetFlags())
17644     .addReg(0);
17645     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17646     addDirectMem(MIB, X86::RDI);
17647     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17648   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17649     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17650                                       TII->get(X86::MOV32rm), X86::EAX)
17651     .addReg(0)
17652     .addImm(0).addReg(0)
17653     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17654                       MI->getOperand(3).getTargetFlags())
17655     .addReg(0);
17656     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17657     addDirectMem(MIB, X86::EAX);
17658     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17659   } else {
17660     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17661                                       TII->get(X86::MOV32rm), X86::EAX)
17662     .addReg(TII->getGlobalBaseReg(F))
17663     .addImm(0).addReg(0)
17664     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17665                       MI->getOperand(3).getTargetFlags())
17666     .addReg(0);
17667     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17668     addDirectMem(MIB, X86::EAX);
17669     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17670   }
17671
17672   MI->eraseFromParent(); // The pseudo instruction is gone now.
17673   return BB;
17674 }
17675
17676 MachineBasicBlock *
17677 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17678                                     MachineBasicBlock *MBB) const {
17679   DebugLoc DL = MI->getDebugLoc();
17680   MachineFunction *MF = MBB->getParent();
17681   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17682   MachineRegisterInfo &MRI = MF->getRegInfo();
17683
17684   const BasicBlock *BB = MBB->getBasicBlock();
17685   MachineFunction::iterator I = MBB;
17686   ++I;
17687
17688   // Memory Reference
17689   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17690   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17691
17692   unsigned DstReg;
17693   unsigned MemOpndSlot = 0;
17694
17695   unsigned CurOp = 0;
17696
17697   DstReg = MI->getOperand(CurOp++).getReg();
17698   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17699   assert(RC->hasType(MVT::i32) && "Invalid destination!");
17700   unsigned mainDstReg = MRI.createVirtualRegister(RC);
17701   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17702
17703   MemOpndSlot = CurOp;
17704
17705   MVT PVT = getPointerTy();
17706   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17707          "Invalid Pointer Size!");
17708
17709   // For v = setjmp(buf), we generate
17710   //
17711   // thisMBB:
17712   //  buf[LabelOffset] = restoreMBB
17713   //  SjLjSetup restoreMBB
17714   //
17715   // mainMBB:
17716   //  v_main = 0
17717   //
17718   // sinkMBB:
17719   //  v = phi(main, restore)
17720   //
17721   // restoreMBB:
17722   //  v_restore = 1
17723
17724   MachineBasicBlock *thisMBB = MBB;
17725   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17726   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17727   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17728   MF->insert(I, mainMBB);
17729   MF->insert(I, sinkMBB);
17730   MF->push_back(restoreMBB);
17731
17732   MachineInstrBuilder MIB;
17733
17734   // Transfer the remainder of BB and its successor edges to sinkMBB.
17735   sinkMBB->splice(sinkMBB->begin(), MBB,
17736                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17737   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17738
17739   // thisMBB:
17740   unsigned PtrStoreOpc = 0;
17741   unsigned LabelReg = 0;
17742   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17743   Reloc::Model RM = MF->getTarget().getRelocationModel();
17744   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17745                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17746
17747   // Prepare IP either in reg or imm.
17748   if (!UseImmLabel) {
17749     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17750     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17751     LabelReg = MRI.createVirtualRegister(PtrRC);
17752     if (Subtarget->is64Bit()) {
17753       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17754               .addReg(X86::RIP)
17755               .addImm(0)
17756               .addReg(0)
17757               .addMBB(restoreMBB)
17758               .addReg(0);
17759     } else {
17760       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17761       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17762               .addReg(XII->getGlobalBaseReg(MF))
17763               .addImm(0)
17764               .addReg(0)
17765               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17766               .addReg(0);
17767     }
17768   } else
17769     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17770   // Store IP
17771   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17772   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17773     if (i == X86::AddrDisp)
17774       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17775     else
17776       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17777   }
17778   if (!UseImmLabel)
17779     MIB.addReg(LabelReg);
17780   else
17781     MIB.addMBB(restoreMBB);
17782   MIB.setMemRefs(MMOBegin, MMOEnd);
17783   // Setup
17784   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17785           .addMBB(restoreMBB);
17786
17787   const X86RegisterInfo *RegInfo =
17788     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17789   MIB.addRegMask(RegInfo->getNoPreservedMask());
17790   thisMBB->addSuccessor(mainMBB);
17791   thisMBB->addSuccessor(restoreMBB);
17792
17793   // mainMBB:
17794   //  EAX = 0
17795   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17796   mainMBB->addSuccessor(sinkMBB);
17797
17798   // sinkMBB:
17799   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17800           TII->get(X86::PHI), DstReg)
17801     .addReg(mainDstReg).addMBB(mainMBB)
17802     .addReg(restoreDstReg).addMBB(restoreMBB);
17803
17804   // restoreMBB:
17805   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17806   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17807   restoreMBB->addSuccessor(sinkMBB);
17808
17809   MI->eraseFromParent();
17810   return sinkMBB;
17811 }
17812
17813 MachineBasicBlock *
17814 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17815                                      MachineBasicBlock *MBB) const {
17816   DebugLoc DL = MI->getDebugLoc();
17817   MachineFunction *MF = MBB->getParent();
17818   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17819   MachineRegisterInfo &MRI = MF->getRegInfo();
17820
17821   // Memory Reference
17822   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17823   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17824
17825   MVT PVT = getPointerTy();
17826   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17827          "Invalid Pointer Size!");
17828
17829   const TargetRegisterClass *RC =
17830     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17831   unsigned Tmp = MRI.createVirtualRegister(RC);
17832   // Since FP is only updated here but NOT referenced, it's treated as GPR.
17833   const X86RegisterInfo *RegInfo =
17834     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17835   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17836   unsigned SP = RegInfo->getStackRegister();
17837
17838   MachineInstrBuilder MIB;
17839
17840   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17841   const int64_t SPOffset = 2 * PVT.getStoreSize();
17842
17843   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17844   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17845
17846   // Reload FP
17847   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17848   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17849     MIB.addOperand(MI->getOperand(i));
17850   MIB.setMemRefs(MMOBegin, MMOEnd);
17851   // Reload IP
17852   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17853   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17854     if (i == X86::AddrDisp)
17855       MIB.addDisp(MI->getOperand(i), LabelOffset);
17856     else
17857       MIB.addOperand(MI->getOperand(i));
17858   }
17859   MIB.setMemRefs(MMOBegin, MMOEnd);
17860   // Reload SP
17861   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17862   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17863     if (i == X86::AddrDisp)
17864       MIB.addDisp(MI->getOperand(i), SPOffset);
17865     else
17866       MIB.addOperand(MI->getOperand(i));
17867   }
17868   MIB.setMemRefs(MMOBegin, MMOEnd);
17869   // Jump
17870   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17871
17872   MI->eraseFromParent();
17873   return MBB;
17874 }
17875
17876 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17877 // accumulator loops. Writing back to the accumulator allows the coalescer
17878 // to remove extra copies in the loop.   
17879 MachineBasicBlock *
17880 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17881                                  MachineBasicBlock *MBB) const {
17882   MachineOperand &AddendOp = MI->getOperand(3);
17883
17884   // Bail out early if the addend isn't a register - we can't switch these.
17885   if (!AddendOp.isReg())
17886     return MBB;
17887
17888   MachineFunction &MF = *MBB->getParent();
17889   MachineRegisterInfo &MRI = MF.getRegInfo();
17890
17891   // Check whether the addend is defined by a PHI:
17892   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17893   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17894   if (!AddendDef.isPHI())
17895     return MBB;
17896
17897   // Look for the following pattern:
17898   // loop:
17899   //   %addend = phi [%entry, 0], [%loop, %result]
17900   //   ...
17901   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17902
17903   // Replace with:
17904   //   loop:
17905   //   %addend = phi [%entry, 0], [%loop, %result]
17906   //   ...
17907   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17908
17909   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17910     assert(AddendDef.getOperand(i).isReg());
17911     MachineOperand PHISrcOp = AddendDef.getOperand(i);
17912     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17913     if (&PHISrcInst == MI) {
17914       // Found a matching instruction.
17915       unsigned NewFMAOpc = 0;
17916       switch (MI->getOpcode()) {
17917         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17918         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17919         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17920         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17921         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17922         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17923         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17924         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17925         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17926         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17927         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17928         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17929         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17930         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17931         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17932         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17933         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17934         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17935         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17936         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17937         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17938         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17939         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17940         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17941         default: llvm_unreachable("Unrecognized FMA variant.");
17942       }
17943
17944       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17945       MachineInstrBuilder MIB =
17946         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17947         .addOperand(MI->getOperand(0))
17948         .addOperand(MI->getOperand(3))
17949         .addOperand(MI->getOperand(2))
17950         .addOperand(MI->getOperand(1));
17951       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17952       MI->eraseFromParent();
17953     }
17954   }
17955
17956   return MBB;
17957 }
17958
17959 MachineBasicBlock *
17960 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17961                                                MachineBasicBlock *BB) const {
17962   switch (MI->getOpcode()) {
17963   default: llvm_unreachable("Unexpected instr type to insert");
17964   case X86::TAILJMPd64:
17965   case X86::TAILJMPr64:
17966   case X86::TAILJMPm64:
17967     llvm_unreachable("TAILJMP64 would not be touched here.");
17968   case X86::TCRETURNdi64:
17969   case X86::TCRETURNri64:
17970   case X86::TCRETURNmi64:
17971     return BB;
17972   case X86::WIN_ALLOCA:
17973     return EmitLoweredWinAlloca(MI, BB);
17974   case X86::SEG_ALLOCA_32:
17975     return EmitLoweredSegAlloca(MI, BB, false);
17976   case X86::SEG_ALLOCA_64:
17977     return EmitLoweredSegAlloca(MI, BB, true);
17978   case X86::TLSCall_32:
17979   case X86::TLSCall_64:
17980     return EmitLoweredTLSCall(MI, BB);
17981   case X86::CMOV_GR8:
17982   case X86::CMOV_FR32:
17983   case X86::CMOV_FR64:
17984   case X86::CMOV_V4F32:
17985   case X86::CMOV_V2F64:
17986   case X86::CMOV_V2I64:
17987   case X86::CMOV_V8F32:
17988   case X86::CMOV_V4F64:
17989   case X86::CMOV_V4I64:
17990   case X86::CMOV_V16F32:
17991   case X86::CMOV_V8F64:
17992   case X86::CMOV_V8I64:
17993   case X86::CMOV_GR16:
17994   case X86::CMOV_GR32:
17995   case X86::CMOV_RFP32:
17996   case X86::CMOV_RFP64:
17997   case X86::CMOV_RFP80:
17998     return EmitLoweredSelect(MI, BB);
17999
18000   case X86::FP32_TO_INT16_IN_MEM:
18001   case X86::FP32_TO_INT32_IN_MEM:
18002   case X86::FP32_TO_INT64_IN_MEM:
18003   case X86::FP64_TO_INT16_IN_MEM:
18004   case X86::FP64_TO_INT32_IN_MEM:
18005   case X86::FP64_TO_INT64_IN_MEM:
18006   case X86::FP80_TO_INT16_IN_MEM:
18007   case X86::FP80_TO_INT32_IN_MEM:
18008   case X86::FP80_TO_INT64_IN_MEM: {
18009     MachineFunction *F = BB->getParent();
18010     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18011     DebugLoc DL = MI->getDebugLoc();
18012
18013     // Change the floating point control register to use "round towards zero"
18014     // mode when truncating to an integer value.
18015     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18016     addFrameReference(BuildMI(*BB, MI, DL,
18017                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18018
18019     // Load the old value of the high byte of the control word...
18020     unsigned OldCW =
18021       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18022     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18023                       CWFrameIdx);
18024
18025     // Set the high part to be round to zero...
18026     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18027       .addImm(0xC7F);
18028
18029     // Reload the modified control word now...
18030     addFrameReference(BuildMI(*BB, MI, DL,
18031                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18032
18033     // Restore the memory image of control word to original value
18034     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18035       .addReg(OldCW);
18036
18037     // Get the X86 opcode to use.
18038     unsigned Opc;
18039     switch (MI->getOpcode()) {
18040     default: llvm_unreachable("illegal opcode!");
18041     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18042     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18043     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18044     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18045     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18046     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18047     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18048     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18049     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18050     }
18051
18052     X86AddressMode AM;
18053     MachineOperand &Op = MI->getOperand(0);
18054     if (Op.isReg()) {
18055       AM.BaseType = X86AddressMode::RegBase;
18056       AM.Base.Reg = Op.getReg();
18057     } else {
18058       AM.BaseType = X86AddressMode::FrameIndexBase;
18059       AM.Base.FrameIndex = Op.getIndex();
18060     }
18061     Op = MI->getOperand(1);
18062     if (Op.isImm())
18063       AM.Scale = Op.getImm();
18064     Op = MI->getOperand(2);
18065     if (Op.isImm())
18066       AM.IndexReg = Op.getImm();
18067     Op = MI->getOperand(3);
18068     if (Op.isGlobal()) {
18069       AM.GV = Op.getGlobal();
18070     } else {
18071       AM.Disp = Op.getImm();
18072     }
18073     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18074                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18075
18076     // Reload the original control word now.
18077     addFrameReference(BuildMI(*BB, MI, DL,
18078                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18079
18080     MI->eraseFromParent();   // The pseudo instruction is gone now.
18081     return BB;
18082   }
18083     // String/text processing lowering.
18084   case X86::PCMPISTRM128REG:
18085   case X86::VPCMPISTRM128REG:
18086   case X86::PCMPISTRM128MEM:
18087   case X86::VPCMPISTRM128MEM:
18088   case X86::PCMPESTRM128REG:
18089   case X86::VPCMPESTRM128REG:
18090   case X86::PCMPESTRM128MEM:
18091   case X86::VPCMPESTRM128MEM:
18092     assert(Subtarget->hasSSE42() &&
18093            "Target must have SSE4.2 or AVX features enabled");
18094     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18095
18096   // String/text processing lowering.
18097   case X86::PCMPISTRIREG:
18098   case X86::VPCMPISTRIREG:
18099   case X86::PCMPISTRIMEM:
18100   case X86::VPCMPISTRIMEM:
18101   case X86::PCMPESTRIREG:
18102   case X86::VPCMPESTRIREG:
18103   case X86::PCMPESTRIMEM:
18104   case X86::VPCMPESTRIMEM:
18105     assert(Subtarget->hasSSE42() &&
18106            "Target must have SSE4.2 or AVX features enabled");
18107     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18108
18109   // Thread synchronization.
18110   case X86::MONITOR:
18111     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18112
18113   // xbegin
18114   case X86::XBEGIN:
18115     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18116
18117   case X86::VASTART_SAVE_XMM_REGS:
18118     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18119
18120   case X86::VAARG_64:
18121     return EmitVAARG64WithCustomInserter(MI, BB);
18122
18123   case X86::EH_SjLj_SetJmp32:
18124   case X86::EH_SjLj_SetJmp64:
18125     return emitEHSjLjSetJmp(MI, BB);
18126
18127   case X86::EH_SjLj_LongJmp32:
18128   case X86::EH_SjLj_LongJmp64:
18129     return emitEHSjLjLongJmp(MI, BB);
18130
18131   case TargetOpcode::STACKMAP:
18132   case TargetOpcode::PATCHPOINT:
18133     return emitPatchPoint(MI, BB);
18134
18135   case X86::VFMADDPDr213r:
18136   case X86::VFMADDPSr213r:
18137   case X86::VFMADDSDr213r:
18138   case X86::VFMADDSSr213r:
18139   case X86::VFMSUBPDr213r:
18140   case X86::VFMSUBPSr213r:
18141   case X86::VFMSUBSDr213r:
18142   case X86::VFMSUBSSr213r:
18143   case X86::VFNMADDPDr213r:
18144   case X86::VFNMADDPSr213r:
18145   case X86::VFNMADDSDr213r:
18146   case X86::VFNMADDSSr213r:
18147   case X86::VFNMSUBPDr213r:
18148   case X86::VFNMSUBPSr213r:
18149   case X86::VFNMSUBSDr213r:
18150   case X86::VFNMSUBSSr213r:
18151   case X86::VFMADDPDr213rY:
18152   case X86::VFMADDPSr213rY:
18153   case X86::VFMSUBPDr213rY:
18154   case X86::VFMSUBPSr213rY:
18155   case X86::VFNMADDPDr213rY:
18156   case X86::VFNMADDPSr213rY:
18157   case X86::VFNMSUBPDr213rY:
18158   case X86::VFNMSUBPSr213rY:
18159     return emitFMA3Instr(MI, BB);
18160   }
18161 }
18162
18163 //===----------------------------------------------------------------------===//
18164 //                           X86 Optimization Hooks
18165 //===----------------------------------------------------------------------===//
18166
18167 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18168                                                       APInt &KnownZero,
18169                                                       APInt &KnownOne,
18170                                                       const SelectionDAG &DAG,
18171                                                       unsigned Depth) const {
18172   unsigned BitWidth = KnownZero.getBitWidth();
18173   unsigned Opc = Op.getOpcode();
18174   assert((Opc >= ISD::BUILTIN_OP_END ||
18175           Opc == ISD::INTRINSIC_WO_CHAIN ||
18176           Opc == ISD::INTRINSIC_W_CHAIN ||
18177           Opc == ISD::INTRINSIC_VOID) &&
18178          "Should use MaskedValueIsZero if you don't know whether Op"
18179          " is a target node!");
18180
18181   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18182   switch (Opc) {
18183   default: break;
18184   case X86ISD::ADD:
18185   case X86ISD::SUB:
18186   case X86ISD::ADC:
18187   case X86ISD::SBB:
18188   case X86ISD::SMUL:
18189   case X86ISD::UMUL:
18190   case X86ISD::INC:
18191   case X86ISD::DEC:
18192   case X86ISD::OR:
18193   case X86ISD::XOR:
18194   case X86ISD::AND:
18195     // These nodes' second result is a boolean.
18196     if (Op.getResNo() == 0)
18197       break;
18198     // Fallthrough
18199   case X86ISD::SETCC:
18200     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18201     break;
18202   case ISD::INTRINSIC_WO_CHAIN: {
18203     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18204     unsigned NumLoBits = 0;
18205     switch (IntId) {
18206     default: break;
18207     case Intrinsic::x86_sse_movmsk_ps:
18208     case Intrinsic::x86_avx_movmsk_ps_256:
18209     case Intrinsic::x86_sse2_movmsk_pd:
18210     case Intrinsic::x86_avx_movmsk_pd_256:
18211     case Intrinsic::x86_mmx_pmovmskb:
18212     case Intrinsic::x86_sse2_pmovmskb_128:
18213     case Intrinsic::x86_avx2_pmovmskb: {
18214       // High bits of movmskp{s|d}, pmovmskb are known zero.
18215       switch (IntId) {
18216         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18217         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18218         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18219         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18220         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18221         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18222         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18223         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18224       }
18225       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18226       break;
18227     }
18228     }
18229     break;
18230   }
18231   }
18232 }
18233
18234 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18235   SDValue Op,
18236   const SelectionDAG &,
18237   unsigned Depth) const {
18238   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18239   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18240     return Op.getValueType().getScalarType().getSizeInBits();
18241
18242   // Fallback case.
18243   return 1;
18244 }
18245
18246 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18247 /// node is a GlobalAddress + offset.
18248 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18249                                        const GlobalValue* &GA,
18250                                        int64_t &Offset) const {
18251   if (N->getOpcode() == X86ISD::Wrapper) {
18252     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18253       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18254       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18255       return true;
18256     }
18257   }
18258   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18259 }
18260
18261 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18262 /// same as extracting the high 128-bit part of 256-bit vector and then
18263 /// inserting the result into the low part of a new 256-bit vector
18264 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18265   EVT VT = SVOp->getValueType(0);
18266   unsigned NumElems = VT.getVectorNumElements();
18267
18268   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18269   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18270     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18271         SVOp->getMaskElt(j) >= 0)
18272       return false;
18273
18274   return true;
18275 }
18276
18277 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18278 /// same as extracting the low 128-bit part of 256-bit vector and then
18279 /// inserting the result into the high part of a new 256-bit vector
18280 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18281   EVT VT = SVOp->getValueType(0);
18282   unsigned NumElems = VT.getVectorNumElements();
18283
18284   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18285   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18286     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18287         SVOp->getMaskElt(j) >= 0)
18288       return false;
18289
18290   return true;
18291 }
18292
18293 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18294 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18295                                         TargetLowering::DAGCombinerInfo &DCI,
18296                                         const X86Subtarget* Subtarget) {
18297   SDLoc dl(N);
18298   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18299   SDValue V1 = SVOp->getOperand(0);
18300   SDValue V2 = SVOp->getOperand(1);
18301   EVT VT = SVOp->getValueType(0);
18302   unsigned NumElems = VT.getVectorNumElements();
18303
18304   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18305       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18306     //
18307     //                   0,0,0,...
18308     //                      |
18309     //    V      UNDEF    BUILD_VECTOR    UNDEF
18310     //     \      /           \           /
18311     //  CONCAT_VECTOR         CONCAT_VECTOR
18312     //         \                  /
18313     //          \                /
18314     //          RESULT: V + zero extended
18315     //
18316     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18317         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18318         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18319       return SDValue();
18320
18321     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18322       return SDValue();
18323
18324     // To match the shuffle mask, the first half of the mask should
18325     // be exactly the first vector, and all the rest a splat with the
18326     // first element of the second one.
18327     for (unsigned i = 0; i != NumElems/2; ++i)
18328       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18329           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18330         return SDValue();
18331
18332     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18333     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18334       if (Ld->hasNUsesOfValue(1, 0)) {
18335         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18336         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18337         SDValue ResNode =
18338           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18339                                   Ld->getMemoryVT(),
18340                                   Ld->getPointerInfo(),
18341                                   Ld->getAlignment(),
18342                                   false/*isVolatile*/, true/*ReadMem*/,
18343                                   false/*WriteMem*/);
18344
18345         // Make sure the newly-created LOAD is in the same position as Ld in
18346         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18347         // and update uses of Ld's output chain to use the TokenFactor.
18348         if (Ld->hasAnyUseOfValue(1)) {
18349           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18350                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18351           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18352           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18353                                  SDValue(ResNode.getNode(), 1));
18354         }
18355
18356         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18357       }
18358     }
18359
18360     // Emit a zeroed vector and insert the desired subvector on its
18361     // first half.
18362     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18363     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18364     return DCI.CombineTo(N, InsV);
18365   }
18366
18367   //===--------------------------------------------------------------------===//
18368   // Combine some shuffles into subvector extracts and inserts:
18369   //
18370
18371   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18372   if (isShuffleHigh128VectorInsertLow(SVOp)) {
18373     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18374     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18375     return DCI.CombineTo(N, InsV);
18376   }
18377
18378   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18379   if (isShuffleLow128VectorInsertHigh(SVOp)) {
18380     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18381     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18382     return DCI.CombineTo(N, InsV);
18383   }
18384
18385   return SDValue();
18386 }
18387
18388 /// \brief Get the PSHUF-style mask from PSHUF node.
18389 ///
18390 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18391 /// PSHUF-style masks that can be reused with such instructions.
18392 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18393   SmallVector<int, 4> Mask;
18394   bool IsUnary;
18395   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18396   (void)HaveMask;
18397   assert(HaveMask);
18398
18399   switch (N.getOpcode()) {
18400   case X86ISD::PSHUFD:
18401     return Mask;
18402   case X86ISD::PSHUFLW:
18403     Mask.resize(4);
18404     return Mask;
18405   case X86ISD::PSHUFHW:
18406     Mask.erase(Mask.begin(), Mask.begin() + 4);
18407     for (int &M : Mask)
18408       M -= 4;
18409     return Mask;
18410   default:
18411     llvm_unreachable("No valid shuffle instruction found!");
18412   }
18413 }
18414
18415 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18416 ///
18417 /// We walk up the chain and look for a combinable shuffle, skipping over
18418 /// shuffles that we could hoist this shuffle's transformation past without
18419 /// altering anything.
18420 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18421                                          SelectionDAG &DAG,
18422                                          TargetLowering::DAGCombinerInfo &DCI) {
18423   assert(N.getOpcode() == X86ISD::PSHUFD &&
18424          "Called with something other than an x86 128-bit half shuffle!");
18425   SDLoc DL(N);
18426
18427   // Walk up a single-use chain looking for a combinable shuffle.
18428   SDValue V = N.getOperand(0);
18429   for (; V.hasOneUse(); V = V.getOperand(0)) {
18430     switch (V.getOpcode()) {
18431     default:
18432       return false; // Nothing combined!
18433
18434     case ISD::BITCAST:
18435       // Skip bitcasts as we always know the type for the target specific
18436       // instructions.
18437       continue;
18438
18439     case X86ISD::PSHUFD:
18440       // Found another dword shuffle.
18441       break;
18442
18443     case X86ISD::PSHUFLW:
18444       // Check that the low words (being shuffled) are the identity in the
18445       // dword shuffle, and the high words are self-contained.
18446       if (Mask[0] != 0 || Mask[1] != 1 ||
18447           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18448         return false;
18449
18450       continue;
18451
18452     case X86ISD::PSHUFHW:
18453       // Check that the high words (being shuffled) are the identity in the
18454       // dword shuffle, and the low words are self-contained.
18455       if (Mask[2] != 2 || Mask[3] != 3 ||
18456           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18457         return false;
18458
18459       continue;
18460     }
18461     // Break out of the loop if we break out of the switch.
18462     break;
18463   }
18464
18465   if (!V.hasOneUse())
18466     // We fell out of the loop without finding a viable combining instruction.
18467     return false;
18468
18469   // Record the old value to use in RAUW-ing.
18470   SDValue Old = V;
18471
18472   // Merge this node's mask and our incoming mask.
18473   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18474   for (int &M : Mask)
18475     M = VMask[M];
18476   V = DAG.getNode(X86ISD::PSHUFD, DL, V.getValueType(), V.getOperand(0),
18477                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18478
18479   // It is possible that one of the combinable shuffles was completely absorbed
18480   // by the other, just replace it and revisit all users in that case.
18481   if (Old.getNode() == V.getNode()) {
18482     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
18483     return true;
18484   }
18485
18486   // Replace N with its operand as we're going to combine that shuffle away.
18487   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18488
18489   // Replace the combinable shuffle with the combined one, updating all users
18490   // so that we re-evaluate the chain here.
18491   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18492   return true;
18493 }
18494
18495 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18496 ///
18497 /// We walk up the chain, skipping shuffles of the other half and looking
18498 /// through shuffles which switch halves trying to find a shuffle of the same
18499 /// pair of dwords.
18500 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18501                                         SelectionDAG &DAG,
18502                                         TargetLowering::DAGCombinerInfo &DCI) {
18503   assert(
18504       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18505       "Called with something other than an x86 128-bit half shuffle!");
18506   SDLoc DL(N);
18507   unsigned CombineOpcode = N.getOpcode();
18508
18509   // Walk up a single-use chain looking for a combinable shuffle.
18510   SDValue V = N.getOperand(0);
18511   for (; V.hasOneUse(); V = V.getOperand(0)) {
18512     switch (V.getOpcode()) {
18513     default:
18514       return false; // Nothing combined!
18515
18516     case ISD::BITCAST:
18517       // Skip bitcasts as we always know the type for the target specific
18518       // instructions.
18519       continue;
18520
18521     case X86ISD::PSHUFLW:
18522     case X86ISD::PSHUFHW:
18523       if (V.getOpcode() == CombineOpcode)
18524         break;
18525
18526       // Other-half shuffles are no-ops.
18527       continue;
18528
18529     case X86ISD::PSHUFD: {
18530       // We can only handle pshufd if the half we are combining either stays in
18531       // its half, or switches to the other half. Bail if one of these isn't
18532       // true.
18533       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18534       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18535       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18536             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18537         return false;
18538
18539       // Map the mask through the pshufd and keep walking up the chain.
18540       for (int i = 0; i < 4; ++i)
18541         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18542
18543       // Switch halves if the pshufd does.
18544       CombineOpcode =
18545           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18546       continue;
18547     }
18548     }
18549     // Break out of the loop if we break out of the switch.
18550     break;
18551   }
18552
18553   if (!V.hasOneUse())
18554     // We fell out of the loop without finding a viable combining instruction.
18555     return false;
18556
18557   // Record the old value to use in RAUW-ing.
18558   SDValue Old = V;
18559
18560   // Merge this node's mask and our incoming mask (adjusted to account for all
18561   // the pshufd instructions encountered).
18562   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18563   for (int &M : Mask)
18564     M = VMask[M];
18565   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18566                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18567
18568   // Replace N with its operand as we're going to combine that shuffle away.
18569   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18570
18571   // Replace the combinable shuffle with the combined one, updating all users
18572   // so that we re-evaluate the chain here.
18573   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18574   return true;
18575 }
18576
18577 /// \brief Try to combine x86 target specific shuffles.
18578 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18579                                            TargetLowering::DAGCombinerInfo &DCI,
18580                                            const X86Subtarget *Subtarget) {
18581   SDLoc DL(N);
18582   MVT VT = N.getSimpleValueType();
18583   SmallVector<int, 4> Mask;
18584
18585   switch (N.getOpcode()) {
18586   case X86ISD::PSHUFD:
18587   case X86ISD::PSHUFLW:
18588   case X86ISD::PSHUFHW:
18589     Mask = getPSHUFShuffleMask(N);
18590     assert(Mask.size() == 4);
18591     break;
18592   default:
18593     return SDValue();
18594   }
18595
18596   // Nuke no-op shuffles that show up after combining.
18597   if (isNoopShuffleMask(Mask))
18598     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18599
18600   // Look for simplifications involving one or two shuffle instructions.
18601   SDValue V = N.getOperand(0);
18602   switch (N.getOpcode()) {
18603   default:
18604     break;
18605   case X86ISD::PSHUFLW:
18606   case X86ISD::PSHUFHW:
18607     assert(VT == MVT::v8i16);
18608     (void)VT;
18609
18610     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18611       return SDValue(); // We combined away this shuffle, so we're done.
18612
18613     // See if this reduces to a PSHUFD which is no more expensive and can
18614     // combine with more operations.
18615     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18616         areAdjacentMasksSequential(Mask)) {
18617       int DMask[] = {-1, -1, -1, -1};
18618       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18619       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18620       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18621       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18622       DCI.AddToWorklist(V.getNode());
18623       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18624                       getV4X86ShuffleImm8ForMask(DMask, DAG));
18625       DCI.AddToWorklist(V.getNode());
18626       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18627     }
18628
18629     break;
18630
18631   case X86ISD::PSHUFD:
18632     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
18633       return SDValue(); // We combined away this shuffle.
18634
18635     break;
18636   }
18637
18638   return SDValue();
18639 }
18640
18641 /// PerformShuffleCombine - Performs several different shuffle combines.
18642 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
18643                                      TargetLowering::DAGCombinerInfo &DCI,
18644                                      const X86Subtarget *Subtarget) {
18645   SDLoc dl(N);
18646   SDValue N0 = N->getOperand(0);
18647   SDValue N1 = N->getOperand(1);
18648   EVT VT = N->getValueType(0);
18649
18650   // Canonicalize shuffles that perform 'addsub' on packed float vectors
18651   // according to the rule:
18652   //  (shuffle (FADD A, B), (FSUB A, B), Mask) ->
18653   //  (shuffle (FSUB A, -B), (FADD A, -B), Mask)
18654   //
18655   // Where 'Mask' is:
18656   //  <0,5,2,7>             -- for v4f32 and v4f64 shuffles;
18657   //  <0,3>                 -- for v2f64 shuffles;
18658   //  <0,9,2,11,4,13,6,15>  -- for v8f32 shuffles.
18659   //
18660   // This helps pattern-matching more SSE3/AVX ADDSUB instructions
18661   // during ISel stage.
18662   if (N->getOpcode() == ISD::VECTOR_SHUFFLE &&
18663       ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18664        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18665       N0->getOpcode() == ISD::FADD && N1->getOpcode() == ISD::FSUB &&
18666       // Operands to the FADD and FSUB must be the same.
18667       ((N0->getOperand(0) == N1->getOperand(0) &&
18668         N0->getOperand(1) == N1->getOperand(1)) ||
18669        // FADD is commutable. See if by commuting the operands of the FADD
18670        // we would still be able to match the operands of the FSUB dag node.
18671        (N0->getOperand(1) == N1->getOperand(0) &&
18672         N0->getOperand(0) == N1->getOperand(1))) &&
18673       N0->getOperand(0)->getOpcode() != ISD::UNDEF &&
18674       N0->getOperand(1)->getOpcode() != ISD::UNDEF) {
18675     
18676     ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
18677     unsigned NumElts = VT.getVectorNumElements();
18678     ArrayRef<int> Mask = SV->getMask();
18679     bool CanFold = true;
18680
18681     for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i)
18682       CanFold = Mask[i] == (int)((i & 1) ? i + NumElts : i);
18683
18684     if (CanFold) {
18685       SDValue Op0 = N1->getOperand(0);
18686       SDValue Op1 = DAG.getNode(ISD::FNEG, dl, VT, N1->getOperand(1));
18687       SDValue Sub = DAG.getNode(ISD::FSUB, dl, VT, Op0, Op1);
18688       SDValue Add = DAG.getNode(ISD::FADD, dl, VT, Op0, Op1);
18689       return DAG.getVectorShuffle(VT, dl, Sub, Add, Mask);
18690     }
18691   }
18692
18693   // Don't create instructions with illegal types after legalize types has run.
18694   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18695   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18696     return SDValue();
18697
18698   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18699   if (Subtarget->hasFp256() && VT.is256BitVector() &&
18700       N->getOpcode() == ISD::VECTOR_SHUFFLE)
18701     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18702
18703   // During Type Legalization, when promoting illegal vector types,
18704   // the backend might introduce new shuffle dag nodes and bitcasts.
18705   //
18706   // This code performs the following transformation:
18707   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18708   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18709   //
18710   // We do this only if both the bitcast and the BINOP dag nodes have
18711   // one use. Also, perform this transformation only if the new binary
18712   // operation is legal. This is to avoid introducing dag nodes that
18713   // potentially need to be further expanded (or custom lowered) into a
18714   // less optimal sequence of dag nodes.
18715   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18716       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18717       N0.getOpcode() == ISD::BITCAST) {
18718     SDValue BC0 = N0.getOperand(0);
18719     EVT SVT = BC0.getValueType();
18720     unsigned Opcode = BC0.getOpcode();
18721     unsigned NumElts = VT.getVectorNumElements();
18722     
18723     if (BC0.hasOneUse() && SVT.isVector() &&
18724         SVT.getVectorNumElements() * 2 == NumElts &&
18725         TLI.isOperationLegal(Opcode, VT)) {
18726       bool CanFold = false;
18727       switch (Opcode) {
18728       default : break;
18729       case ISD::ADD :
18730       case ISD::FADD :
18731       case ISD::SUB :
18732       case ISD::FSUB :
18733       case ISD::MUL :
18734       case ISD::FMUL :
18735         CanFold = true;
18736       }
18737
18738       unsigned SVTNumElts = SVT.getVectorNumElements();
18739       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18740       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18741         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18742       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18743         CanFold = SVOp->getMaskElt(i) < 0;
18744
18745       if (CanFold) {
18746         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18747         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18748         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18749         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18750       }
18751     }
18752   }
18753
18754   // Only handle 128 wide vector from here on.
18755   if (!VT.is128BitVector())
18756     return SDValue();
18757
18758   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18759   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18760   // consecutive, non-overlapping, and in the right order.
18761   SmallVector<SDValue, 16> Elts;
18762   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18763     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18764
18765   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18766   if (LD.getNode())
18767     return LD;
18768
18769   if (isTargetShuffle(N->getOpcode())) {
18770     SDValue Shuffle =
18771         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
18772     if (Shuffle.getNode())
18773       return Shuffle;
18774   }
18775
18776   return SDValue();
18777 }
18778
18779 /// PerformTruncateCombine - Converts truncate operation to
18780 /// a sequence of vector shuffle operations.
18781 /// It is possible when we truncate 256-bit vector to 128-bit vector
18782 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18783                                       TargetLowering::DAGCombinerInfo &DCI,
18784                                       const X86Subtarget *Subtarget)  {
18785   return SDValue();
18786 }
18787
18788 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18789 /// specific shuffle of a load can be folded into a single element load.
18790 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18791 /// shuffles have been customed lowered so we need to handle those here.
18792 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18793                                          TargetLowering::DAGCombinerInfo &DCI) {
18794   if (DCI.isBeforeLegalizeOps())
18795     return SDValue();
18796
18797   SDValue InVec = N->getOperand(0);
18798   SDValue EltNo = N->getOperand(1);
18799
18800   if (!isa<ConstantSDNode>(EltNo))
18801     return SDValue();
18802
18803   EVT VT = InVec.getValueType();
18804
18805   bool HasShuffleIntoBitcast = false;
18806   if (InVec.getOpcode() == ISD::BITCAST) {
18807     // Don't duplicate a load with other uses.
18808     if (!InVec.hasOneUse())
18809       return SDValue();
18810     EVT BCVT = InVec.getOperand(0).getValueType();
18811     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18812       return SDValue();
18813     InVec = InVec.getOperand(0);
18814     HasShuffleIntoBitcast = true;
18815   }
18816
18817   if (!isTargetShuffle(InVec.getOpcode()))
18818     return SDValue();
18819
18820   // Don't duplicate a load with other uses.
18821   if (!InVec.hasOneUse())
18822     return SDValue();
18823
18824   SmallVector<int, 16> ShuffleMask;
18825   bool UnaryShuffle;
18826   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18827                             UnaryShuffle))
18828     return SDValue();
18829
18830   // Select the input vector, guarding against out of range extract vector.
18831   unsigned NumElems = VT.getVectorNumElements();
18832   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18833   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18834   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18835                                          : InVec.getOperand(1);
18836
18837   // If inputs to shuffle are the same for both ops, then allow 2 uses
18838   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18839
18840   if (LdNode.getOpcode() == ISD::BITCAST) {
18841     // Don't duplicate a load with other uses.
18842     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18843       return SDValue();
18844
18845     AllowedUses = 1; // only allow 1 load use if we have a bitcast
18846     LdNode = LdNode.getOperand(0);
18847   }
18848
18849   if (!ISD::isNormalLoad(LdNode.getNode()))
18850     return SDValue();
18851
18852   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18853
18854   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18855     return SDValue();
18856
18857   if (HasShuffleIntoBitcast) {
18858     // If there's a bitcast before the shuffle, check if the load type and
18859     // alignment is valid.
18860     unsigned Align = LN0->getAlignment();
18861     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18862     unsigned NewAlign = TLI.getDataLayout()->
18863       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18864
18865     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18866       return SDValue();
18867   }
18868
18869   // All checks match so transform back to vector_shuffle so that DAG combiner
18870   // can finish the job
18871   SDLoc dl(N);
18872
18873   // Create shuffle node taking into account the case that its a unary shuffle
18874   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18875   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18876                                  InVec.getOperand(0), Shuffle,
18877                                  &ShuffleMask[0]);
18878   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18879   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18880                      EltNo);
18881 }
18882
18883 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
18884 /// generation and convert it from being a bunch of shuffles and extracts
18885 /// to a simple store and scalar loads to extract the elements.
18886 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
18887                                          TargetLowering::DAGCombinerInfo &DCI) {
18888   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
18889   if (NewOp.getNode())
18890     return NewOp;
18891
18892   SDValue InputVector = N->getOperand(0);
18893
18894   // Detect whether we are trying to convert from mmx to i32 and the bitcast
18895   // from mmx to v2i32 has a single usage.
18896   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
18897       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
18898       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
18899     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
18900                        N->getValueType(0),
18901                        InputVector.getNode()->getOperand(0));
18902
18903   // Only operate on vectors of 4 elements, where the alternative shuffling
18904   // gets to be more expensive.
18905   if (InputVector.getValueType() != MVT::v4i32)
18906     return SDValue();
18907
18908   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
18909   // single use which is a sign-extend or zero-extend, and all elements are
18910   // used.
18911   SmallVector<SDNode *, 4> Uses;
18912   unsigned ExtractedElements = 0;
18913   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
18914        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
18915     if (UI.getUse().getResNo() != InputVector.getResNo())
18916       return SDValue();
18917
18918     SDNode *Extract = *UI;
18919     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18920       return SDValue();
18921
18922     if (Extract->getValueType(0) != MVT::i32)
18923       return SDValue();
18924     if (!Extract->hasOneUse())
18925       return SDValue();
18926     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
18927         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
18928       return SDValue();
18929     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
18930       return SDValue();
18931
18932     // Record which element was extracted.
18933     ExtractedElements |=
18934       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
18935
18936     Uses.push_back(Extract);
18937   }
18938
18939   // If not all the elements were used, this may not be worthwhile.
18940   if (ExtractedElements != 15)
18941     return SDValue();
18942
18943   // Ok, we've now decided to do the transformation.
18944   SDLoc dl(InputVector);
18945
18946   // Store the value to a temporary stack slot.
18947   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18948   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18949                             MachinePointerInfo(), false, false, 0);
18950
18951   // Replace each use (extract) with a load of the appropriate element.
18952   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18953        UE = Uses.end(); UI != UE; ++UI) {
18954     SDNode *Extract = *UI;
18955
18956     // cOMpute the element's address.
18957     SDValue Idx = Extract->getOperand(1);
18958     unsigned EltSize =
18959         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18960     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18961     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18962     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
18963
18964     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
18965                                      StackPtr, OffsetVal);
18966
18967     // Load the scalar.
18968     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
18969                                      ScalarAddr, MachinePointerInfo(),
18970                                      false, false, false, 0);
18971
18972     // Replace the exact with the load.
18973     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
18974   }
18975
18976   // The replacement was made in place; don't return anything.
18977   return SDValue();
18978 }
18979
18980 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
18981 static std::pair<unsigned, bool>
18982 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
18983                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
18984   if (!VT.isVector())
18985     return std::make_pair(0, false);
18986
18987   bool NeedSplit = false;
18988   switch (VT.getSimpleVT().SimpleTy) {
18989   default: return std::make_pair(0, false);
18990   case MVT::v32i8:
18991   case MVT::v16i16:
18992   case MVT::v8i32:
18993     if (!Subtarget->hasAVX2())
18994       NeedSplit = true;
18995     if (!Subtarget->hasAVX())
18996       return std::make_pair(0, false);
18997     break;
18998   case MVT::v16i8:
18999   case MVT::v8i16:
19000   case MVT::v4i32:
19001     if (!Subtarget->hasSSE2())
19002       return std::make_pair(0, false);
19003   }
19004
19005   // SSE2 has only a small subset of the operations.
19006   bool hasUnsigned = Subtarget->hasSSE41() ||
19007                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19008   bool hasSigned = Subtarget->hasSSE41() ||
19009                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19010
19011   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19012
19013   unsigned Opc = 0;
19014   // Check for x CC y ? x : y.
19015   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19016       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19017     switch (CC) {
19018     default: break;
19019     case ISD::SETULT:
19020     case ISD::SETULE:
19021       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19022     case ISD::SETUGT:
19023     case ISD::SETUGE:
19024       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19025     case ISD::SETLT:
19026     case ISD::SETLE:
19027       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19028     case ISD::SETGT:
19029     case ISD::SETGE:
19030       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19031     }
19032   // Check for x CC y ? y : x -- a min/max with reversed arms.
19033   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19034              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19035     switch (CC) {
19036     default: break;
19037     case ISD::SETULT:
19038     case ISD::SETULE:
19039       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19040     case ISD::SETUGT:
19041     case ISD::SETUGE:
19042       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19043     case ISD::SETLT:
19044     case ISD::SETLE:
19045       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19046     case ISD::SETGT:
19047     case ISD::SETGE:
19048       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19049     }
19050   }
19051
19052   return std::make_pair(Opc, NeedSplit);
19053 }
19054
19055 static SDValue
19056 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19057                                       const X86Subtarget *Subtarget) {
19058   SDLoc dl(N);
19059   SDValue Cond = N->getOperand(0);
19060   SDValue LHS = N->getOperand(1);
19061   SDValue RHS = N->getOperand(2);
19062
19063   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19064     SDValue CondSrc = Cond->getOperand(0);
19065     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19066       Cond = CondSrc->getOperand(0);
19067   }
19068
19069   MVT VT = N->getSimpleValueType(0);
19070   MVT EltVT = VT.getVectorElementType();
19071   unsigned NumElems = VT.getVectorNumElements();
19072   // There is no blend with immediate in AVX-512.
19073   if (VT.is512BitVector())
19074     return SDValue();
19075
19076   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19077     return SDValue();
19078   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19079     return SDValue();
19080
19081   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19082     return SDValue();
19083
19084   unsigned MaskValue = 0;
19085   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19086     return SDValue();
19087
19088   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19089   for (unsigned i = 0; i < NumElems; ++i) {
19090     // Be sure we emit undef where we can.
19091     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19092       ShuffleMask[i] = -1;
19093     else
19094       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19095   }
19096
19097   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19098 }
19099
19100 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19101 /// nodes.
19102 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19103                                     TargetLowering::DAGCombinerInfo &DCI,
19104                                     const X86Subtarget *Subtarget) {
19105   SDLoc DL(N);
19106   SDValue Cond = N->getOperand(0);
19107   // Get the LHS/RHS of the select.
19108   SDValue LHS = N->getOperand(1);
19109   SDValue RHS = N->getOperand(2);
19110   EVT VT = LHS.getValueType();
19111   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19112
19113   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19114   // instructions match the semantics of the common C idiom x<y?x:y but not
19115   // x<=y?x:y, because of how they handle negative zero (which can be
19116   // ignored in unsafe-math mode).
19117   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19118       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19119       (Subtarget->hasSSE2() ||
19120        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19121     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19122
19123     unsigned Opcode = 0;
19124     // Check for x CC y ? x : y.
19125     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19126         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19127       switch (CC) {
19128       default: break;
19129       case ISD::SETULT:
19130         // Converting this to a min would handle NaNs incorrectly, and swapping
19131         // the operands would cause it to handle comparisons between positive
19132         // and negative zero incorrectly.
19133         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19134           if (!DAG.getTarget().Options.UnsafeFPMath &&
19135               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19136             break;
19137           std::swap(LHS, RHS);
19138         }
19139         Opcode = X86ISD::FMIN;
19140         break;
19141       case ISD::SETOLE:
19142         // Converting this to a min would handle comparisons between positive
19143         // and negative zero incorrectly.
19144         if (!DAG.getTarget().Options.UnsafeFPMath &&
19145             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19146           break;
19147         Opcode = X86ISD::FMIN;
19148         break;
19149       case ISD::SETULE:
19150         // Converting this to a min would handle both negative zeros and NaNs
19151         // incorrectly, but we can swap the operands to fix both.
19152         std::swap(LHS, RHS);
19153       case ISD::SETOLT:
19154       case ISD::SETLT:
19155       case ISD::SETLE:
19156         Opcode = X86ISD::FMIN;
19157         break;
19158
19159       case ISD::SETOGE:
19160         // Converting this to a max would handle comparisons between positive
19161         // and negative zero incorrectly.
19162         if (!DAG.getTarget().Options.UnsafeFPMath &&
19163             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19164           break;
19165         Opcode = X86ISD::FMAX;
19166         break;
19167       case ISD::SETUGT:
19168         // Converting this to a max would handle NaNs incorrectly, and swapping
19169         // the operands would cause it to handle comparisons between positive
19170         // and negative zero incorrectly.
19171         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19172           if (!DAG.getTarget().Options.UnsafeFPMath &&
19173               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19174             break;
19175           std::swap(LHS, RHS);
19176         }
19177         Opcode = X86ISD::FMAX;
19178         break;
19179       case ISD::SETUGE:
19180         // Converting this to a max would handle both negative zeros and NaNs
19181         // incorrectly, but we can swap the operands to fix both.
19182         std::swap(LHS, RHS);
19183       case ISD::SETOGT:
19184       case ISD::SETGT:
19185       case ISD::SETGE:
19186         Opcode = X86ISD::FMAX;
19187         break;
19188       }
19189     // Check for x CC y ? y : x -- a min/max with reversed arms.
19190     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19191                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19192       switch (CC) {
19193       default: break;
19194       case ISD::SETOGE:
19195         // Converting this to a min would handle comparisons between positive
19196         // and negative zero incorrectly, and swapping the operands would
19197         // cause it to handle NaNs incorrectly.
19198         if (!DAG.getTarget().Options.UnsafeFPMath &&
19199             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19200           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19201             break;
19202           std::swap(LHS, RHS);
19203         }
19204         Opcode = X86ISD::FMIN;
19205         break;
19206       case ISD::SETUGT:
19207         // Converting this to a min would handle NaNs incorrectly.
19208         if (!DAG.getTarget().Options.UnsafeFPMath &&
19209             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19210           break;
19211         Opcode = X86ISD::FMIN;
19212         break;
19213       case ISD::SETUGE:
19214         // Converting this to a min would handle both negative zeros and NaNs
19215         // incorrectly, but we can swap the operands to fix both.
19216         std::swap(LHS, RHS);
19217       case ISD::SETOGT:
19218       case ISD::SETGT:
19219       case ISD::SETGE:
19220         Opcode = X86ISD::FMIN;
19221         break;
19222
19223       case ISD::SETULT:
19224         // Converting this to a max would handle NaNs incorrectly.
19225         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19226           break;
19227         Opcode = X86ISD::FMAX;
19228         break;
19229       case ISD::SETOLE:
19230         // Converting this to a max would handle comparisons between positive
19231         // and negative zero incorrectly, and swapping the operands would
19232         // cause it to handle NaNs incorrectly.
19233         if (!DAG.getTarget().Options.UnsafeFPMath &&
19234             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19235           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19236             break;
19237           std::swap(LHS, RHS);
19238         }
19239         Opcode = X86ISD::FMAX;
19240         break;
19241       case ISD::SETULE:
19242         // Converting this to a max would handle both negative zeros and NaNs
19243         // incorrectly, but we can swap the operands to fix both.
19244         std::swap(LHS, RHS);
19245       case ISD::SETOLT:
19246       case ISD::SETLT:
19247       case ISD::SETLE:
19248         Opcode = X86ISD::FMAX;
19249         break;
19250       }
19251     }
19252
19253     if (Opcode)
19254       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19255   }
19256
19257   EVT CondVT = Cond.getValueType();
19258   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19259       CondVT.getVectorElementType() == MVT::i1) {
19260     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19261     // lowering on AVX-512. In this case we convert it to
19262     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19263     // The same situation for all 128 and 256-bit vectors of i8 and i16
19264     EVT OpVT = LHS.getValueType();
19265     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19266         (OpVT.getVectorElementType() == MVT::i8 ||
19267          OpVT.getVectorElementType() == MVT::i16)) {
19268       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19269       DCI.AddToWorklist(Cond.getNode());
19270       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19271     }
19272   }
19273   // If this is a select between two integer constants, try to do some
19274   // optimizations.
19275   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19276     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19277       // Don't do this for crazy integer types.
19278       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19279         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19280         // so that TrueC (the true value) is larger than FalseC.
19281         bool NeedsCondInvert = false;
19282
19283         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19284             // Efficiently invertible.
19285             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
19286              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
19287               isa<ConstantSDNode>(Cond.getOperand(1))))) {
19288           NeedsCondInvert = true;
19289           std::swap(TrueC, FalseC);
19290         }
19291
19292         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
19293         if (FalseC->getAPIntValue() == 0 &&
19294             TrueC->getAPIntValue().isPowerOf2()) {
19295           if (NeedsCondInvert) // Invert the condition if needed.
19296             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19297                                DAG.getConstant(1, Cond.getValueType()));
19298
19299           // Zero extend the condition if needed.
19300           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19301
19302           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19303           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19304                              DAG.getConstant(ShAmt, MVT::i8));
19305         }
19306
19307         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19308         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19309           if (NeedsCondInvert) // Invert the condition if needed.
19310             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19311                                DAG.getConstant(1, Cond.getValueType()));
19312
19313           // Zero extend the condition if needed.
19314           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19315                              FalseC->getValueType(0), Cond);
19316           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19317                              SDValue(FalseC, 0));
19318         }
19319
19320         // Optimize cases that will turn into an LEA instruction.  This requires
19321         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19322         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19323           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19324           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19325
19326           bool isFastMultiplier = false;
19327           if (Diff < 10) {
19328             switch ((unsigned char)Diff) {
19329               default: break;
19330               case 1:  // result = add base, cond
19331               case 2:  // result = lea base(    , cond*2)
19332               case 3:  // result = lea base(cond, cond*2)
19333               case 4:  // result = lea base(    , cond*4)
19334               case 5:  // result = lea base(cond, cond*4)
19335               case 8:  // result = lea base(    , cond*8)
19336               case 9:  // result = lea base(cond, cond*8)
19337                 isFastMultiplier = true;
19338                 break;
19339             }
19340           }
19341
19342           if (isFastMultiplier) {
19343             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19344             if (NeedsCondInvert) // Invert the condition if needed.
19345               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19346                                  DAG.getConstant(1, Cond.getValueType()));
19347
19348             // Zero extend the condition if needed.
19349             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19350                                Cond);
19351             // Scale the condition by the difference.
19352             if (Diff != 1)
19353               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19354                                  DAG.getConstant(Diff, Cond.getValueType()));
19355
19356             // Add the base if non-zero.
19357             if (FalseC->getAPIntValue() != 0)
19358               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19359                                  SDValue(FalseC, 0));
19360             return Cond;
19361           }
19362         }
19363       }
19364   }
19365
19366   // Canonicalize max and min:
19367   // (x > y) ? x : y -> (x >= y) ? x : y
19368   // (x < y) ? x : y -> (x <= y) ? x : y
19369   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19370   // the need for an extra compare
19371   // against zero. e.g.
19372   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19373   // subl   %esi, %edi
19374   // testl  %edi, %edi
19375   // movl   $0, %eax
19376   // cmovgl %edi, %eax
19377   // =>
19378   // xorl   %eax, %eax
19379   // subl   %esi, $edi
19380   // cmovsl %eax, %edi
19381   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19382       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19383       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19384     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19385     switch (CC) {
19386     default: break;
19387     case ISD::SETLT:
19388     case ISD::SETGT: {
19389       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19390       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19391                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
19392       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19393     }
19394     }
19395   }
19396
19397   // Early exit check
19398   if (!TLI.isTypeLegal(VT))
19399     return SDValue();
19400
19401   // Match VSELECTs into subs with unsigned saturation.
19402   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19403       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19404       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19405        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19406     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19407
19408     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19409     // left side invert the predicate to simplify logic below.
19410     SDValue Other;
19411     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19412       Other = RHS;
19413       CC = ISD::getSetCCInverse(CC, true);
19414     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19415       Other = LHS;
19416     }
19417
19418     if (Other.getNode() && Other->getNumOperands() == 2 &&
19419         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19420       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19421       SDValue CondRHS = Cond->getOperand(1);
19422
19423       // Look for a general sub with unsigned saturation first.
19424       // x >= y ? x-y : 0 --> subus x, y
19425       // x >  y ? x-y : 0 --> subus x, y
19426       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19427           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19428         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19429
19430       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
19431         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
19432           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
19433             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
19434               // If the RHS is a constant we have to reverse the const
19435               // canonicalization.
19436               // x > C-1 ? x+-C : 0 --> subus x, C
19437               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19438                   CondRHSConst->getAPIntValue() ==
19439                       (-OpRHSConst->getAPIntValue() - 1))
19440                 return DAG.getNode(
19441                     X86ISD::SUBUS, DL, VT, OpLHS,
19442                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
19443
19444           // Another special case: If C was a sign bit, the sub has been
19445           // canonicalized into a xor.
19446           // FIXME: Would it be better to use computeKnownBits to determine
19447           //        whether it's safe to decanonicalize the xor?
19448           // x s< 0 ? x^C : 0 --> subus x, C
19449           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19450               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
19451               OpRHSConst->getAPIntValue().isSignBit())
19452             // Note that we have to rebuild the RHS constant here to ensure we
19453             // don't rely on particular values of undef lanes.
19454             return DAG.getNode(
19455                 X86ISD::SUBUS, DL, VT, OpLHS,
19456                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
19457         }
19458     }
19459   }
19460
19461   // Try to match a min/max vector operation.
19462   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19463     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19464     unsigned Opc = ret.first;
19465     bool NeedSplit = ret.second;
19466
19467     if (Opc && NeedSplit) {
19468       unsigned NumElems = VT.getVectorNumElements();
19469       // Extract the LHS vectors
19470       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19471       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19472
19473       // Extract the RHS vectors
19474       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19475       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19476
19477       // Create min/max for each subvector
19478       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19479       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19480
19481       // Merge the result
19482       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19483     } else if (Opc)
19484       return DAG.getNode(Opc, DL, VT, LHS, RHS);
19485   }
19486
19487   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19488   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19489       // Check if SETCC has already been promoted
19490       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19491       // Check that condition value type matches vselect operand type
19492       CondVT == VT) { 
19493
19494     assert(Cond.getValueType().isVector() &&
19495            "vector select expects a vector selector!");
19496
19497     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19498     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19499
19500     if (!TValIsAllOnes && !FValIsAllZeros) {
19501       // Try invert the condition if true value is not all 1s and false value
19502       // is not all 0s.
19503       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19504       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19505
19506       if (TValIsAllZeros || FValIsAllOnes) {
19507         SDValue CC = Cond.getOperand(2);
19508         ISD::CondCode NewCC =
19509           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19510                                Cond.getOperand(0).getValueType().isInteger());
19511         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19512         std::swap(LHS, RHS);
19513         TValIsAllOnes = FValIsAllOnes;
19514         FValIsAllZeros = TValIsAllZeros;
19515       }
19516     }
19517
19518     if (TValIsAllOnes || FValIsAllZeros) {
19519       SDValue Ret;
19520
19521       if (TValIsAllOnes && FValIsAllZeros)
19522         Ret = Cond;
19523       else if (TValIsAllOnes)
19524         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19525                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19526       else if (FValIsAllZeros)
19527         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19528                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19529
19530       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19531     }
19532   }
19533
19534   // Try to fold this VSELECT into a MOVSS/MOVSD
19535   if (N->getOpcode() == ISD::VSELECT &&
19536       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19537     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19538         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19539       bool CanFold = false;
19540       unsigned NumElems = Cond.getNumOperands();
19541       SDValue A = LHS;
19542       SDValue B = RHS;
19543       
19544       if (isZero(Cond.getOperand(0))) {
19545         CanFold = true;
19546
19547         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19548         // fold (vselect <0,-1> -> (movsd A, B)
19549         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19550           CanFold = isAllOnes(Cond.getOperand(i));
19551       } else if (isAllOnes(Cond.getOperand(0))) {
19552         CanFold = true;
19553         std::swap(A, B);
19554
19555         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19556         // fold (vselect <-1,0> -> (movsd B, A)
19557         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19558           CanFold = isZero(Cond.getOperand(i));
19559       }
19560
19561       if (CanFold) {
19562         if (VT == MVT::v4i32 || VT == MVT::v4f32)
19563           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19564         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19565       }
19566
19567       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19568         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19569         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19570         //                             (v2i64 (bitcast B)))))
19571         //
19572         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19573         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19574         //                             (v2f64 (bitcast B)))))
19575         //
19576         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19577         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19578         //                             (v2i64 (bitcast A)))))
19579         //
19580         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19581         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19582         //                             (v2f64 (bitcast A)))))
19583
19584         CanFold = (isZero(Cond.getOperand(0)) &&
19585                    isZero(Cond.getOperand(1)) &&
19586                    isAllOnes(Cond.getOperand(2)) &&
19587                    isAllOnes(Cond.getOperand(3)));
19588
19589         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19590             isAllOnes(Cond.getOperand(1)) &&
19591             isZero(Cond.getOperand(2)) &&
19592             isZero(Cond.getOperand(3))) {
19593           CanFold = true;
19594           std::swap(LHS, RHS);
19595         }
19596
19597         if (CanFold) {
19598           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19599           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19600           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19601           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19602                                                 NewB, DAG);
19603           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19604         }
19605       }
19606     }
19607   }
19608
19609   // If we know that this node is legal then we know that it is going to be
19610   // matched by one of the SSE/AVX BLEND instructions. These instructions only
19611   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19612   // to simplify previous instructions.
19613   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19614       !DCI.isBeforeLegalize() &&
19615       // We explicitly check against v8i16 and v16i16 because, although
19616       // they're marked as Custom, they might only be legal when Cond is a
19617       // build_vector of constants. This will be taken care in a later
19618       // condition.
19619       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19620        VT != MVT::v8i16)) {
19621     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19622
19623     // Don't optimize vector selects that map to mask-registers.
19624     if (BitWidth == 1)
19625       return SDValue();
19626
19627     // Check all uses of that condition operand to check whether it will be
19628     // consumed by non-BLEND instructions, which may depend on all bits are set
19629     // properly.
19630     for (SDNode::use_iterator I = Cond->use_begin(),
19631                               E = Cond->use_end(); I != E; ++I)
19632       if (I->getOpcode() != ISD::VSELECT)
19633         // TODO: Add other opcodes eventually lowered into BLEND.
19634         return SDValue();
19635
19636     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19637     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19638
19639     APInt KnownZero, KnownOne;
19640     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19641                                           DCI.isBeforeLegalizeOps());
19642     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
19643         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
19644       DCI.CommitTargetLoweringOpt(TLO);
19645   }
19646
19647   // We should generate an X86ISD::BLENDI from a vselect if its argument
19648   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
19649   // constants. This specific pattern gets generated when we split a
19650   // selector for a 512 bit vector in a machine without AVX512 (but with
19651   // 256-bit vectors), during legalization:
19652   //
19653   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
19654   //
19655   // Iff we find this pattern and the build_vectors are built from
19656   // constants, we translate the vselect into a shuffle_vector that we
19657   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
19658   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
19659     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
19660     if (Shuffle.getNode())
19661       return Shuffle;
19662   }
19663
19664   return SDValue();
19665 }
19666
19667 // Check whether a boolean test is testing a boolean value generated by
19668 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
19669 // code.
19670 //
19671 // Simplify the following patterns:
19672 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
19673 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
19674 // to (Op EFLAGS Cond)
19675 //
19676 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
19677 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
19678 // to (Op EFLAGS !Cond)
19679 //
19680 // where Op could be BRCOND or CMOV.
19681 //
19682 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
19683   // Quit if not CMP and SUB with its value result used.
19684   if (Cmp.getOpcode() != X86ISD::CMP &&
19685       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
19686       return SDValue();
19687
19688   // Quit if not used as a boolean value.
19689   if (CC != X86::COND_E && CC != X86::COND_NE)
19690     return SDValue();
19691
19692   // Check CMP operands. One of them should be 0 or 1 and the other should be
19693   // an SetCC or extended from it.
19694   SDValue Op1 = Cmp.getOperand(0);
19695   SDValue Op2 = Cmp.getOperand(1);
19696
19697   SDValue SetCC;
19698   const ConstantSDNode* C = nullptr;
19699   bool needOppositeCond = (CC == X86::COND_E);
19700   bool checkAgainstTrue = false; // Is it a comparison against 1?
19701
19702   if ((C = dyn_cast<ConstantSDNode>(Op1)))
19703     SetCC = Op2;
19704   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19705     SetCC = Op1;
19706   else // Quit if all operands are not constants.
19707     return SDValue();
19708
19709   if (C->getZExtValue() == 1) {
19710     needOppositeCond = !needOppositeCond;
19711     checkAgainstTrue = true;
19712   } else if (C->getZExtValue() != 0)
19713     // Quit if the constant is neither 0 or 1.
19714     return SDValue();
19715
19716   bool truncatedToBoolWithAnd = false;
19717   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19718   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19719          SetCC.getOpcode() == ISD::TRUNCATE ||
19720          SetCC.getOpcode() == ISD::AND) {
19721     if (SetCC.getOpcode() == ISD::AND) {
19722       int OpIdx = -1;
19723       ConstantSDNode *CS;
19724       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19725           CS->getZExtValue() == 1)
19726         OpIdx = 1;
19727       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19728           CS->getZExtValue() == 1)
19729         OpIdx = 0;
19730       if (OpIdx == -1)
19731         break;
19732       SetCC = SetCC.getOperand(OpIdx);
19733       truncatedToBoolWithAnd = true;
19734     } else
19735       SetCC = SetCC.getOperand(0);
19736   }
19737
19738   switch (SetCC.getOpcode()) {
19739   case X86ISD::SETCC_CARRY:
19740     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19741     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19742     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19743     // truncated to i1 using 'and'.
19744     if (checkAgainstTrue && !truncatedToBoolWithAnd)
19745       break;
19746     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19747            "Invalid use of SETCC_CARRY!");
19748     // FALL THROUGH
19749   case X86ISD::SETCC:
19750     // Set the condition code or opposite one if necessary.
19751     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19752     if (needOppositeCond)
19753       CC = X86::GetOppositeBranchCondition(CC);
19754     return SetCC.getOperand(1);
19755   case X86ISD::CMOV: {
19756     // Check whether false/true value has canonical one, i.e. 0 or 1.
19757     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19758     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19759     // Quit if true value is not a constant.
19760     if (!TVal)
19761       return SDValue();
19762     // Quit if false value is not a constant.
19763     if (!FVal) {
19764       SDValue Op = SetCC.getOperand(0);
19765       // Skip 'zext' or 'trunc' node.
19766       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19767           Op.getOpcode() == ISD::TRUNCATE)
19768         Op = Op.getOperand(0);
19769       // A special case for rdrand/rdseed, where 0 is set if false cond is
19770       // found.
19771       if ((Op.getOpcode() != X86ISD::RDRAND &&
19772            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19773         return SDValue();
19774     }
19775     // Quit if false value is not the constant 0 or 1.
19776     bool FValIsFalse = true;
19777     if (FVal && FVal->getZExtValue() != 0) {
19778       if (FVal->getZExtValue() != 1)
19779         return SDValue();
19780       // If FVal is 1, opposite cond is needed.
19781       needOppositeCond = !needOppositeCond;
19782       FValIsFalse = false;
19783     }
19784     // Quit if TVal is not the constant opposite of FVal.
19785     if (FValIsFalse && TVal->getZExtValue() != 1)
19786       return SDValue();
19787     if (!FValIsFalse && TVal->getZExtValue() != 0)
19788       return SDValue();
19789     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19790     if (needOppositeCond)
19791       CC = X86::GetOppositeBranchCondition(CC);
19792     return SetCC.getOperand(3);
19793   }
19794   }
19795
19796   return SDValue();
19797 }
19798
19799 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19800 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19801                                   TargetLowering::DAGCombinerInfo &DCI,
19802                                   const X86Subtarget *Subtarget) {
19803   SDLoc DL(N);
19804
19805   // If the flag operand isn't dead, don't touch this CMOV.
19806   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19807     return SDValue();
19808
19809   SDValue FalseOp = N->getOperand(0);
19810   SDValue TrueOp = N->getOperand(1);
19811   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19812   SDValue Cond = N->getOperand(3);
19813
19814   if (CC == X86::COND_E || CC == X86::COND_NE) {
19815     switch (Cond.getOpcode()) {
19816     default: break;
19817     case X86ISD::BSR:
19818     case X86ISD::BSF:
19819       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19820       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19821         return (CC == X86::COND_E) ? FalseOp : TrueOp;
19822     }
19823   }
19824
19825   SDValue Flags;
19826
19827   Flags = checkBoolTestSetCCCombine(Cond, CC);
19828   if (Flags.getNode() &&
19829       // Extra check as FCMOV only supports a subset of X86 cond.
19830       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19831     SDValue Ops[] = { FalseOp, TrueOp,
19832                       DAG.getConstant(CC, MVT::i8), Flags };
19833     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19834   }
19835
19836   // If this is a select between two integer constants, try to do some
19837   // optimizations.  Note that the operands are ordered the opposite of SELECT
19838   // operands.
19839   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19840     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19841       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19842       // larger than FalseC (the false value).
19843       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19844         CC = X86::GetOppositeBranchCondition(CC);
19845         std::swap(TrueC, FalseC);
19846         std::swap(TrueOp, FalseOp);
19847       }
19848
19849       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
19850       // This is efficient for any integer data type (including i8/i16) and
19851       // shift amount.
19852       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19853         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19854                            DAG.getConstant(CC, MVT::i8), Cond);
19855
19856         // Zero extend the condition if needed.
19857         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19858
19859         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19860         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19861                            DAG.getConstant(ShAmt, MVT::i8));
19862         if (N->getNumValues() == 2)  // Dead flag value?
19863           return DCI.CombineTo(N, Cond, SDValue());
19864         return Cond;
19865       }
19866
19867       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
19868       // for any integer data type, including i8/i16.
19869       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19870         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19871                            DAG.getConstant(CC, MVT::i8), Cond);
19872
19873         // Zero extend the condition if needed.
19874         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19875                            FalseC->getValueType(0), Cond);
19876         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19877                            SDValue(FalseC, 0));
19878
19879         if (N->getNumValues() == 2)  // Dead flag value?
19880           return DCI.CombineTo(N, Cond, SDValue());
19881         return Cond;
19882       }
19883
19884       // Optimize cases that will turn into an LEA instruction.  This requires
19885       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19886       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19887         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19888         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19889
19890         bool isFastMultiplier = false;
19891         if (Diff < 10) {
19892           switch ((unsigned char)Diff) {
19893           default: break;
19894           case 1:  // result = add base, cond
19895           case 2:  // result = lea base(    , cond*2)
19896           case 3:  // result = lea base(cond, cond*2)
19897           case 4:  // result = lea base(    , cond*4)
19898           case 5:  // result = lea base(cond, cond*4)
19899           case 8:  // result = lea base(    , cond*8)
19900           case 9:  // result = lea base(cond, cond*8)
19901             isFastMultiplier = true;
19902             break;
19903           }
19904         }
19905
19906         if (isFastMultiplier) {
19907           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19908           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19909                              DAG.getConstant(CC, MVT::i8), Cond);
19910           // Zero extend the condition if needed.
19911           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19912                              Cond);
19913           // Scale the condition by the difference.
19914           if (Diff != 1)
19915             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19916                                DAG.getConstant(Diff, Cond.getValueType()));
19917
19918           // Add the base if non-zero.
19919           if (FalseC->getAPIntValue() != 0)
19920             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19921                                SDValue(FalseC, 0));
19922           if (N->getNumValues() == 2)  // Dead flag value?
19923             return DCI.CombineTo(N, Cond, SDValue());
19924           return Cond;
19925         }
19926       }
19927     }
19928   }
19929
19930   // Handle these cases:
19931   //   (select (x != c), e, c) -> select (x != c), e, x),
19932   //   (select (x == c), c, e) -> select (x == c), x, e)
19933   // where the c is an integer constant, and the "select" is the combination
19934   // of CMOV and CMP.
19935   //
19936   // The rationale for this change is that the conditional-move from a constant
19937   // needs two instructions, however, conditional-move from a register needs
19938   // only one instruction.
19939   //
19940   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
19941   //  some instruction-combining opportunities. This opt needs to be
19942   //  postponed as late as possible.
19943   //
19944   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
19945     // the DCI.xxxx conditions are provided to postpone the optimization as
19946     // late as possible.
19947
19948     ConstantSDNode *CmpAgainst = nullptr;
19949     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19950         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19951         !isa<ConstantSDNode>(Cond.getOperand(0))) {
19952
19953       if (CC == X86::COND_NE &&
19954           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19955         CC = X86::GetOppositeBranchCondition(CC);
19956         std::swap(TrueOp, FalseOp);
19957       }
19958
19959       if (CC == X86::COND_E &&
19960           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19961         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19962                           DAG.getConstant(CC, MVT::i8), Cond };
19963         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
19964       }
19965     }
19966   }
19967
19968   return SDValue();
19969 }
19970
19971 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
19972                                                 const X86Subtarget *Subtarget) {
19973   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
19974   switch (IntNo) {
19975   default: return SDValue();
19976   // SSE/AVX/AVX2 blend intrinsics.
19977   case Intrinsic::x86_avx2_pblendvb:
19978   case Intrinsic::x86_avx2_pblendw:
19979   case Intrinsic::x86_avx2_pblendd_128:
19980   case Intrinsic::x86_avx2_pblendd_256:
19981     // Don't try to simplify this intrinsic if we don't have AVX2.
19982     if (!Subtarget->hasAVX2())
19983       return SDValue();
19984     // FALL-THROUGH
19985   case Intrinsic::x86_avx_blend_pd_256:
19986   case Intrinsic::x86_avx_blend_ps_256:
19987   case Intrinsic::x86_avx_blendv_pd_256:
19988   case Intrinsic::x86_avx_blendv_ps_256:
19989     // Don't try to simplify this intrinsic if we don't have AVX.
19990     if (!Subtarget->hasAVX())
19991       return SDValue();
19992     // FALL-THROUGH
19993   case Intrinsic::x86_sse41_pblendw:
19994   case Intrinsic::x86_sse41_blendpd:
19995   case Intrinsic::x86_sse41_blendps:
19996   case Intrinsic::x86_sse41_blendvps:
19997   case Intrinsic::x86_sse41_blendvpd:
19998   case Intrinsic::x86_sse41_pblendvb: {
19999     SDValue Op0 = N->getOperand(1);
20000     SDValue Op1 = N->getOperand(2);
20001     SDValue Mask = N->getOperand(3);
20002
20003     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20004     if (!Subtarget->hasSSE41())
20005       return SDValue();
20006
20007     // fold (blend A, A, Mask) -> A
20008     if (Op0 == Op1)
20009       return Op0;
20010     // fold (blend A, B, allZeros) -> A
20011     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20012       return Op0;
20013     // fold (blend A, B, allOnes) -> B
20014     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20015       return Op1;
20016     
20017     // Simplify the case where the mask is a constant i32 value.
20018     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20019       if (C->isNullValue())
20020         return Op0;
20021       if (C->isAllOnesValue())
20022         return Op1;
20023     }
20024
20025     return SDValue();
20026   }
20027
20028   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20029   case Intrinsic::x86_sse2_psrai_w:
20030   case Intrinsic::x86_sse2_psrai_d:
20031   case Intrinsic::x86_avx2_psrai_w:
20032   case Intrinsic::x86_avx2_psrai_d:
20033   case Intrinsic::x86_sse2_psra_w:
20034   case Intrinsic::x86_sse2_psra_d:
20035   case Intrinsic::x86_avx2_psra_w:
20036   case Intrinsic::x86_avx2_psra_d: {
20037     SDValue Op0 = N->getOperand(1);
20038     SDValue Op1 = N->getOperand(2);
20039     EVT VT = Op0.getValueType();
20040     assert(VT.isVector() && "Expected a vector type!");
20041
20042     if (isa<BuildVectorSDNode>(Op1))
20043       Op1 = Op1.getOperand(0);
20044
20045     if (!isa<ConstantSDNode>(Op1))
20046       return SDValue();
20047
20048     EVT SVT = VT.getVectorElementType();
20049     unsigned SVTBits = SVT.getSizeInBits();
20050
20051     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20052     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20053     uint64_t ShAmt = C.getZExtValue();
20054
20055     // Don't try to convert this shift into a ISD::SRA if the shift
20056     // count is bigger than or equal to the element size.
20057     if (ShAmt >= SVTBits)
20058       return SDValue();
20059
20060     // Trivial case: if the shift count is zero, then fold this
20061     // into the first operand.
20062     if (ShAmt == 0)
20063       return Op0;
20064
20065     // Replace this packed shift intrinsic with a target independent
20066     // shift dag node.
20067     SDValue Splat = DAG.getConstant(C, VT);
20068     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20069   }
20070   }
20071 }
20072
20073 /// PerformMulCombine - Optimize a single multiply with constant into two
20074 /// in order to implement it with two cheaper instructions, e.g.
20075 /// LEA + SHL, LEA + LEA.
20076 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20077                                  TargetLowering::DAGCombinerInfo &DCI) {
20078   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20079     return SDValue();
20080
20081   EVT VT = N->getValueType(0);
20082   if (VT != MVT::i64)
20083     return SDValue();
20084
20085   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20086   if (!C)
20087     return SDValue();
20088   uint64_t MulAmt = C->getZExtValue();
20089   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20090     return SDValue();
20091
20092   uint64_t MulAmt1 = 0;
20093   uint64_t MulAmt2 = 0;
20094   if ((MulAmt % 9) == 0) {
20095     MulAmt1 = 9;
20096     MulAmt2 = MulAmt / 9;
20097   } else if ((MulAmt % 5) == 0) {
20098     MulAmt1 = 5;
20099     MulAmt2 = MulAmt / 5;
20100   } else if ((MulAmt % 3) == 0) {
20101     MulAmt1 = 3;
20102     MulAmt2 = MulAmt / 3;
20103   }
20104   if (MulAmt2 &&
20105       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20106     SDLoc DL(N);
20107
20108     if (isPowerOf2_64(MulAmt2) &&
20109         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20110       // If second multiplifer is pow2, issue it first. We want the multiply by
20111       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20112       // is an add.
20113       std::swap(MulAmt1, MulAmt2);
20114
20115     SDValue NewMul;
20116     if (isPowerOf2_64(MulAmt1))
20117       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20118                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20119     else
20120       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20121                            DAG.getConstant(MulAmt1, VT));
20122
20123     if (isPowerOf2_64(MulAmt2))
20124       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20125                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20126     else
20127       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20128                            DAG.getConstant(MulAmt2, VT));
20129
20130     // Do not add new nodes to DAG combiner worklist.
20131     DCI.CombineTo(N, NewMul, false);
20132   }
20133   return SDValue();
20134 }
20135
20136 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20137   SDValue N0 = N->getOperand(0);
20138   SDValue N1 = N->getOperand(1);
20139   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20140   EVT VT = N0.getValueType();
20141
20142   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20143   // since the result of setcc_c is all zero's or all ones.
20144   if (VT.isInteger() && !VT.isVector() &&
20145       N1C && N0.getOpcode() == ISD::AND &&
20146       N0.getOperand(1).getOpcode() == ISD::Constant) {
20147     SDValue N00 = N0.getOperand(0);
20148     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20149         ((N00.getOpcode() == ISD::ANY_EXTEND ||
20150           N00.getOpcode() == ISD::ZERO_EXTEND) &&
20151          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20152       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20153       APInt ShAmt = N1C->getAPIntValue();
20154       Mask = Mask.shl(ShAmt);
20155       if (Mask != 0)
20156         return DAG.getNode(ISD::AND, SDLoc(N), VT,
20157                            N00, DAG.getConstant(Mask, VT));
20158     }
20159   }
20160
20161   // Hardware support for vector shifts is sparse which makes us scalarize the
20162   // vector operations in many cases. Also, on sandybridge ADD is faster than
20163   // shl.
20164   // (shl V, 1) -> add V,V
20165   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20166     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
20167       assert(N0.getValueType().isVector() && "Invalid vector shift type");
20168       // We shift all of the values by one. In many cases we do not have
20169       // hardware support for this operation. This is better expressed as an ADD
20170       // of two values.
20171       if (N1SplatC->getZExtValue() == 1)
20172         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20173     }
20174
20175   return SDValue();
20176 }
20177
20178 /// \brief Returns a vector of 0s if the node in input is a vector logical
20179 /// shift by a constant amount which is known to be bigger than or equal
20180 /// to the vector element size in bits.
20181 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20182                                       const X86Subtarget *Subtarget) {
20183   EVT VT = N->getValueType(0);
20184
20185   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20186       (!Subtarget->hasInt256() ||
20187        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20188     return SDValue();
20189
20190   SDValue Amt = N->getOperand(1);
20191   SDLoc DL(N);
20192   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20193     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
20194       APInt ShiftAmt = AmtSplat->getAPIntValue();
20195       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20196
20197       // SSE2/AVX2 logical shifts always return a vector of 0s
20198       // if the shift amount is bigger than or equal to
20199       // the element size. The constant shift amount will be
20200       // encoded as a 8-bit immediate.
20201       if (ShiftAmt.trunc(8).uge(MaxAmount))
20202         return getZeroVector(VT, Subtarget, DAG, DL);
20203     }
20204
20205   return SDValue();
20206 }
20207
20208 /// PerformShiftCombine - Combine shifts.
20209 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20210                                    TargetLowering::DAGCombinerInfo &DCI,
20211                                    const X86Subtarget *Subtarget) {
20212   if (N->getOpcode() == ISD::SHL) {
20213     SDValue V = PerformSHLCombine(N, DAG);
20214     if (V.getNode()) return V;
20215   }
20216
20217   if (N->getOpcode() != ISD::SRA) {
20218     // Try to fold this logical shift into a zero vector.
20219     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20220     if (V.getNode()) return V;
20221   }
20222
20223   return SDValue();
20224 }
20225
20226 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
20227 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20228 // and friends.  Likewise for OR -> CMPNEQSS.
20229 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20230                             TargetLowering::DAGCombinerInfo &DCI,
20231                             const X86Subtarget *Subtarget) {
20232   unsigned opcode;
20233
20234   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20235   // we're requiring SSE2 for both.
20236   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20237     SDValue N0 = N->getOperand(0);
20238     SDValue N1 = N->getOperand(1);
20239     SDValue CMP0 = N0->getOperand(1);
20240     SDValue CMP1 = N1->getOperand(1);
20241     SDLoc DL(N);
20242
20243     // The SETCCs should both refer to the same CMP.
20244     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20245       return SDValue();
20246
20247     SDValue CMP00 = CMP0->getOperand(0);
20248     SDValue CMP01 = CMP0->getOperand(1);
20249     EVT     VT    = CMP00.getValueType();
20250
20251     if (VT == MVT::f32 || VT == MVT::f64) {
20252       bool ExpectingFlags = false;
20253       // Check for any users that want flags:
20254       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20255            !ExpectingFlags && UI != UE; ++UI)
20256         switch (UI->getOpcode()) {
20257         default:
20258         case ISD::BR_CC:
20259         case ISD::BRCOND:
20260         case ISD::SELECT:
20261           ExpectingFlags = true;
20262           break;
20263         case ISD::CopyToReg:
20264         case ISD::SIGN_EXTEND:
20265         case ISD::ZERO_EXTEND:
20266         case ISD::ANY_EXTEND:
20267           break;
20268         }
20269
20270       if (!ExpectingFlags) {
20271         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20272         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20273
20274         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20275           X86::CondCode tmp = cc0;
20276           cc0 = cc1;
20277           cc1 = tmp;
20278         }
20279
20280         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
20281             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20282           // FIXME: need symbolic constants for these magic numbers.
20283           // See X86ATTInstPrinter.cpp:printSSECC().
20284           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20285           if (Subtarget->hasAVX512()) {
20286             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20287                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
20288             if (N->getValueType(0) != MVT::i1)
20289               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20290                                  FSetCC);
20291             return FSetCC;
20292           }
20293           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20294                                               CMP00.getValueType(), CMP00, CMP01,
20295                                               DAG.getConstant(x86cc, MVT::i8));
20296
20297           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20298           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20299
20300           if (is64BitFP && !Subtarget->is64Bit()) {
20301             // On a 32-bit target, we cannot bitcast the 64-bit float to a
20302             // 64-bit integer, since that's not a legal type. Since
20303             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20304             // bits, but can do this little dance to extract the lowest 32 bits
20305             // and work with those going forward.
20306             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20307                                            OnesOrZeroesF);
20308             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20309                                            Vector64);
20310             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20311                                         Vector32, DAG.getIntPtrConstant(0));
20312             IntVT = MVT::i32;
20313           }
20314
20315           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20316           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20317                                       DAG.getConstant(1, IntVT));
20318           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20319           return OneBitOfTruth;
20320         }
20321       }
20322     }
20323   }
20324   return SDValue();
20325 }
20326
20327 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20328 /// so it can be folded inside ANDNP.
20329 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20330   EVT VT = N->getValueType(0);
20331
20332   // Match direct AllOnes for 128 and 256-bit vectors
20333   if (ISD::isBuildVectorAllOnes(N))
20334     return true;
20335
20336   // Look through a bit convert.
20337   if (N->getOpcode() == ISD::BITCAST)
20338     N = N->getOperand(0).getNode();
20339
20340   // Sometimes the operand may come from a insert_subvector building a 256-bit
20341   // allones vector
20342   if (VT.is256BitVector() &&
20343       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20344     SDValue V1 = N->getOperand(0);
20345     SDValue V2 = N->getOperand(1);
20346
20347     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20348         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20349         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20350         ISD::isBuildVectorAllOnes(V2.getNode()))
20351       return true;
20352   }
20353
20354   return false;
20355 }
20356
20357 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20358 // register. In most cases we actually compare or select YMM-sized registers
20359 // and mixing the two types creates horrible code. This method optimizes
20360 // some of the transition sequences.
20361 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20362                                  TargetLowering::DAGCombinerInfo &DCI,
20363                                  const X86Subtarget *Subtarget) {
20364   EVT VT = N->getValueType(0);
20365   if (!VT.is256BitVector())
20366     return SDValue();
20367
20368   assert((N->getOpcode() == ISD::ANY_EXTEND ||
20369           N->getOpcode() == ISD::ZERO_EXTEND ||
20370           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20371
20372   SDValue Narrow = N->getOperand(0);
20373   EVT NarrowVT = Narrow->getValueType(0);
20374   if (!NarrowVT.is128BitVector())
20375     return SDValue();
20376
20377   if (Narrow->getOpcode() != ISD::XOR &&
20378       Narrow->getOpcode() != ISD::AND &&
20379       Narrow->getOpcode() != ISD::OR)
20380     return SDValue();
20381
20382   SDValue N0  = Narrow->getOperand(0);
20383   SDValue N1  = Narrow->getOperand(1);
20384   SDLoc DL(Narrow);
20385
20386   // The Left side has to be a trunc.
20387   if (N0.getOpcode() != ISD::TRUNCATE)
20388     return SDValue();
20389
20390   // The type of the truncated inputs.
20391   EVT WideVT = N0->getOperand(0)->getValueType(0);
20392   if (WideVT != VT)
20393     return SDValue();
20394
20395   // The right side has to be a 'trunc' or a constant vector.
20396   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20397   ConstantSDNode *RHSConstSplat = nullptr;
20398   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
20399     RHSConstSplat = RHSBV->getConstantSplatNode();
20400   if (!RHSTrunc && !RHSConstSplat)
20401     return SDValue();
20402
20403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20404
20405   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20406     return SDValue();
20407
20408   // Set N0 and N1 to hold the inputs to the new wide operation.
20409   N0 = N0->getOperand(0);
20410   if (RHSConstSplat) {
20411     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20412                      SDValue(RHSConstSplat, 0));
20413     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20414     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20415   } else if (RHSTrunc) {
20416     N1 = N1->getOperand(0);
20417   }
20418
20419   // Generate the wide operation.
20420   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20421   unsigned Opcode = N->getOpcode();
20422   switch (Opcode) {
20423   case ISD::ANY_EXTEND:
20424     return Op;
20425   case ISD::ZERO_EXTEND: {
20426     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20427     APInt Mask = APInt::getAllOnesValue(InBits);
20428     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20429     return DAG.getNode(ISD::AND, DL, VT,
20430                        Op, DAG.getConstant(Mask, VT));
20431   }
20432   case ISD::SIGN_EXTEND:
20433     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20434                        Op, DAG.getValueType(NarrowVT));
20435   default:
20436     llvm_unreachable("Unexpected opcode");
20437   }
20438 }
20439
20440 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20441                                  TargetLowering::DAGCombinerInfo &DCI,
20442                                  const X86Subtarget *Subtarget) {
20443   EVT VT = N->getValueType(0);
20444   if (DCI.isBeforeLegalizeOps())
20445     return SDValue();
20446
20447   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20448   if (R.getNode())
20449     return R;
20450
20451   // Create BEXTR instructions
20452   // BEXTR is ((X >> imm) & (2**size-1))
20453   if (VT == MVT::i32 || VT == MVT::i64) {
20454     SDValue N0 = N->getOperand(0);
20455     SDValue N1 = N->getOperand(1);
20456     SDLoc DL(N);
20457
20458     // Check for BEXTR.
20459     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20460         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20461       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20462       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20463       if (MaskNode && ShiftNode) {
20464         uint64_t Mask = MaskNode->getZExtValue();
20465         uint64_t Shift = ShiftNode->getZExtValue();
20466         if (isMask_64(Mask)) {
20467           uint64_t MaskSize = CountPopulation_64(Mask);
20468           if (Shift + MaskSize <= VT.getSizeInBits())
20469             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20470                                DAG.getConstant(Shift | (MaskSize << 8), VT));
20471         }
20472       }
20473     } // BEXTR
20474
20475     return SDValue();
20476   }
20477
20478   // Want to form ANDNP nodes:
20479   // 1) In the hopes of then easily combining them with OR and AND nodes
20480   //    to form PBLEND/PSIGN.
20481   // 2) To match ANDN packed intrinsics
20482   if (VT != MVT::v2i64 && VT != MVT::v4i64)
20483     return SDValue();
20484
20485   SDValue N0 = N->getOperand(0);
20486   SDValue N1 = N->getOperand(1);
20487   SDLoc DL(N);
20488
20489   // Check LHS for vnot
20490   if (N0.getOpcode() == ISD::XOR &&
20491       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20492       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20493     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20494
20495   // Check RHS for vnot
20496   if (N1.getOpcode() == ISD::XOR &&
20497       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20498       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20499     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20500
20501   return SDValue();
20502 }
20503
20504 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20505                                 TargetLowering::DAGCombinerInfo &DCI,
20506                                 const X86Subtarget *Subtarget) {
20507   if (DCI.isBeforeLegalizeOps())
20508     return SDValue();
20509
20510   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20511   if (R.getNode())
20512     return R;
20513
20514   SDValue N0 = N->getOperand(0);
20515   SDValue N1 = N->getOperand(1);
20516   EVT VT = N->getValueType(0);
20517
20518   // look for psign/blend
20519   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20520     if (!Subtarget->hasSSSE3() ||
20521         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20522       return SDValue();
20523
20524     // Canonicalize pandn to RHS
20525     if (N0.getOpcode() == X86ISD::ANDNP)
20526       std::swap(N0, N1);
20527     // or (and (m, y), (pandn m, x))
20528     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20529       SDValue Mask = N1.getOperand(0);
20530       SDValue X    = N1.getOperand(1);
20531       SDValue Y;
20532       if (N0.getOperand(0) == Mask)
20533         Y = N0.getOperand(1);
20534       if (N0.getOperand(1) == Mask)
20535         Y = N0.getOperand(0);
20536
20537       // Check to see if the mask appeared in both the AND and ANDNP and
20538       if (!Y.getNode())
20539         return SDValue();
20540
20541       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20542       // Look through mask bitcast.
20543       if (Mask.getOpcode() == ISD::BITCAST)
20544         Mask = Mask.getOperand(0);
20545       if (X.getOpcode() == ISD::BITCAST)
20546         X = X.getOperand(0);
20547       if (Y.getOpcode() == ISD::BITCAST)
20548         Y = Y.getOperand(0);
20549
20550       EVT MaskVT = Mask.getValueType();
20551
20552       // Validate that the Mask operand is a vector sra node.
20553       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20554       // there is no psrai.b
20555       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20556       unsigned SraAmt = ~0;
20557       if (Mask.getOpcode() == ISD::SRA) {
20558         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
20559           if (auto *AmtConst = AmtBV->getConstantSplatNode())
20560             SraAmt = AmtConst->getZExtValue();
20561       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20562         SDValue SraC = Mask.getOperand(1);
20563         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
20564       }
20565       if ((SraAmt + 1) != EltBits)
20566         return SDValue();
20567
20568       SDLoc DL(N);
20569
20570       // Now we know we at least have a plendvb with the mask val.  See if
20571       // we can form a psignb/w/d.
20572       // psign = x.type == y.type == mask.type && y = sub(0, x);
20573       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20574           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20575           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20576         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20577                "Unsupported VT for PSIGN");
20578         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20579         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20580       }
20581       // PBLENDVB only available on SSE 4.1
20582       if (!Subtarget->hasSSE41())
20583         return SDValue();
20584
20585       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20586
20587       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20588       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20589       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20590       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20591       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20592     }
20593   }
20594
20595   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20596     return SDValue();
20597
20598   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20599   MachineFunction &MF = DAG.getMachineFunction();
20600   bool OptForSize = MF.getFunction()->getAttributes().
20601     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20602
20603   // SHLD/SHRD instructions have lower register pressure, but on some
20604   // platforms they have higher latency than the equivalent
20605   // series of shifts/or that would otherwise be generated.
20606   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20607   // have higher latencies and we are not optimizing for size.
20608   if (!OptForSize && Subtarget->isSHLDSlow())
20609     return SDValue();
20610
20611   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20612     std::swap(N0, N1);
20613   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20614     return SDValue();
20615   if (!N0.hasOneUse() || !N1.hasOneUse())
20616     return SDValue();
20617
20618   SDValue ShAmt0 = N0.getOperand(1);
20619   if (ShAmt0.getValueType() != MVT::i8)
20620     return SDValue();
20621   SDValue ShAmt1 = N1.getOperand(1);
20622   if (ShAmt1.getValueType() != MVT::i8)
20623     return SDValue();
20624   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20625     ShAmt0 = ShAmt0.getOperand(0);
20626   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20627     ShAmt1 = ShAmt1.getOperand(0);
20628
20629   SDLoc DL(N);
20630   unsigned Opc = X86ISD::SHLD;
20631   SDValue Op0 = N0.getOperand(0);
20632   SDValue Op1 = N1.getOperand(0);
20633   if (ShAmt0.getOpcode() == ISD::SUB) {
20634     Opc = X86ISD::SHRD;
20635     std::swap(Op0, Op1);
20636     std::swap(ShAmt0, ShAmt1);
20637   }
20638
20639   unsigned Bits = VT.getSizeInBits();
20640   if (ShAmt1.getOpcode() == ISD::SUB) {
20641     SDValue Sum = ShAmt1.getOperand(0);
20642     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
20643       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
20644       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
20645         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
20646       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
20647         return DAG.getNode(Opc, DL, VT,
20648                            Op0, Op1,
20649                            DAG.getNode(ISD::TRUNCATE, DL,
20650                                        MVT::i8, ShAmt0));
20651     }
20652   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
20653     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
20654     if (ShAmt0C &&
20655         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
20656       return DAG.getNode(Opc, DL, VT,
20657                          N0.getOperand(0), N1.getOperand(0),
20658                          DAG.getNode(ISD::TRUNCATE, DL,
20659                                        MVT::i8, ShAmt0));
20660   }
20661
20662   return SDValue();
20663 }
20664
20665 // Generate NEG and CMOV for integer abs.
20666 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
20667   EVT VT = N->getValueType(0);
20668
20669   // Since X86 does not have CMOV for 8-bit integer, we don't convert
20670   // 8-bit integer abs to NEG and CMOV.
20671   if (VT.isInteger() && VT.getSizeInBits() == 8)
20672     return SDValue();
20673
20674   SDValue N0 = N->getOperand(0);
20675   SDValue N1 = N->getOperand(1);
20676   SDLoc DL(N);
20677
20678   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
20679   // and change it to SUB and CMOV.
20680   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
20681       N0.getOpcode() == ISD::ADD &&
20682       N0.getOperand(1) == N1 &&
20683       N1.getOpcode() == ISD::SRA &&
20684       N1.getOperand(0) == N0.getOperand(0))
20685     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
20686       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
20687         // Generate SUB & CMOV.
20688         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
20689                                   DAG.getConstant(0, VT), N0.getOperand(0));
20690
20691         SDValue Ops[] = { N0.getOperand(0), Neg,
20692                           DAG.getConstant(X86::COND_GE, MVT::i8),
20693                           SDValue(Neg.getNode(), 1) };
20694         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
20695       }
20696   return SDValue();
20697 }
20698
20699 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20700 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20701                                  TargetLowering::DAGCombinerInfo &DCI,
20702                                  const X86Subtarget *Subtarget) {
20703   if (DCI.isBeforeLegalizeOps())
20704     return SDValue();
20705
20706   if (Subtarget->hasCMov()) {
20707     SDValue RV = performIntegerAbsCombine(N, DAG);
20708     if (RV.getNode())
20709       return RV;
20710   }
20711
20712   return SDValue();
20713 }
20714
20715 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20716 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20717                                   TargetLowering::DAGCombinerInfo &DCI,
20718                                   const X86Subtarget *Subtarget) {
20719   LoadSDNode *Ld = cast<LoadSDNode>(N);
20720   EVT RegVT = Ld->getValueType(0);
20721   EVT MemVT = Ld->getMemoryVT();
20722   SDLoc dl(Ld);
20723   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20724   unsigned RegSz = RegVT.getSizeInBits();
20725
20726   // On Sandybridge unaligned 256bit loads are inefficient.
20727   ISD::LoadExtType Ext = Ld->getExtensionType();
20728   unsigned Alignment = Ld->getAlignment();
20729   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20730   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20731       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20732     unsigned NumElems = RegVT.getVectorNumElements();
20733     if (NumElems < 2)
20734       return SDValue();
20735
20736     SDValue Ptr = Ld->getBasePtr();
20737     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20738
20739     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20740                                   NumElems/2);
20741     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20742                                 Ld->getPointerInfo(), Ld->isVolatile(),
20743                                 Ld->isNonTemporal(), Ld->isInvariant(),
20744                                 Alignment);
20745     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20746     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20747                                 Ld->getPointerInfo(), Ld->isVolatile(),
20748                                 Ld->isNonTemporal(), Ld->isInvariant(),
20749                                 std::min(16U, Alignment));
20750     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20751                              Load1.getValue(1),
20752                              Load2.getValue(1));
20753
20754     SDValue NewVec = DAG.getUNDEF(RegVT);
20755     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20756     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20757     return DCI.CombineTo(N, NewVec, TF, true);
20758   }
20759
20760   // If this is a vector EXT Load then attempt to optimize it using a
20761   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20762   // expansion is still better than scalar code.
20763   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20764   // emit a shuffle and a arithmetic shift.
20765   // TODO: It is possible to support ZExt by zeroing the undef values
20766   // during the shuffle phase or after the shuffle.
20767   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20768       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20769     assert(MemVT != RegVT && "Cannot extend to the same type");
20770     assert(MemVT.isVector() && "Must load a vector from memory");
20771
20772     unsigned NumElems = RegVT.getVectorNumElements();
20773     unsigned MemSz = MemVT.getSizeInBits();
20774     assert(RegSz > MemSz && "Register size must be greater than the mem size");
20775
20776     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20777       return SDValue();
20778
20779     // All sizes must be a power of two.
20780     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20781       return SDValue();
20782
20783     // Attempt to load the original value using scalar loads.
20784     // Find the largest scalar type that divides the total loaded size.
20785     MVT SclrLoadTy = MVT::i8;
20786     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20787          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20788       MVT Tp = (MVT::SimpleValueType)tp;
20789       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20790         SclrLoadTy = Tp;
20791       }
20792     }
20793
20794     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20795     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20796         (64 <= MemSz))
20797       SclrLoadTy = MVT::f64;
20798
20799     // Calculate the number of scalar loads that we need to perform
20800     // in order to load our vector from memory.
20801     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20802     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20803       return SDValue();
20804
20805     unsigned loadRegZize = RegSz;
20806     if (Ext == ISD::SEXTLOAD && RegSz == 256)
20807       loadRegZize /= 2;
20808
20809     // Represent our vector as a sequence of elements which are the
20810     // largest scalar that we can load.
20811     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20812       loadRegZize/SclrLoadTy.getSizeInBits());
20813
20814     // Represent the data using the same element type that is stored in
20815     // memory. In practice, we ''widen'' MemVT.
20816     EVT WideVecVT =
20817           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20818                        loadRegZize/MemVT.getScalarType().getSizeInBits());
20819
20820     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20821       "Invalid vector type");
20822
20823     // We can't shuffle using an illegal type.
20824     if (!TLI.isTypeLegal(WideVecVT))
20825       return SDValue();
20826
20827     SmallVector<SDValue, 8> Chains;
20828     SDValue Ptr = Ld->getBasePtr();
20829     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20830                                         TLI.getPointerTy());
20831     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20832
20833     for (unsigned i = 0; i < NumLoads; ++i) {
20834       // Perform a single load.
20835       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20836                                        Ptr, Ld->getPointerInfo(),
20837                                        Ld->isVolatile(), Ld->isNonTemporal(),
20838                                        Ld->isInvariant(), Ld->getAlignment());
20839       Chains.push_back(ScalarLoad.getValue(1));
20840       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20841       // another round of DAGCombining.
20842       if (i == 0)
20843         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20844       else
20845         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20846                           ScalarLoad, DAG.getIntPtrConstant(i));
20847
20848       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20849     }
20850
20851     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20852
20853     // Bitcast the loaded value to a vector of the original element type, in
20854     // the size of the target vector type.
20855     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20856     unsigned SizeRatio = RegSz/MemSz;
20857
20858     if (Ext == ISD::SEXTLOAD) {
20859       // If we have SSE4.1 we can directly emit a VSEXT node.
20860       if (Subtarget->hasSSE41()) {
20861         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20862         return DCI.CombineTo(N, Sext, TF, true);
20863       }
20864
20865       // Otherwise we'll shuffle the small elements in the high bits of the
20866       // larger type and perform an arithmetic shift. If the shift is not legal
20867       // it's better to scalarize.
20868       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20869         return SDValue();
20870
20871       // Redistribute the loaded elements into the different locations.
20872       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20873       for (unsigned i = 0; i != NumElems; ++i)
20874         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20875
20876       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20877                                            DAG.getUNDEF(WideVecVT),
20878                                            &ShuffleVec[0]);
20879
20880       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20881
20882       // Build the arithmetic shift.
20883       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
20884                      MemVT.getVectorElementType().getSizeInBits();
20885       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
20886                           DAG.getConstant(Amt, RegVT));
20887
20888       return DCI.CombineTo(N, Shuff, TF, true);
20889     }
20890
20891     // Redistribute the loaded elements into the different locations.
20892     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20893     for (unsigned i = 0; i != NumElems; ++i)
20894       ShuffleVec[i*SizeRatio] = i;
20895
20896     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20897                                          DAG.getUNDEF(WideVecVT),
20898                                          &ShuffleVec[0]);
20899
20900     // Bitcast to the requested type.
20901     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20902     // Replace the original load with the new sequence
20903     // and return the new chain.
20904     return DCI.CombineTo(N, Shuff, TF, true);
20905   }
20906
20907   return SDValue();
20908 }
20909
20910 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
20911 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
20912                                    const X86Subtarget *Subtarget) {
20913   StoreSDNode *St = cast<StoreSDNode>(N);
20914   EVT VT = St->getValue().getValueType();
20915   EVT StVT = St->getMemoryVT();
20916   SDLoc dl(St);
20917   SDValue StoredVal = St->getOperand(1);
20918   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20919
20920   // If we are saving a concatenation of two XMM registers, perform two stores.
20921   // On Sandy Bridge, 256-bit memory operations are executed by two
20922   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
20923   // memory  operation.
20924   unsigned Alignment = St->getAlignment();
20925   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
20926   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
20927       StVT == VT && !IsAligned) {
20928     unsigned NumElems = VT.getVectorNumElements();
20929     if (NumElems < 2)
20930       return SDValue();
20931
20932     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
20933     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
20934
20935     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
20936     SDValue Ptr0 = St->getBasePtr();
20937     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
20938
20939     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
20940                                 St->getPointerInfo(), St->isVolatile(),
20941                                 St->isNonTemporal(), Alignment);
20942     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
20943                                 St->getPointerInfo(), St->isVolatile(),
20944                                 St->isNonTemporal(),
20945                                 std::min(16U, Alignment));
20946     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20947   }
20948
20949   // Optimize trunc store (of multiple scalars) to shuffle and store.
20950   // First, pack all of the elements in one place. Next, store to memory
20951   // in fewer chunks.
20952   if (St->isTruncatingStore() && VT.isVector()) {
20953     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20954     unsigned NumElems = VT.getVectorNumElements();
20955     assert(StVT != VT && "Cannot truncate to the same type");
20956     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20957     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20958
20959     // From, To sizes and ElemCount must be pow of two
20960     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20961     // We are going to use the original vector elt for storing.
20962     // Accumulated smaller vector elements must be a multiple of the store size.
20963     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
20964
20965     unsigned SizeRatio  = FromSz / ToSz;
20966
20967     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
20968
20969     // Create a type on which we perform the shuffle
20970     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
20971             StVT.getScalarType(), NumElems*SizeRatio);
20972
20973     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
20974
20975     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
20976     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20977     for (unsigned i = 0; i != NumElems; ++i)
20978       ShuffleVec[i] = i * SizeRatio;
20979
20980     // Can't shuffle using an illegal type.
20981     if (!TLI.isTypeLegal(WideVecVT))
20982       return SDValue();
20983
20984     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
20985                                          DAG.getUNDEF(WideVecVT),
20986                                          &ShuffleVec[0]);
20987     // At this point all of the data is stored at the bottom of the
20988     // register. We now need to save it to mem.
20989
20990     // Find the largest store unit
20991     MVT StoreType = MVT::i8;
20992     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20993          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20994       MVT Tp = (MVT::SimpleValueType)tp;
20995       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
20996         StoreType = Tp;
20997     }
20998
20999     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21000     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21001         (64 <= NumElems * ToSz))
21002       StoreType = MVT::f64;
21003
21004     // Bitcast the original vector into a vector of store-size units
21005     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21006             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21007     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21008     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21009     SmallVector<SDValue, 8> Chains;
21010     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21011                                         TLI.getPointerTy());
21012     SDValue Ptr = St->getBasePtr();
21013
21014     // Perform one or more big stores into memory.
21015     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21016       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21017                                    StoreType, ShuffWide,
21018                                    DAG.getIntPtrConstant(i));
21019       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21020                                 St->getPointerInfo(), St->isVolatile(),
21021                                 St->isNonTemporal(), St->getAlignment());
21022       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21023       Chains.push_back(Ch);
21024     }
21025
21026     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21027   }
21028
21029   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21030   // the FP state in cases where an emms may be missing.
21031   // A preferable solution to the general problem is to figure out the right
21032   // places to insert EMMS.  This qualifies as a quick hack.
21033
21034   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21035   if (VT.getSizeInBits() != 64)
21036     return SDValue();
21037
21038   const Function *F = DAG.getMachineFunction().getFunction();
21039   bool NoImplicitFloatOps = F->getAttributes().
21040     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21041   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21042                      && Subtarget->hasSSE2();
21043   if ((VT.isVector() ||
21044        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21045       isa<LoadSDNode>(St->getValue()) &&
21046       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21047       St->getChain().hasOneUse() && !St->isVolatile()) {
21048     SDNode* LdVal = St->getValue().getNode();
21049     LoadSDNode *Ld = nullptr;
21050     int TokenFactorIndex = -1;
21051     SmallVector<SDValue, 8> Ops;
21052     SDNode* ChainVal = St->getChain().getNode();
21053     // Must be a store of a load.  We currently handle two cases:  the load
21054     // is a direct child, and it's under an intervening TokenFactor.  It is
21055     // possible to dig deeper under nested TokenFactors.
21056     if (ChainVal == LdVal)
21057       Ld = cast<LoadSDNode>(St->getChain());
21058     else if (St->getValue().hasOneUse() &&
21059              ChainVal->getOpcode() == ISD::TokenFactor) {
21060       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21061         if (ChainVal->getOperand(i).getNode() == LdVal) {
21062           TokenFactorIndex = i;
21063           Ld = cast<LoadSDNode>(St->getValue());
21064         } else
21065           Ops.push_back(ChainVal->getOperand(i));
21066       }
21067     }
21068
21069     if (!Ld || !ISD::isNormalLoad(Ld))
21070       return SDValue();
21071
21072     // If this is not the MMX case, i.e. we are just turning i64 load/store
21073     // into f64 load/store, avoid the transformation if there are multiple
21074     // uses of the loaded value.
21075     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21076       return SDValue();
21077
21078     SDLoc LdDL(Ld);
21079     SDLoc StDL(N);
21080     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21081     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21082     // pair instead.
21083     if (Subtarget->is64Bit() || F64IsLegal) {
21084       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21085       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21086                                   Ld->getPointerInfo(), Ld->isVolatile(),
21087                                   Ld->isNonTemporal(), Ld->isInvariant(),
21088                                   Ld->getAlignment());
21089       SDValue NewChain = NewLd.getValue(1);
21090       if (TokenFactorIndex != -1) {
21091         Ops.push_back(NewChain);
21092         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21093       }
21094       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21095                           St->getPointerInfo(),
21096                           St->isVolatile(), St->isNonTemporal(),
21097                           St->getAlignment());
21098     }
21099
21100     // Otherwise, lower to two pairs of 32-bit loads / stores.
21101     SDValue LoAddr = Ld->getBasePtr();
21102     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21103                                  DAG.getConstant(4, MVT::i32));
21104
21105     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21106                                Ld->getPointerInfo(),
21107                                Ld->isVolatile(), Ld->isNonTemporal(),
21108                                Ld->isInvariant(), Ld->getAlignment());
21109     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21110                                Ld->getPointerInfo().getWithOffset(4),
21111                                Ld->isVolatile(), Ld->isNonTemporal(),
21112                                Ld->isInvariant(),
21113                                MinAlign(Ld->getAlignment(), 4));
21114
21115     SDValue NewChain = LoLd.getValue(1);
21116     if (TokenFactorIndex != -1) {
21117       Ops.push_back(LoLd);
21118       Ops.push_back(HiLd);
21119       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21120     }
21121
21122     LoAddr = St->getBasePtr();
21123     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21124                          DAG.getConstant(4, MVT::i32));
21125
21126     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21127                                 St->getPointerInfo(),
21128                                 St->isVolatile(), St->isNonTemporal(),
21129                                 St->getAlignment());
21130     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21131                                 St->getPointerInfo().getWithOffset(4),
21132                                 St->isVolatile(),
21133                                 St->isNonTemporal(),
21134                                 MinAlign(St->getAlignment(), 4));
21135     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21136   }
21137   return SDValue();
21138 }
21139
21140 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21141 /// and return the operands for the horizontal operation in LHS and RHS.  A
21142 /// horizontal operation performs the binary operation on successive elements
21143 /// of its first operand, then on successive elements of its second operand,
21144 /// returning the resulting values in a vector.  For example, if
21145 ///   A = < float a0, float a1, float a2, float a3 >
21146 /// and
21147 ///   B = < float b0, float b1, float b2, float b3 >
21148 /// then the result of doing a horizontal operation on A and B is
21149 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21150 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21151 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21152 /// set to A, RHS to B, and the routine returns 'true'.
21153 /// Note that the binary operation should have the property that if one of the
21154 /// operands is UNDEF then the result is UNDEF.
21155 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21156   // Look for the following pattern: if
21157   //   A = < float a0, float a1, float a2, float a3 >
21158   //   B = < float b0, float b1, float b2, float b3 >
21159   // and
21160   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21161   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21162   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21163   // which is A horizontal-op B.
21164
21165   // At least one of the operands should be a vector shuffle.
21166   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21167       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21168     return false;
21169
21170   MVT VT = LHS.getSimpleValueType();
21171
21172   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21173          "Unsupported vector type for horizontal add/sub");
21174
21175   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21176   // operate independently on 128-bit lanes.
21177   unsigned NumElts = VT.getVectorNumElements();
21178   unsigned NumLanes = VT.getSizeInBits()/128;
21179   unsigned NumLaneElts = NumElts / NumLanes;
21180   assert((NumLaneElts % 2 == 0) &&
21181          "Vector type should have an even number of elements in each lane");
21182   unsigned HalfLaneElts = NumLaneElts/2;
21183
21184   // View LHS in the form
21185   //   LHS = VECTOR_SHUFFLE A, B, LMask
21186   // If LHS is not a shuffle then pretend it is the shuffle
21187   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21188   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21189   // type VT.
21190   SDValue A, B;
21191   SmallVector<int, 16> LMask(NumElts);
21192   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21193     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21194       A = LHS.getOperand(0);
21195     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21196       B = LHS.getOperand(1);
21197     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21198     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21199   } else {
21200     if (LHS.getOpcode() != ISD::UNDEF)
21201       A = LHS;
21202     for (unsigned i = 0; i != NumElts; ++i)
21203       LMask[i] = i;
21204   }
21205
21206   // Likewise, view RHS in the form
21207   //   RHS = VECTOR_SHUFFLE C, D, RMask
21208   SDValue C, D;
21209   SmallVector<int, 16> RMask(NumElts);
21210   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21211     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21212       C = RHS.getOperand(0);
21213     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21214       D = RHS.getOperand(1);
21215     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21216     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21217   } else {
21218     if (RHS.getOpcode() != ISD::UNDEF)
21219       C = RHS;
21220     for (unsigned i = 0; i != NumElts; ++i)
21221       RMask[i] = i;
21222   }
21223
21224   // Check that the shuffles are both shuffling the same vectors.
21225   if (!(A == C && B == D) && !(A == D && B == C))
21226     return false;
21227
21228   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21229   if (!A.getNode() && !B.getNode())
21230     return false;
21231
21232   // If A and B occur in reverse order in RHS, then "swap" them (which means
21233   // rewriting the mask).
21234   if (A != C)
21235     CommuteVectorShuffleMask(RMask, NumElts);
21236
21237   // At this point LHS and RHS are equivalent to
21238   //   LHS = VECTOR_SHUFFLE A, B, LMask
21239   //   RHS = VECTOR_SHUFFLE A, B, RMask
21240   // Check that the masks correspond to performing a horizontal operation.
21241   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21242     for (unsigned i = 0; i != NumLaneElts; ++i) {
21243       int LIdx = LMask[i+l], RIdx = RMask[i+l];
21244
21245       // Ignore any UNDEF components.
21246       if (LIdx < 0 || RIdx < 0 ||
21247           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21248           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21249         continue;
21250
21251       // Check that successive elements are being operated on.  If not, this is
21252       // not a horizontal operation.
21253       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21254       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21255       if (!(LIdx == Index && RIdx == Index + 1) &&
21256           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21257         return false;
21258     }
21259   }
21260
21261   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21262   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21263   return true;
21264 }
21265
21266 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21267 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21268                                   const X86Subtarget *Subtarget) {
21269   EVT VT = N->getValueType(0);
21270   SDValue LHS = N->getOperand(0);
21271   SDValue RHS = N->getOperand(1);
21272
21273   // Try to synthesize horizontal adds from adds of shuffles.
21274   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21275        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21276       isHorizontalBinOp(LHS, RHS, true))
21277     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21278   return SDValue();
21279 }
21280
21281 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21282 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21283                                   const X86Subtarget *Subtarget) {
21284   EVT VT = N->getValueType(0);
21285   SDValue LHS = N->getOperand(0);
21286   SDValue RHS = N->getOperand(1);
21287
21288   // Try to synthesize horizontal subs from subs of shuffles.
21289   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21290        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21291       isHorizontalBinOp(LHS, RHS, false))
21292     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21293   return SDValue();
21294 }
21295
21296 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21297 /// X86ISD::FXOR nodes.
21298 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21299   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21300   // F[X]OR(0.0, x) -> x
21301   // F[X]OR(x, 0.0) -> x
21302   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21303     if (C->getValueAPF().isPosZero())
21304       return N->getOperand(1);
21305   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21306     if (C->getValueAPF().isPosZero())
21307       return N->getOperand(0);
21308   return SDValue();
21309 }
21310
21311 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21312 /// X86ISD::FMAX nodes.
21313 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21314   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21315
21316   // Only perform optimizations if UnsafeMath is used.
21317   if (!DAG.getTarget().Options.UnsafeFPMath)
21318     return SDValue();
21319
21320   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21321   // into FMINC and FMAXC, which are Commutative operations.
21322   unsigned NewOp = 0;
21323   switch (N->getOpcode()) {
21324     default: llvm_unreachable("unknown opcode");
21325     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
21326     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
21327   }
21328
21329   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21330                      N->getOperand(0), N->getOperand(1));
21331 }
21332
21333 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21334 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21335   // FAND(0.0, x) -> 0.0
21336   // FAND(x, 0.0) -> 0.0
21337   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21338     if (C->getValueAPF().isPosZero())
21339       return N->getOperand(0);
21340   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21341     if (C->getValueAPF().isPosZero())
21342       return N->getOperand(1);
21343   return SDValue();
21344 }
21345
21346 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21347 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21348   // FANDN(x, 0.0) -> 0.0
21349   // FANDN(0.0, x) -> x
21350   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21351     if (C->getValueAPF().isPosZero())
21352       return N->getOperand(1);
21353   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21354     if (C->getValueAPF().isPosZero())
21355       return N->getOperand(1);
21356   return SDValue();
21357 }
21358
21359 static SDValue PerformBTCombine(SDNode *N,
21360                                 SelectionDAG &DAG,
21361                                 TargetLowering::DAGCombinerInfo &DCI) {
21362   // BT ignores high bits in the bit index operand.
21363   SDValue Op1 = N->getOperand(1);
21364   if (Op1.hasOneUse()) {
21365     unsigned BitWidth = Op1.getValueSizeInBits();
21366     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21367     APInt KnownZero, KnownOne;
21368     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21369                                           !DCI.isBeforeLegalizeOps());
21370     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21371     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21372         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21373       DCI.CommitTargetLoweringOpt(TLO);
21374   }
21375   return SDValue();
21376 }
21377
21378 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21379   SDValue Op = N->getOperand(0);
21380   if (Op.getOpcode() == ISD::BITCAST)
21381     Op = Op.getOperand(0);
21382   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21383   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21384       VT.getVectorElementType().getSizeInBits() ==
21385       OpVT.getVectorElementType().getSizeInBits()) {
21386     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21387   }
21388   return SDValue();
21389 }
21390
21391 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21392                                                const X86Subtarget *Subtarget) {
21393   EVT VT = N->getValueType(0);
21394   if (!VT.isVector())
21395     return SDValue();
21396
21397   SDValue N0 = N->getOperand(0);
21398   SDValue N1 = N->getOperand(1);
21399   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21400   SDLoc dl(N);
21401
21402   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21403   // both SSE and AVX2 since there is no sign-extended shift right
21404   // operation on a vector with 64-bit elements.
21405   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21406   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21407   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21408       N0.getOpcode() == ISD::SIGN_EXTEND)) {
21409     SDValue N00 = N0.getOperand(0);
21410
21411     // EXTLOAD has a better solution on AVX2,
21412     // it may be replaced with X86ISD::VSEXT node.
21413     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21414       if (!ISD::isNormalLoad(N00.getNode()))
21415         return SDValue();
21416
21417     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21418         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21419                                   N00, N1);
21420       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21421     }
21422   }
21423   return SDValue();
21424 }
21425
21426 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21427                                   TargetLowering::DAGCombinerInfo &DCI,
21428                                   const X86Subtarget *Subtarget) {
21429   if (!DCI.isBeforeLegalizeOps())
21430     return SDValue();
21431
21432   if (!Subtarget->hasFp256())
21433     return SDValue();
21434
21435   EVT VT = N->getValueType(0);
21436   if (VT.isVector() && VT.getSizeInBits() == 256) {
21437     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21438     if (R.getNode())
21439       return R;
21440   }
21441
21442   return SDValue();
21443 }
21444
21445 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21446                                  const X86Subtarget* Subtarget) {
21447   SDLoc dl(N);
21448   EVT VT = N->getValueType(0);
21449
21450   // Let legalize expand this if it isn't a legal type yet.
21451   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21452     return SDValue();
21453
21454   EVT ScalarVT = VT.getScalarType();
21455   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21456       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21457     return SDValue();
21458
21459   SDValue A = N->getOperand(0);
21460   SDValue B = N->getOperand(1);
21461   SDValue C = N->getOperand(2);
21462
21463   bool NegA = (A.getOpcode() == ISD::FNEG);
21464   bool NegB = (B.getOpcode() == ISD::FNEG);
21465   bool NegC = (C.getOpcode() == ISD::FNEG);
21466
21467   // Negative multiplication when NegA xor NegB
21468   bool NegMul = (NegA != NegB);
21469   if (NegA)
21470     A = A.getOperand(0);
21471   if (NegB)
21472     B = B.getOperand(0);
21473   if (NegC)
21474     C = C.getOperand(0);
21475
21476   unsigned Opcode;
21477   if (!NegMul)
21478     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21479   else
21480     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21481
21482   return DAG.getNode(Opcode, dl, VT, A, B, C);
21483 }
21484
21485 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21486                                   TargetLowering::DAGCombinerInfo &DCI,
21487                                   const X86Subtarget *Subtarget) {
21488   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
21489   //           (and (i32 x86isd::setcc_carry), 1)
21490   // This eliminates the zext. This transformation is necessary because
21491   // ISD::SETCC is always legalized to i8.
21492   SDLoc dl(N);
21493   SDValue N0 = N->getOperand(0);
21494   EVT VT = N->getValueType(0);
21495
21496   if (N0.getOpcode() == ISD::AND &&
21497       N0.hasOneUse() &&
21498       N0.getOperand(0).hasOneUse()) {
21499     SDValue N00 = N0.getOperand(0);
21500     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21501       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21502       if (!C || C->getZExtValue() != 1)
21503         return SDValue();
21504       return DAG.getNode(ISD::AND, dl, VT,
21505                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21506                                      N00.getOperand(0), N00.getOperand(1)),
21507                          DAG.getConstant(1, VT));
21508     }
21509   }
21510
21511   if (N0.getOpcode() == ISD::TRUNCATE &&
21512       N0.hasOneUse() &&
21513       N0.getOperand(0).hasOneUse()) {
21514     SDValue N00 = N0.getOperand(0);
21515     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21516       return DAG.getNode(ISD::AND, dl, VT,
21517                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21518                                      N00.getOperand(0), N00.getOperand(1)),
21519                          DAG.getConstant(1, VT));
21520     }
21521   }
21522   if (VT.is256BitVector()) {
21523     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21524     if (R.getNode())
21525       return R;
21526   }
21527
21528   return SDValue();
21529 }
21530
21531 // Optimize x == -y --> x+y == 0
21532 //          x != -y --> x+y != 0
21533 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21534                                       const X86Subtarget* Subtarget) {
21535   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21536   SDValue LHS = N->getOperand(0);
21537   SDValue RHS = N->getOperand(1);
21538   EVT VT = N->getValueType(0);
21539   SDLoc DL(N);
21540
21541   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21542     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21543       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21544         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21545                                    LHS.getValueType(), RHS, LHS.getOperand(1));
21546         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21547                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21548       }
21549   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21550     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21551       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21552         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21553                                    RHS.getValueType(), LHS, RHS.getOperand(1));
21554         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21555                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21556       }
21557
21558   if (VT.getScalarType() == MVT::i1) {
21559     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21560       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21561     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21562     if (!IsSEXT0 && !IsVZero0)
21563       return SDValue();
21564     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21565       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21566     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21567
21568     if (!IsSEXT1 && !IsVZero1)
21569       return SDValue();
21570
21571     if (IsSEXT0 && IsVZero1) {
21572       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21573       if (CC == ISD::SETEQ)
21574         return DAG.getNOT(DL, LHS.getOperand(0), VT);
21575       return LHS.getOperand(0);
21576     }
21577     if (IsSEXT1 && IsVZero0) {
21578       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21579       if (CC == ISD::SETEQ)
21580         return DAG.getNOT(DL, RHS.getOperand(0), VT);
21581       return RHS.getOperand(0);
21582     }
21583   }
21584
21585   return SDValue();
21586 }
21587
21588 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21589                                       const X86Subtarget *Subtarget) {
21590   SDLoc dl(N);
21591   MVT VT = N->getOperand(1)->getSimpleValueType(0);
21592   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21593          "X86insertps is only defined for v4x32");
21594
21595   SDValue Ld = N->getOperand(1);
21596   if (MayFoldLoad(Ld)) {
21597     // Extract the countS bits from the immediate so we can get the proper
21598     // address when narrowing the vector load to a specific element.
21599     // When the second source op is a memory address, interps doesn't use
21600     // countS and just gets an f32 from that address.
21601     unsigned DestIndex =
21602         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21603     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21604   } else
21605     return SDValue();
21606
21607   // Create this as a scalar to vector to match the instruction pattern.
21608   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21609   // countS bits are ignored when loading from memory on insertps, which
21610   // means we don't need to explicitly set them to 0.
21611   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21612                      LoadScalarToVector, N->getOperand(2));
21613 }
21614
21615 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21616 // as "sbb reg,reg", since it can be extended without zext and produces
21617 // an all-ones bit which is more useful than 0/1 in some cases.
21618 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21619                                MVT VT) {
21620   if (VT == MVT::i8)
21621     return DAG.getNode(ISD::AND, DL, VT,
21622                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21623                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21624                        DAG.getConstant(1, VT));
21625   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21626   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21627                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21628                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21629 }
21630
21631 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21632 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21633                                    TargetLowering::DAGCombinerInfo &DCI,
21634                                    const X86Subtarget *Subtarget) {
21635   SDLoc DL(N);
21636   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21637   SDValue EFLAGS = N->getOperand(1);
21638
21639   if (CC == X86::COND_A) {
21640     // Try to convert COND_A into COND_B in an attempt to facilitate
21641     // materializing "setb reg".
21642     //
21643     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21644     // cannot take an immediate as its first operand.
21645     //
21646     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21647         EFLAGS.getValueType().isInteger() &&
21648         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21649       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21650                                    EFLAGS.getNode()->getVTList(),
21651                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21652       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21653       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21654     }
21655   }
21656
21657   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21658   // a zext and produces an all-ones bit which is more useful than 0/1 in some
21659   // cases.
21660   if (CC == X86::COND_B)
21661     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21662
21663   SDValue Flags;
21664
21665   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21666   if (Flags.getNode()) {
21667     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21668     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21669   }
21670
21671   return SDValue();
21672 }
21673
21674 // Optimize branch condition evaluation.
21675 //
21676 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21677                                     TargetLowering::DAGCombinerInfo &DCI,
21678                                     const X86Subtarget *Subtarget) {
21679   SDLoc DL(N);
21680   SDValue Chain = N->getOperand(0);
21681   SDValue Dest = N->getOperand(1);
21682   SDValue EFLAGS = N->getOperand(3);
21683   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21684
21685   SDValue Flags;
21686
21687   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21688   if (Flags.getNode()) {
21689     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21690     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21691                        Flags);
21692   }
21693
21694   return SDValue();
21695 }
21696
21697 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21698                                         const X86TargetLowering *XTLI) {
21699   SDValue Op0 = N->getOperand(0);
21700   EVT InVT = Op0->getValueType(0);
21701
21702   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21703   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21704     SDLoc dl(N);
21705     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21706     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21707     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21708   }
21709
21710   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21711   // a 32-bit target where SSE doesn't support i64->FP operations.
21712   if (Op0.getOpcode() == ISD::LOAD) {
21713     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21714     EVT VT = Ld->getValueType(0);
21715     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21716         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21717         !XTLI->getSubtarget()->is64Bit() &&
21718         VT == MVT::i64) {
21719       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21720                                           Ld->getChain(), Op0, DAG);
21721       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21722       return FILDChain;
21723     }
21724   }
21725   return SDValue();
21726 }
21727
21728 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21729 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21730                                  X86TargetLowering::DAGCombinerInfo &DCI) {
21731   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21732   // the result is either zero or one (depending on the input carry bit).
21733   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21734   if (X86::isZeroNode(N->getOperand(0)) &&
21735       X86::isZeroNode(N->getOperand(1)) &&
21736       // We don't have a good way to replace an EFLAGS use, so only do this when
21737       // dead right now.
21738       SDValue(N, 1).use_empty()) {
21739     SDLoc DL(N);
21740     EVT VT = N->getValueType(0);
21741     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21742     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21743                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21744                                            DAG.getConstant(X86::COND_B,MVT::i8),
21745                                            N->getOperand(2)),
21746                                DAG.getConstant(1, VT));
21747     return DCI.CombineTo(N, Res1, CarryOut);
21748   }
21749
21750   return SDValue();
21751 }
21752
21753 // fold (add Y, (sete  X, 0)) -> adc  0, Y
21754 //      (add Y, (setne X, 0)) -> sbb -1, Y
21755 //      (sub (sete  X, 0), Y) -> sbb  0, Y
21756 //      (sub (setne X, 0), Y) -> adc -1, Y
21757 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21758   SDLoc DL(N);
21759
21760   // Look through ZExts.
21761   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21762   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21763     return SDValue();
21764
21765   SDValue SetCC = Ext.getOperand(0);
21766   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21767     return SDValue();
21768
21769   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21770   if (CC != X86::COND_E && CC != X86::COND_NE)
21771     return SDValue();
21772
21773   SDValue Cmp = SetCC.getOperand(1);
21774   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21775       !X86::isZeroNode(Cmp.getOperand(1)) ||
21776       !Cmp.getOperand(0).getValueType().isInteger())
21777     return SDValue();
21778
21779   SDValue CmpOp0 = Cmp.getOperand(0);
21780   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21781                                DAG.getConstant(1, CmpOp0.getValueType()));
21782
21783   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21784   if (CC == X86::COND_NE)
21785     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21786                        DL, OtherVal.getValueType(), OtherVal,
21787                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21788   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21789                      DL, OtherVal.getValueType(), OtherVal,
21790                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
21791 }
21792
21793 /// PerformADDCombine - Do target-specific dag combines on integer adds.
21794 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
21795                                  const X86Subtarget *Subtarget) {
21796   EVT VT = N->getValueType(0);
21797   SDValue Op0 = N->getOperand(0);
21798   SDValue Op1 = N->getOperand(1);
21799
21800   // Try to synthesize horizontal adds from adds of shuffles.
21801   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21802        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21803       isHorizontalBinOp(Op0, Op1, true))
21804     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
21805
21806   return OptimizeConditionalInDecrement(N, DAG);
21807 }
21808
21809 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
21810                                  const X86Subtarget *Subtarget) {
21811   SDValue Op0 = N->getOperand(0);
21812   SDValue Op1 = N->getOperand(1);
21813
21814   // X86 can't encode an immediate LHS of a sub. See if we can push the
21815   // negation into a preceding instruction.
21816   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
21817     // If the RHS of the sub is a XOR with one use and a constant, invert the
21818     // immediate. Then add one to the LHS of the sub so we can turn
21819     // X-Y -> X+~Y+1, saving one register.
21820     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
21821         isa<ConstantSDNode>(Op1.getOperand(1))) {
21822       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
21823       EVT VT = Op0.getValueType();
21824       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
21825                                    Op1.getOperand(0),
21826                                    DAG.getConstant(~XorC, VT));
21827       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
21828                          DAG.getConstant(C->getAPIntValue()+1, VT));
21829     }
21830   }
21831
21832   // Try to synthesize horizontal adds from adds of shuffles.
21833   EVT VT = N->getValueType(0);
21834   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21835        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21836       isHorizontalBinOp(Op0, Op1, true))
21837     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21838
21839   return OptimizeConditionalInDecrement(N, DAG);
21840 }
21841
21842 /// performVZEXTCombine - Performs build vector combines
21843 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21844                                         TargetLowering::DAGCombinerInfo &DCI,
21845                                         const X86Subtarget *Subtarget) {
21846   // (vzext (bitcast (vzext (x)) -> (vzext x)
21847   SDValue In = N->getOperand(0);
21848   while (In.getOpcode() == ISD::BITCAST)
21849     In = In.getOperand(0);
21850
21851   if (In.getOpcode() != X86ISD::VZEXT)
21852     return SDValue();
21853
21854   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
21855                      In.getOperand(0));
21856 }
21857
21858 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
21859                                              DAGCombinerInfo &DCI) const {
21860   SelectionDAG &DAG = DCI.DAG;
21861   switch (N->getOpcode()) {
21862   default: break;
21863   case ISD::EXTRACT_VECTOR_ELT:
21864     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
21865   case ISD::VSELECT:
21866   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
21867   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
21868   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
21869   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
21870   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
21871   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
21872   case ISD::SHL:
21873   case ISD::SRA:
21874   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
21875   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
21876   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
21877   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
21878   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
21879   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
21880   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
21881   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
21882   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
21883   case X86ISD::FXOR:
21884   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
21885   case X86ISD::FMIN:
21886   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
21887   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
21888   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
21889   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
21890   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
21891   case ISD::ANY_EXTEND:
21892   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
21893   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
21894   case ISD::SIGN_EXTEND_INREG:
21895     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
21896   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
21897   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
21898   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
21899   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
21900   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
21901   case X86ISD::SHUFP:       // Handle all target specific shuffles
21902   case X86ISD::PALIGNR:
21903   case X86ISD::UNPCKH:
21904   case X86ISD::UNPCKL:
21905   case X86ISD::MOVHLPS:
21906   case X86ISD::MOVLHPS:
21907   case X86ISD::PSHUFD:
21908   case X86ISD::PSHUFHW:
21909   case X86ISD::PSHUFLW:
21910   case X86ISD::MOVSS:
21911   case X86ISD::MOVSD:
21912   case X86ISD::VPERMILP:
21913   case X86ISD::VPERM2X128:
21914   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
21915   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
21916   case ISD::INTRINSIC_WO_CHAIN:
21917     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
21918   case X86ISD::INSERTPS:
21919     return PerformINSERTPSCombine(N, DAG, Subtarget);
21920   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
21921   }
21922
21923   return SDValue();
21924 }
21925
21926 /// isTypeDesirableForOp - Return true if the target has native support for
21927 /// the specified value type and it is 'desirable' to use the type for the
21928 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
21929 /// instruction encodings are longer and some i16 instructions are slow.
21930 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
21931   if (!isTypeLegal(VT))
21932     return false;
21933   if (VT != MVT::i16)
21934     return true;
21935
21936   switch (Opc) {
21937   default:
21938     return true;
21939   case ISD::LOAD:
21940   case ISD::SIGN_EXTEND:
21941   case ISD::ZERO_EXTEND:
21942   case ISD::ANY_EXTEND:
21943   case ISD::SHL:
21944   case ISD::SRL:
21945   case ISD::SUB:
21946   case ISD::ADD:
21947   case ISD::MUL:
21948   case ISD::AND:
21949   case ISD::OR:
21950   case ISD::XOR:
21951     return false;
21952   }
21953 }
21954
21955 /// IsDesirableToPromoteOp - This method query the target whether it is
21956 /// beneficial for dag combiner to promote the specified node. If true, it
21957 /// should return the desired promotion type by reference.
21958 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21959   EVT VT = Op.getValueType();
21960   if (VT != MVT::i16)
21961     return false;
21962
21963   bool Promote = false;
21964   bool Commute = false;
21965   switch (Op.getOpcode()) {
21966   default: break;
21967   case ISD::LOAD: {
21968     LoadSDNode *LD = cast<LoadSDNode>(Op);
21969     // If the non-extending load has a single use and it's not live out, then it
21970     // might be folded.
21971     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
21972                                                      Op.hasOneUse()*/) {
21973       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
21974              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
21975         // The only case where we'd want to promote LOAD (rather then it being
21976         // promoted as an operand is when it's only use is liveout.
21977         if (UI->getOpcode() != ISD::CopyToReg)
21978           return false;
21979       }
21980     }
21981     Promote = true;
21982     break;
21983   }
21984   case ISD::SIGN_EXTEND:
21985   case ISD::ZERO_EXTEND:
21986   case ISD::ANY_EXTEND:
21987     Promote = true;
21988     break;
21989   case ISD::SHL:
21990   case ISD::SRL: {
21991     SDValue N0 = Op.getOperand(0);
21992     // Look out for (store (shl (load), x)).
21993     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
21994       return false;
21995     Promote = true;
21996     break;
21997   }
21998   case ISD::ADD:
21999   case ISD::MUL:
22000   case ISD::AND:
22001   case ISD::OR:
22002   case ISD::XOR:
22003     Commute = true;
22004     // fallthrough
22005   case ISD::SUB: {
22006     SDValue N0 = Op.getOperand(0);
22007     SDValue N1 = Op.getOperand(1);
22008     if (!Commute && MayFoldLoad(N1))
22009       return false;
22010     // Avoid disabling potential load folding opportunities.
22011     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22012       return false;
22013     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22014       return false;
22015     Promote = true;
22016   }
22017   }
22018
22019   PVT = MVT::i32;
22020   return Promote;
22021 }
22022
22023 //===----------------------------------------------------------------------===//
22024 //                           X86 Inline Assembly Support
22025 //===----------------------------------------------------------------------===//
22026
22027 namespace {
22028   // Helper to match a string separated by whitespace.
22029   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22030     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22031
22032     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22033       StringRef piece(*args[i]);
22034       if (!s.startswith(piece)) // Check if the piece matches.
22035         return false;
22036
22037       s = s.substr(piece.size());
22038       StringRef::size_type pos = s.find_first_not_of(" \t");
22039       if (pos == 0) // We matched a prefix.
22040         return false;
22041
22042       s = s.substr(pos);
22043     }
22044
22045     return s.empty();
22046   }
22047   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22048 }
22049
22050 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22051
22052   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22053     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22054         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22055         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22056
22057       if (AsmPieces.size() == 3)
22058         return true;
22059       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22060         return true;
22061     }
22062   }
22063   return false;
22064 }
22065
22066 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22067   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22068
22069   std::string AsmStr = IA->getAsmString();
22070
22071   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22072   if (!Ty || Ty->getBitWidth() % 16 != 0)
22073     return false;
22074
22075   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22076   SmallVector<StringRef, 4> AsmPieces;
22077   SplitString(AsmStr, AsmPieces, ";\n");
22078
22079   switch (AsmPieces.size()) {
22080   default: return false;
22081   case 1:
22082     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22083     // we will turn this bswap into something that will be lowered to logical
22084     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22085     // lower so don't worry about this.
22086     // bswap $0
22087     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22088         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22089         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22090         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22091         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22092         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22093       // No need to check constraints, nothing other than the equivalent of
22094       // "=r,0" would be valid here.
22095       return IntrinsicLowering::LowerToByteSwap(CI);
22096     }
22097
22098     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22099     if (CI->getType()->isIntegerTy(16) &&
22100         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22101         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22102          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22103       AsmPieces.clear();
22104       const std::string &ConstraintsStr = IA->getConstraintString();
22105       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22106       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22107       if (clobbersFlagRegisters(AsmPieces))
22108         return IntrinsicLowering::LowerToByteSwap(CI);
22109     }
22110     break;
22111   case 3:
22112     if (CI->getType()->isIntegerTy(32) &&
22113         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22114         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22115         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22116         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22117       AsmPieces.clear();
22118       const std::string &ConstraintsStr = IA->getConstraintString();
22119       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22120       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22121       if (clobbersFlagRegisters(AsmPieces))
22122         return IntrinsicLowering::LowerToByteSwap(CI);
22123     }
22124
22125     if (CI->getType()->isIntegerTy(64)) {
22126       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22127       if (Constraints.size() >= 2 &&
22128           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22129           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22130         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22131         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22132             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22133             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22134           return IntrinsicLowering::LowerToByteSwap(CI);
22135       }
22136     }
22137     break;
22138   }
22139   return false;
22140 }
22141
22142 /// getConstraintType - Given a constraint letter, return the type of
22143 /// constraint it is for this target.
22144 X86TargetLowering::ConstraintType
22145 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22146   if (Constraint.size() == 1) {
22147     switch (Constraint[0]) {
22148     case 'R':
22149     case 'q':
22150     case 'Q':
22151     case 'f':
22152     case 't':
22153     case 'u':
22154     case 'y':
22155     case 'x':
22156     case 'Y':
22157     case 'l':
22158       return C_RegisterClass;
22159     case 'a':
22160     case 'b':
22161     case 'c':
22162     case 'd':
22163     case 'S':
22164     case 'D':
22165     case 'A':
22166       return C_Register;
22167     case 'I':
22168     case 'J':
22169     case 'K':
22170     case 'L':
22171     case 'M':
22172     case 'N':
22173     case 'G':
22174     case 'C':
22175     case 'e':
22176     case 'Z':
22177       return C_Other;
22178     default:
22179       break;
22180     }
22181   }
22182   return TargetLowering::getConstraintType(Constraint);
22183 }
22184
22185 /// Examine constraint type and operand type and determine a weight value.
22186 /// This object must already have been set up with the operand type
22187 /// and the current alternative constraint selected.
22188 TargetLowering::ConstraintWeight
22189   X86TargetLowering::getSingleConstraintMatchWeight(
22190     AsmOperandInfo &info, const char *constraint) const {
22191   ConstraintWeight weight = CW_Invalid;
22192   Value *CallOperandVal = info.CallOperandVal;
22193     // If we don't have a value, we can't do a match,
22194     // but allow it at the lowest weight.
22195   if (!CallOperandVal)
22196     return CW_Default;
22197   Type *type = CallOperandVal->getType();
22198   // Look at the constraint type.
22199   switch (*constraint) {
22200   default:
22201     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22202   case 'R':
22203   case 'q':
22204   case 'Q':
22205   case 'a':
22206   case 'b':
22207   case 'c':
22208   case 'd':
22209   case 'S':
22210   case 'D':
22211   case 'A':
22212     if (CallOperandVal->getType()->isIntegerTy())
22213       weight = CW_SpecificReg;
22214     break;
22215   case 'f':
22216   case 't':
22217   case 'u':
22218     if (type->isFloatingPointTy())
22219       weight = CW_SpecificReg;
22220     break;
22221   case 'y':
22222     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22223       weight = CW_SpecificReg;
22224     break;
22225   case 'x':
22226   case 'Y':
22227     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22228         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22229       weight = CW_Register;
22230     break;
22231   case 'I':
22232     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22233       if (C->getZExtValue() <= 31)
22234         weight = CW_Constant;
22235     }
22236     break;
22237   case 'J':
22238     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22239       if (C->getZExtValue() <= 63)
22240         weight = CW_Constant;
22241     }
22242     break;
22243   case 'K':
22244     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22245       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22246         weight = CW_Constant;
22247     }
22248     break;
22249   case 'L':
22250     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22251       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22252         weight = CW_Constant;
22253     }
22254     break;
22255   case 'M':
22256     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22257       if (C->getZExtValue() <= 3)
22258         weight = CW_Constant;
22259     }
22260     break;
22261   case 'N':
22262     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22263       if (C->getZExtValue() <= 0xff)
22264         weight = CW_Constant;
22265     }
22266     break;
22267   case 'G':
22268   case 'C':
22269     if (dyn_cast<ConstantFP>(CallOperandVal)) {
22270       weight = CW_Constant;
22271     }
22272     break;
22273   case 'e':
22274     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22275       if ((C->getSExtValue() >= -0x80000000LL) &&
22276           (C->getSExtValue() <= 0x7fffffffLL))
22277         weight = CW_Constant;
22278     }
22279     break;
22280   case 'Z':
22281     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22282       if (C->getZExtValue() <= 0xffffffff)
22283         weight = CW_Constant;
22284     }
22285     break;
22286   }
22287   return weight;
22288 }
22289
22290 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22291 /// with another that has more specific requirements based on the type of the
22292 /// corresponding operand.
22293 const char *X86TargetLowering::
22294 LowerXConstraint(EVT ConstraintVT) const {
22295   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22296   // 'f' like normal targets.
22297   if (ConstraintVT.isFloatingPoint()) {
22298     if (Subtarget->hasSSE2())
22299       return "Y";
22300     if (Subtarget->hasSSE1())
22301       return "x";
22302   }
22303
22304   return TargetLowering::LowerXConstraint(ConstraintVT);
22305 }
22306
22307 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22308 /// vector.  If it is invalid, don't add anything to Ops.
22309 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22310                                                      std::string &Constraint,
22311                                                      std::vector<SDValue>&Ops,
22312                                                      SelectionDAG &DAG) const {
22313   SDValue Result;
22314
22315   // Only support length 1 constraints for now.
22316   if (Constraint.length() > 1) return;
22317
22318   char ConstraintLetter = Constraint[0];
22319   switch (ConstraintLetter) {
22320   default: break;
22321   case 'I':
22322     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22323       if (C->getZExtValue() <= 31) {
22324         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22325         break;
22326       }
22327     }
22328     return;
22329   case 'J':
22330     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22331       if (C->getZExtValue() <= 63) {
22332         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22333         break;
22334       }
22335     }
22336     return;
22337   case 'K':
22338     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22339       if (isInt<8>(C->getSExtValue())) {
22340         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22341         break;
22342       }
22343     }
22344     return;
22345   case 'N':
22346     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22347       if (C->getZExtValue() <= 255) {
22348         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22349         break;
22350       }
22351     }
22352     return;
22353   case 'e': {
22354     // 32-bit signed value
22355     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22356       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22357                                            C->getSExtValue())) {
22358         // Widen to 64 bits here to get it sign extended.
22359         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22360         break;
22361       }
22362     // FIXME gcc accepts some relocatable values here too, but only in certain
22363     // memory models; it's complicated.
22364     }
22365     return;
22366   }
22367   case 'Z': {
22368     // 32-bit unsigned value
22369     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22370       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22371                                            C->getZExtValue())) {
22372         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22373         break;
22374       }
22375     }
22376     // FIXME gcc accepts some relocatable values here too, but only in certain
22377     // memory models; it's complicated.
22378     return;
22379   }
22380   case 'i': {
22381     // Literal immediates are always ok.
22382     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22383       // Widen to 64 bits here to get it sign extended.
22384       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22385       break;
22386     }
22387
22388     // In any sort of PIC mode addresses need to be computed at runtime by
22389     // adding in a register or some sort of table lookup.  These can't
22390     // be used as immediates.
22391     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22392       return;
22393
22394     // If we are in non-pic codegen mode, we allow the address of a global (with
22395     // an optional displacement) to be used with 'i'.
22396     GlobalAddressSDNode *GA = nullptr;
22397     int64_t Offset = 0;
22398
22399     // Match either (GA), (GA+C), (GA+C1+C2), etc.
22400     while (1) {
22401       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22402         Offset += GA->getOffset();
22403         break;
22404       } else if (Op.getOpcode() == ISD::ADD) {
22405         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22406           Offset += C->getZExtValue();
22407           Op = Op.getOperand(0);
22408           continue;
22409         }
22410       } else if (Op.getOpcode() == ISD::SUB) {
22411         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22412           Offset += -C->getZExtValue();
22413           Op = Op.getOperand(0);
22414           continue;
22415         }
22416       }
22417
22418       // Otherwise, this isn't something we can handle, reject it.
22419       return;
22420     }
22421
22422     const GlobalValue *GV = GA->getGlobal();
22423     // If we require an extra load to get this address, as in PIC mode, we
22424     // can't accept it.
22425     if (isGlobalStubReference(
22426             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22427       return;
22428
22429     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22430                                         GA->getValueType(0), Offset);
22431     break;
22432   }
22433   }
22434
22435   if (Result.getNode()) {
22436     Ops.push_back(Result);
22437     return;
22438   }
22439   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22440 }
22441
22442 std::pair<unsigned, const TargetRegisterClass*>
22443 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22444                                                 MVT VT) const {
22445   // First, see if this is a constraint that directly corresponds to an LLVM
22446   // register class.
22447   if (Constraint.size() == 1) {
22448     // GCC Constraint Letters
22449     switch (Constraint[0]) {
22450     default: break;
22451       // TODO: Slight differences here in allocation order and leaving
22452       // RIP in the class. Do they matter any more here than they do
22453       // in the normal allocation?
22454     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22455       if (Subtarget->is64Bit()) {
22456         if (VT == MVT::i32 || VT == MVT::f32)
22457           return std::make_pair(0U, &X86::GR32RegClass);
22458         if (VT == MVT::i16)
22459           return std::make_pair(0U, &X86::GR16RegClass);
22460         if (VT == MVT::i8 || VT == MVT::i1)
22461           return std::make_pair(0U, &X86::GR8RegClass);
22462         if (VT == MVT::i64 || VT == MVT::f64)
22463           return std::make_pair(0U, &X86::GR64RegClass);
22464         break;
22465       }
22466       // 32-bit fallthrough
22467     case 'Q':   // Q_REGS
22468       if (VT == MVT::i32 || VT == MVT::f32)
22469         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22470       if (VT == MVT::i16)
22471         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22472       if (VT == MVT::i8 || VT == MVT::i1)
22473         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22474       if (VT == MVT::i64)
22475         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22476       break;
22477     case 'r':   // GENERAL_REGS
22478     case 'l':   // INDEX_REGS
22479       if (VT == MVT::i8 || VT == MVT::i1)
22480         return std::make_pair(0U, &X86::GR8RegClass);
22481       if (VT == MVT::i16)
22482         return std::make_pair(0U, &X86::GR16RegClass);
22483       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22484         return std::make_pair(0U, &X86::GR32RegClass);
22485       return std::make_pair(0U, &X86::GR64RegClass);
22486     case 'R':   // LEGACY_REGS
22487       if (VT == MVT::i8 || VT == MVT::i1)
22488         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22489       if (VT == MVT::i16)
22490         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22491       if (VT == MVT::i32 || !Subtarget->is64Bit())
22492         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22493       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22494     case 'f':  // FP Stack registers.
22495       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22496       // value to the correct fpstack register class.
22497       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22498         return std::make_pair(0U, &X86::RFP32RegClass);
22499       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22500         return std::make_pair(0U, &X86::RFP64RegClass);
22501       return std::make_pair(0U, &X86::RFP80RegClass);
22502     case 'y':   // MMX_REGS if MMX allowed.
22503       if (!Subtarget->hasMMX()) break;
22504       return std::make_pair(0U, &X86::VR64RegClass);
22505     case 'Y':   // SSE_REGS if SSE2 allowed
22506       if (!Subtarget->hasSSE2()) break;
22507       // FALL THROUGH.
22508     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22509       if (!Subtarget->hasSSE1()) break;
22510
22511       switch (VT.SimpleTy) {
22512       default: break;
22513       // Scalar SSE types.
22514       case MVT::f32:
22515       case MVT::i32:
22516         return std::make_pair(0U, &X86::FR32RegClass);
22517       case MVT::f64:
22518       case MVT::i64:
22519         return std::make_pair(0U, &X86::FR64RegClass);
22520       // Vector types.
22521       case MVT::v16i8:
22522       case MVT::v8i16:
22523       case MVT::v4i32:
22524       case MVT::v2i64:
22525       case MVT::v4f32:
22526       case MVT::v2f64:
22527         return std::make_pair(0U, &X86::VR128RegClass);
22528       // AVX types.
22529       case MVT::v32i8:
22530       case MVT::v16i16:
22531       case MVT::v8i32:
22532       case MVT::v4i64:
22533       case MVT::v8f32:
22534       case MVT::v4f64:
22535         return std::make_pair(0U, &X86::VR256RegClass);
22536       case MVT::v8f64:
22537       case MVT::v16f32:
22538       case MVT::v16i32:
22539       case MVT::v8i64:
22540         return std::make_pair(0U, &X86::VR512RegClass);
22541       }
22542       break;
22543     }
22544   }
22545
22546   // Use the default implementation in TargetLowering to convert the register
22547   // constraint into a member of a register class.
22548   std::pair<unsigned, const TargetRegisterClass*> Res;
22549   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22550
22551   // Not found as a standard register?
22552   if (!Res.second) {
22553     // Map st(0) -> st(7) -> ST0
22554     if (Constraint.size() == 7 && Constraint[0] == '{' &&
22555         tolower(Constraint[1]) == 's' &&
22556         tolower(Constraint[2]) == 't' &&
22557         Constraint[3] == '(' &&
22558         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22559         Constraint[5] == ')' &&
22560         Constraint[6] == '}') {
22561
22562       Res.first = X86::ST0+Constraint[4]-'0';
22563       Res.second = &X86::RFP80RegClass;
22564       return Res;
22565     }
22566
22567     // GCC allows "st(0)" to be called just plain "st".
22568     if (StringRef("{st}").equals_lower(Constraint)) {
22569       Res.first = X86::ST0;
22570       Res.second = &X86::RFP80RegClass;
22571       return Res;
22572     }
22573
22574     // flags -> EFLAGS
22575     if (StringRef("{flags}").equals_lower(Constraint)) {
22576       Res.first = X86::EFLAGS;
22577       Res.second = &X86::CCRRegClass;
22578       return Res;
22579     }
22580
22581     // 'A' means EAX + EDX.
22582     if (Constraint == "A") {
22583       Res.first = X86::EAX;
22584       Res.second = &X86::GR32_ADRegClass;
22585       return Res;
22586     }
22587     return Res;
22588   }
22589
22590   // Otherwise, check to see if this is a register class of the wrong value
22591   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22592   // turn into {ax},{dx}.
22593   if (Res.second->hasType(VT))
22594     return Res;   // Correct type already, nothing to do.
22595
22596   // All of the single-register GCC register classes map their values onto
22597   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
22598   // really want an 8-bit or 32-bit register, map to the appropriate register
22599   // class and return the appropriate register.
22600   if (Res.second == &X86::GR16RegClass) {
22601     if (VT == MVT::i8 || VT == MVT::i1) {
22602       unsigned DestReg = 0;
22603       switch (Res.first) {
22604       default: break;
22605       case X86::AX: DestReg = X86::AL; break;
22606       case X86::DX: DestReg = X86::DL; break;
22607       case X86::CX: DestReg = X86::CL; break;
22608       case X86::BX: DestReg = X86::BL; break;
22609       }
22610       if (DestReg) {
22611         Res.first = DestReg;
22612         Res.second = &X86::GR8RegClass;
22613       }
22614     } else if (VT == MVT::i32 || VT == MVT::f32) {
22615       unsigned DestReg = 0;
22616       switch (Res.first) {
22617       default: break;
22618       case X86::AX: DestReg = X86::EAX; break;
22619       case X86::DX: DestReg = X86::EDX; break;
22620       case X86::CX: DestReg = X86::ECX; break;
22621       case X86::BX: DestReg = X86::EBX; break;
22622       case X86::SI: DestReg = X86::ESI; break;
22623       case X86::DI: DestReg = X86::EDI; break;
22624       case X86::BP: DestReg = X86::EBP; break;
22625       case X86::SP: DestReg = X86::ESP; break;
22626       }
22627       if (DestReg) {
22628         Res.first = DestReg;
22629         Res.second = &X86::GR32RegClass;
22630       }
22631     } else if (VT == MVT::i64 || VT == MVT::f64) {
22632       unsigned DestReg = 0;
22633       switch (Res.first) {
22634       default: break;
22635       case X86::AX: DestReg = X86::RAX; break;
22636       case X86::DX: DestReg = X86::RDX; break;
22637       case X86::CX: DestReg = X86::RCX; break;
22638       case X86::BX: DestReg = X86::RBX; break;
22639       case X86::SI: DestReg = X86::RSI; break;
22640       case X86::DI: DestReg = X86::RDI; break;
22641       case X86::BP: DestReg = X86::RBP; break;
22642       case X86::SP: DestReg = X86::RSP; break;
22643       }
22644       if (DestReg) {
22645         Res.first = DestReg;
22646         Res.second = &X86::GR64RegClass;
22647       }
22648     }
22649   } else if (Res.second == &X86::FR32RegClass ||
22650              Res.second == &X86::FR64RegClass ||
22651              Res.second == &X86::VR128RegClass ||
22652              Res.second == &X86::VR256RegClass ||
22653              Res.second == &X86::FR32XRegClass ||
22654              Res.second == &X86::FR64XRegClass ||
22655              Res.second == &X86::VR128XRegClass ||
22656              Res.second == &X86::VR256XRegClass ||
22657              Res.second == &X86::VR512RegClass) {
22658     // Handle references to XMM physical registers that got mapped into the
22659     // wrong class.  This can happen with constraints like {xmm0} where the
22660     // target independent register mapper will just pick the first match it can
22661     // find, ignoring the required type.
22662
22663     if (VT == MVT::f32 || VT == MVT::i32)
22664       Res.second = &X86::FR32RegClass;
22665     else if (VT == MVT::f64 || VT == MVT::i64)
22666       Res.second = &X86::FR64RegClass;
22667     else if (X86::VR128RegClass.hasType(VT))
22668       Res.second = &X86::VR128RegClass;
22669     else if (X86::VR256RegClass.hasType(VT))
22670       Res.second = &X86::VR256RegClass;
22671     else if (X86::VR512RegClass.hasType(VT))
22672       Res.second = &X86::VR512RegClass;
22673   }
22674
22675   return Res;
22676 }
22677
22678 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22679                                             Type *Ty) const {
22680   // Scaling factors are not free at all.
22681   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22682   // will take 2 allocations in the out of order engine instead of 1
22683   // for plain addressing mode, i.e. inst (reg1).
22684   // E.g.,
22685   // vaddps (%rsi,%drx), %ymm0, %ymm1
22686   // Requires two allocations (one for the load, one for the computation)
22687   // whereas:
22688   // vaddps (%rsi), %ymm0, %ymm1
22689   // Requires just 1 allocation, i.e., freeing allocations for other operations
22690   // and having less micro operations to execute.
22691   //
22692   // For some X86 architectures, this is even worse because for instance for
22693   // stores, the complex addressing mode forces the instruction to use the
22694   // "load" ports instead of the dedicated "store" port.
22695   // E.g., on Haswell:
22696   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22697   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
22698   if (isLegalAddressingMode(AM, Ty))
22699     // Scale represents reg2 * scale, thus account for 1
22700     // as soon as we use a second register.
22701     return AM.Scale != 0;
22702   return -1;
22703 }
22704
22705 bool X86TargetLowering::isTargetFTOL() const {
22706   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
22707 }