[x86] Fix an indentation goof in a prior commit. Should have re-run
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
524   }
525
526   // There's never any support for operations beyond MVT::f32.
527   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
531
532   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
536
537   if (Subtarget->hasPOPCNT()) {
538     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
539   } else {
540     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
541     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
543     if (Subtarget->is64Bit())
544       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
545   }
546
547   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
548
549   if (!Subtarget->hasMOVBE())
550     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
551
552   // These should be promoted to a larger select which is supported.
553   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
554   // X86 wants to expand cmov itself.
555   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
556   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
561   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
567   if (Subtarget->is64Bit()) {
568     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
569     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
570   }
571   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
572   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574   // support continuation, user-level threading, and etc.. As a result, no
575   // other SjLj exception interfaces are implemented and please don't build
576   // your own exception handling based on them.
577   // LLVM/Clang supports zero-cost DWARF exception handling.
578   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
580
581   // Darwin ABI issue.
582   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
583   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
584   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
586   if (Subtarget->is64Bit())
587     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
589   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
592     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
593     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
594     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
595     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
596   }
597   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
599   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
601   if (Subtarget->is64Bit()) {
602     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
603     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
605   }
606
607   if (Subtarget->hasSSE1())
608     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
609
610   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
611
612   // Expand certain atomics
613   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
614     MVT VT = IntVTs[i];
615     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
618   }
619
620   if (Subtarget->hasCmpxchg16b()) {
621     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
622   }
623
624   // FIXME - use subtarget debug flags
625   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
628   }
629
630   if (Subtarget->is64Bit()) {
631     setExceptionPointerRegister(X86::RAX);
632     setExceptionSelectorRegister(X86::RDX);
633   } else {
634     setExceptionPointerRegister(X86::EAX);
635     setExceptionSelectorRegister(X86::EDX);
636   }
637   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
639
640   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
642
643   setOperationAction(ISD::TRAP, MVT::Other, Legal);
644   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
645
646   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
648   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
649   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650     // TargetInfo::X86_64ABIBuiltinVaList
651     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
652     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
653   } else {
654     // TargetInfo::CharPtrBuiltinVaList
655     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
656     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
657   }
658
659   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
660   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
661
662   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
663
664   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
665     // f32 and f64 use SSE.
666     // Set up the FP register classes.
667     addRegisterClass(MVT::f32, &X86::FR32RegClass);
668     addRegisterClass(MVT::f64, &X86::FR64RegClass);
669
670     // Use ANDPD to simulate FABS.
671     setOperationAction(ISD::FABS , MVT::f64, Custom);
672     setOperationAction(ISD::FABS , MVT::f32, Custom);
673
674     // Use XORP to simulate FNEG.
675     setOperationAction(ISD::FNEG , MVT::f64, Custom);
676     setOperationAction(ISD::FNEG , MVT::f32, Custom);
677
678     // Use ANDPD and ORPD to simulate FCOPYSIGN.
679     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
680     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
681
682     // Lower this to FGETSIGNx86 plus an AND.
683     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
684     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
685
686     // We don't support sin/cos/fmod
687     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
688     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
689     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
690     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
691     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
692     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
693
694     // Expand FP immediates into loads from the stack, except for the special
695     // cases we handle.
696     addLegalFPImmediate(APFloat(+0.0)); // xorpd
697     addLegalFPImmediate(APFloat(+0.0f)); // xorps
698   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
699     // Use SSE for f32, x87 for f64.
700     // Set up the FP register classes.
701     addRegisterClass(MVT::f32, &X86::FR32RegClass);
702     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
703
704     // Use ANDPS to simulate FABS.
705     setOperationAction(ISD::FABS , MVT::f32, Custom);
706
707     // Use XORP to simulate FNEG.
708     setOperationAction(ISD::FNEG , MVT::f32, Custom);
709
710     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
711
712     // Use ANDPS and ORPS to simulate FCOPYSIGN.
713     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
714     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
715
716     // We don't support sin/cos/fmod
717     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
718     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
719     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
720
721     // Special cases we handle for FP constants.
722     addLegalFPImmediate(APFloat(+0.0f)); // xorps
723     addLegalFPImmediate(APFloat(+0.0)); // FLD0
724     addLegalFPImmediate(APFloat(+1.0)); // FLD1
725     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
726     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
727
728     if (!TM.Options.UnsafeFPMath) {
729       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
730       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
731       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
732     }
733   } else if (!TM.Options.UseSoftFloat) {
734     // f32 and f64 in x87.
735     // Set up the FP register classes.
736     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
737     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
738
739     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
740     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
741     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
743
744     if (!TM.Options.UnsafeFPMath) {
745       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
746       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
747       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
749       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
751     }
752     addLegalFPImmediate(APFloat(+0.0)); // FLD0
753     addLegalFPImmediate(APFloat(+1.0)); // FLD1
754     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
755     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
756     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
757     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
758     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
759     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
760   }
761
762   // We don't support FMA.
763   setOperationAction(ISD::FMA, MVT::f64, Expand);
764   setOperationAction(ISD::FMA, MVT::f32, Expand);
765
766   // Long double always uses X87.
767   if (!TM.Options.UseSoftFloat) {
768     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
769     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
770     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
771     {
772       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
773       addLegalFPImmediate(TmpFlt);  // FLD0
774       TmpFlt.changeSign();
775       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
776
777       bool ignored;
778       APFloat TmpFlt2(+1.0);
779       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
780                       &ignored);
781       addLegalFPImmediate(TmpFlt2);  // FLD1
782       TmpFlt2.changeSign();
783       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
784     }
785
786     if (!TM.Options.UnsafeFPMath) {
787       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
788       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
789       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
790     }
791
792     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
793     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
794     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
795     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
796     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
797     setOperationAction(ISD::FMA, MVT::f80, Expand);
798   }
799
800   // Always use a library call for pow.
801   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
802   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
804
805   setOperationAction(ISD::FLOG, MVT::f80, Expand);
806   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
808   setOperationAction(ISD::FEXP, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
810
811   // First set operation action for all vector types to either promote
812   // (for widening) or expand (for scalarization). Then we will selectively
813   // turn on ones that can be effectively codegen'd.
814   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
815            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
816     MVT VT = (MVT::SimpleValueType)i;
817     setOperationAction(ISD::ADD , VT, Expand);
818     setOperationAction(ISD::SUB , VT, Expand);
819     setOperationAction(ISD::FADD, VT, Expand);
820     setOperationAction(ISD::FNEG, VT, Expand);
821     setOperationAction(ISD::FSUB, VT, Expand);
822     setOperationAction(ISD::MUL , VT, Expand);
823     setOperationAction(ISD::FMUL, VT, Expand);
824     setOperationAction(ISD::SDIV, VT, Expand);
825     setOperationAction(ISD::UDIV, VT, Expand);
826     setOperationAction(ISD::FDIV, VT, Expand);
827     setOperationAction(ISD::SREM, VT, Expand);
828     setOperationAction(ISD::UREM, VT, Expand);
829     setOperationAction(ISD::LOAD, VT, Expand);
830     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
831     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
832     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
833     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
834     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::FABS, VT, Expand);
836     setOperationAction(ISD::FSIN, VT, Expand);
837     setOperationAction(ISD::FSINCOS, VT, Expand);
838     setOperationAction(ISD::FCOS, VT, Expand);
839     setOperationAction(ISD::FSINCOS, VT, Expand);
840     setOperationAction(ISD::FREM, VT, Expand);
841     setOperationAction(ISD::FMA,  VT, Expand);
842     setOperationAction(ISD::FPOWI, VT, Expand);
843     setOperationAction(ISD::FSQRT, VT, Expand);
844     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
845     setOperationAction(ISD::FFLOOR, VT, Expand);
846     setOperationAction(ISD::FCEIL, VT, Expand);
847     setOperationAction(ISD::FTRUNC, VT, Expand);
848     setOperationAction(ISD::FRINT, VT, Expand);
849     setOperationAction(ISD::FNEARBYINT, VT, Expand);
850     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
851     setOperationAction(ISD::MULHS, VT, Expand);
852     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
853     setOperationAction(ISD::MULHU, VT, Expand);
854     setOperationAction(ISD::SDIVREM, VT, Expand);
855     setOperationAction(ISD::UDIVREM, VT, Expand);
856     setOperationAction(ISD::FPOW, VT, Expand);
857     setOperationAction(ISD::CTPOP, VT, Expand);
858     setOperationAction(ISD::CTTZ, VT, Expand);
859     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
860     setOperationAction(ISD::CTLZ, VT, Expand);
861     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
862     setOperationAction(ISD::SHL, VT, Expand);
863     setOperationAction(ISD::SRA, VT, Expand);
864     setOperationAction(ISD::SRL, VT, Expand);
865     setOperationAction(ISD::ROTL, VT, Expand);
866     setOperationAction(ISD::ROTR, VT, Expand);
867     setOperationAction(ISD::BSWAP, VT, Expand);
868     setOperationAction(ISD::SETCC, VT, Expand);
869     setOperationAction(ISD::FLOG, VT, Expand);
870     setOperationAction(ISD::FLOG2, VT, Expand);
871     setOperationAction(ISD::FLOG10, VT, Expand);
872     setOperationAction(ISD::FEXP, VT, Expand);
873     setOperationAction(ISD::FEXP2, VT, Expand);
874     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
875     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
876     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
877     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
879     setOperationAction(ISD::TRUNCATE, VT, Expand);
880     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
881     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
882     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
883     setOperationAction(ISD::VSELECT, VT, Expand);
884     setOperationAction(ISD::SELECT_CC, VT, Expand);
885     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
886              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
887       setTruncStoreAction(VT,
888                           (MVT::SimpleValueType)InnerVT, Expand);
889     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
890     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
891
892     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
893     // we have to deal with them whether we ask for Expansion or not. Setting
894     // Expand causes its own optimisation problems though, so leave them legal.
895     if (VT.getVectorElementType() == MVT::i1)
896       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
897   }
898
899   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
900   // with -msoft-float, disable use of MMX as well.
901   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
902     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
903     // No operations on x86mmx supported, everything uses intrinsics.
904   }
905
906   // MMX-sized vectors (other than x86mmx) are expected to be expanded
907   // into smaller operations.
908   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
909   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
910   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
912   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
913   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
914   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
915   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
916   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
917   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
918   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
919   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
920   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
921   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
922   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
923   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
924   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
928   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
929   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
930   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
931   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
933   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
937
938   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
939     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
940
941     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
942     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
946     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
947     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
948     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
949     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
950     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
951     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
952     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
953   }
954
955   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
956     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
957
958     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
959     // registers cannot be used even for integer operations.
960     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
961     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
962     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
963     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
964
965     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
966     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
967     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
968     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
969     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
970     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
971     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
972     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
974     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
975     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
976     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
977     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
978     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
979     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
980     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
981     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
985     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
986     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
987
988     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
989     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
992
993     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
998
999     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1000     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1001       MVT VT = (MVT::SimpleValueType)i;
1002       // Do not attempt to custom lower non-power-of-2 vectors
1003       if (!isPowerOf2_32(VT.getVectorNumElements()))
1004         continue;
1005       // Do not attempt to custom lower non-128-bit vectors
1006       if (!VT.is128BitVector())
1007         continue;
1008       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1009       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1010       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1011     }
1012
1013     // We support custom legalizing of sext and anyext loads for specific
1014     // memory vector types which we can load as a scalar (or sequence of
1015     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1016     // loads these must work with a single scalar load.
1017     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1018     if (Subtarget->is64Bit()) {
1019       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1020       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1021     }
1022     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1028
1029     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1030     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1031     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1032     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1033     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1034     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1035
1036     if (Subtarget->is64Bit()) {
1037       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1038       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1039     }
1040
1041     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1042     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1043       MVT VT = (MVT::SimpleValueType)i;
1044
1045       // Do not attempt to promote non-128-bit vectors
1046       if (!VT.is128BitVector())
1047         continue;
1048
1049       setOperationAction(ISD::AND,    VT, Promote);
1050       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1051       setOperationAction(ISD::OR,     VT, Promote);
1052       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1053       setOperationAction(ISD::XOR,    VT, Promote);
1054       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1055       setOperationAction(ISD::LOAD,   VT, Promote);
1056       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1057       setOperationAction(ISD::SELECT, VT, Promote);
1058       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1059     }
1060
1061     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1062
1063     // Custom lower v2i64 and v2f64 selects.
1064     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1065     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1066     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1067     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1068
1069     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1070     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1071
1072     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1074     // As there is no 64-bit GPR available, we need build a special custom
1075     // sequence to convert from v2i32 to v2f32.
1076     if (!Subtarget->is64Bit())
1077       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1078
1079     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1080     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1081
1082     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1083
1084     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1085     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1086     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1087   }
1088
1089   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1090     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1091     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1092     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1093     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1094     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1095     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1096     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1097     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1098     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1099     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1100
1101     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1102     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1103     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1104     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1105     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1106     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1107     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1108     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1109     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1110     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1111
1112     // FIXME: Do we need to handle scalar-to-vector here?
1113     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1114
1115     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1116     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1119     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1120     // There is no BLENDI for byte vectors. We don't need to custom lower
1121     // some vselects for now.
1122     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1123
1124     // SSE41 brings specific instructions for doing vector sign extend even in
1125     // cases where we don't have SRA.
1126     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1128     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1129
1130     // i8 and i16 vectors are custom because the source register and source
1131     // source memory operand types are not the same width.  f32 vectors are
1132     // custom since the immediate controlling the insert encodes additional
1133     // information.
1134     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1138
1139     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1143
1144     // FIXME: these should be Legal, but that's only for the case where
1145     // the index is constant.  For now custom expand to deal with that.
1146     if (Subtarget->is64Bit()) {
1147       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1148       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1149     }
1150   }
1151
1152   if (Subtarget->hasSSE2()) {
1153     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1154     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1155
1156     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1157     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1158
1159     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1160     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1161
1162     // In the customized shift lowering, the legal cases in AVX2 will be
1163     // recognized.
1164     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1165     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1166
1167     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1168     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1169
1170     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1171   }
1172
1173   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1174     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1175     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1176     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1177     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1179     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1180
1181     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1182     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1183     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1184
1185     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1186     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1190     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1191     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1192     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1193     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1194     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1195     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1196     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1197
1198     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1199     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1203     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1204     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1205     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1206     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1207     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1208     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1209     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1210
1211     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1212     // even though v8i16 is a legal type.
1213     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1214     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1215     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1216
1217     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1218     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1219     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1220
1221     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1222     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1223
1224     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1225
1226     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1227     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1228
1229     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1230     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1231
1232     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1233     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1234
1235     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1236     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1238     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1239
1240     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1241     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1242     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1243
1244     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1245     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1247     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1248
1249     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1251     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1252     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1254     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1255     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1257     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1258     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1260     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1261
1262     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1263       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1264       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1266       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1267       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1268       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1269     }
1270
1271     if (Subtarget->hasInt256()) {
1272       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1273       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1275       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1276
1277       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1278       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1280       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1281
1282       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1283       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1284       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1285       // Don't lower v32i8 because there is no 128-bit byte mul
1286
1287       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1288       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1289       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1290       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1291
1292       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1293       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1294     } else {
1295       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1296       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1298       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1299
1300       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1301       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1303       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1304
1305       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1306       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1307       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1308       // Don't lower v32i8 because there is no 128-bit byte mul
1309     }
1310
1311     // In the customized shift lowering, the legal cases in AVX2 will be
1312     // recognized.
1313     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1314     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1315
1316     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1317     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1318
1319     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1320
1321     // Custom lower several nodes for 256-bit types.
1322     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1323              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1324       MVT VT = (MVT::SimpleValueType)i;
1325
1326       // Extract subvector is special because the value type
1327       // (result) is 128-bit but the source is 256-bit wide.
1328       if (VT.is128BitVector())
1329         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1330
1331       // Do not attempt to custom lower other non-256-bit vectors
1332       if (!VT.is256BitVector())
1333         continue;
1334
1335       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1336       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1337       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1338       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1339       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1340       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1341       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1342     }
1343
1344     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1345     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1346       MVT VT = (MVT::SimpleValueType)i;
1347
1348       // Do not attempt to promote non-256-bit vectors
1349       if (!VT.is256BitVector())
1350         continue;
1351
1352       setOperationAction(ISD::AND,    VT, Promote);
1353       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1354       setOperationAction(ISD::OR,     VT, Promote);
1355       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1356       setOperationAction(ISD::XOR,    VT, Promote);
1357       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1358       setOperationAction(ISD::LOAD,   VT, Promote);
1359       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1360       setOperationAction(ISD::SELECT, VT, Promote);
1361       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1362     }
1363   }
1364
1365   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1366     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1367     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1368     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1369     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1370
1371     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1372     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1373     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1374
1375     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1376     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1377     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1378     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1379     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1380     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1381     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1385     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1386
1387     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1388     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1391     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1392     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1393
1394     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1395     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1398     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1399     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1400     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1401     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1402
1403     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1404     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1405     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1406     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1407     if (Subtarget->is64Bit()) {
1408       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1409       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1410       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1411       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1412     }
1413     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1414     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1416     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1417     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1418     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1421     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1422     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1423
1424     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1425     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1430     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1432     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1437
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1444
1445     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1446     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1447
1448     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1449
1450     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1452     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1454     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1459
1460     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1461     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1462
1463     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1464     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1465
1466     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1467
1468     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1469     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1470
1471     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1472     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1473
1474     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1475     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1476
1477     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1478     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1479     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1480     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1481     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1482     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1483
1484     if (Subtarget->hasCDI()) {
1485       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1486       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1487     }
1488
1489     // Custom lower several nodes.
1490     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1491              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1492       MVT VT = (MVT::SimpleValueType)i;
1493
1494       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1495       // Extract subvector is special because the value type
1496       // (result) is 256/128-bit but the source is 512-bit wide.
1497       if (VT.is128BitVector() || VT.is256BitVector())
1498         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1499
1500       if (VT.getVectorElementType() == MVT::i1)
1501         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1502
1503       // Do not attempt to custom lower other non-512-bit vectors
1504       if (!VT.is512BitVector())
1505         continue;
1506
1507       if ( EltSize >= 32) {
1508         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1509         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1510         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1511         setOperationAction(ISD::VSELECT,             VT, Legal);
1512         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1513         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1514         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1515       }
1516     }
1517     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1518       MVT VT = (MVT::SimpleValueType)i;
1519
1520       // Do not attempt to promote non-256-bit vectors
1521       if (!VT.is512BitVector())
1522         continue;
1523
1524       setOperationAction(ISD::SELECT, VT, Promote);
1525       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1526     }
1527   }// has  AVX-512
1528
1529   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1530     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1531     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1532   }
1533
1534   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1535   // of this type with custom code.
1536   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1537            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1538     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1539                        Custom);
1540   }
1541
1542   // We want to custom lower some of our intrinsics.
1543   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1544   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1545   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1546   if (!Subtarget->is64Bit())
1547     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1548
1549   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1550   // handle type legalization for these operations here.
1551   //
1552   // FIXME: We really should do custom legalization for addition and
1553   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1554   // than generic legalization for 64-bit multiplication-with-overflow, though.
1555   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1556     // Add/Sub/Mul with overflow operations are custom lowered.
1557     MVT VT = IntVTs[i];
1558     setOperationAction(ISD::SADDO, VT, Custom);
1559     setOperationAction(ISD::UADDO, VT, Custom);
1560     setOperationAction(ISD::SSUBO, VT, Custom);
1561     setOperationAction(ISD::USUBO, VT, Custom);
1562     setOperationAction(ISD::SMULO, VT, Custom);
1563     setOperationAction(ISD::UMULO, VT, Custom);
1564   }
1565
1566   // There are no 8-bit 3-address imul/mul instructions
1567   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1568   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1569
1570   if (!Subtarget->is64Bit()) {
1571     // These libcalls are not available in 32-bit.
1572     setLibcallName(RTLIB::SHL_I128, nullptr);
1573     setLibcallName(RTLIB::SRL_I128, nullptr);
1574     setLibcallName(RTLIB::SRA_I128, nullptr);
1575   }
1576
1577   // Combine sin / cos into one node or libcall if possible.
1578   if (Subtarget->hasSinCos()) {
1579     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1580     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1581     if (Subtarget->isTargetDarwin()) {
1582       // For MacOSX, we don't want to the normal expansion of a libcall to
1583       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1584       // traffic.
1585       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1586       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1587     }
1588   }
1589
1590   if (Subtarget->isTargetWin64()) {
1591     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1592     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1593     setOperationAction(ISD::SREM, MVT::i128, Custom);
1594     setOperationAction(ISD::UREM, MVT::i128, Custom);
1595     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1596     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1597   }
1598
1599   // We have target-specific dag combine patterns for the following nodes:
1600   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1601   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1602   setTargetDAGCombine(ISD::VSELECT);
1603   setTargetDAGCombine(ISD::SELECT);
1604   setTargetDAGCombine(ISD::SHL);
1605   setTargetDAGCombine(ISD::SRA);
1606   setTargetDAGCombine(ISD::SRL);
1607   setTargetDAGCombine(ISD::OR);
1608   setTargetDAGCombine(ISD::AND);
1609   setTargetDAGCombine(ISD::ADD);
1610   setTargetDAGCombine(ISD::FADD);
1611   setTargetDAGCombine(ISD::FSUB);
1612   setTargetDAGCombine(ISD::FMA);
1613   setTargetDAGCombine(ISD::SUB);
1614   setTargetDAGCombine(ISD::LOAD);
1615   setTargetDAGCombine(ISD::STORE);
1616   setTargetDAGCombine(ISD::ZERO_EXTEND);
1617   setTargetDAGCombine(ISD::ANY_EXTEND);
1618   setTargetDAGCombine(ISD::SIGN_EXTEND);
1619   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1620   setTargetDAGCombine(ISD::TRUNCATE);
1621   setTargetDAGCombine(ISD::SINT_TO_FP);
1622   setTargetDAGCombine(ISD::SETCC);
1623   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1624   setTargetDAGCombine(ISD::BUILD_VECTOR);
1625   if (Subtarget->is64Bit())
1626     setTargetDAGCombine(ISD::MUL);
1627   setTargetDAGCombine(ISD::XOR);
1628
1629   computeRegisterProperties();
1630
1631   // On Darwin, -Os means optimize for size without hurting performance,
1632   // do not reduce the limit.
1633   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1634   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1635   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1636   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1637   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1638   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1639   setPrefLoopAlignment(4); // 2^4 bytes.
1640
1641   // Predictable cmov don't hurt on atom because it's in-order.
1642   PredictableSelectIsExpensive = !Subtarget->isAtom();
1643
1644   setPrefFunctionAlignment(4); // 2^4 bytes.
1645 }
1646
1647 // This has so far only been implemented for 64-bit MachO.
1648 bool X86TargetLowering::useLoadStackGuardNode() const {
1649   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1650          Subtarget->is64Bit();
1651 }
1652
1653 TargetLoweringBase::LegalizeTypeAction
1654 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1655   if (ExperimentalVectorWideningLegalization &&
1656       VT.getVectorNumElements() != 1 &&
1657       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1658     return TypeWidenVector;
1659
1660   return TargetLoweringBase::getPreferredVectorAction(VT);
1661 }
1662
1663 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1664   if (!VT.isVector())
1665     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1666
1667   if (Subtarget->hasAVX512())
1668     switch(VT.getVectorNumElements()) {
1669     case  8: return MVT::v8i1;
1670     case 16: return MVT::v16i1;
1671   }
1672
1673   return VT.changeVectorElementTypeToInteger();
1674 }
1675
1676 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1677 /// the desired ByVal argument alignment.
1678 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1679   if (MaxAlign == 16)
1680     return;
1681   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1682     if (VTy->getBitWidth() == 128)
1683       MaxAlign = 16;
1684   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1685     unsigned EltAlign = 0;
1686     getMaxByValAlign(ATy->getElementType(), EltAlign);
1687     if (EltAlign > MaxAlign)
1688       MaxAlign = EltAlign;
1689   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1690     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1691       unsigned EltAlign = 0;
1692       getMaxByValAlign(STy->getElementType(i), EltAlign);
1693       if (EltAlign > MaxAlign)
1694         MaxAlign = EltAlign;
1695       if (MaxAlign == 16)
1696         break;
1697     }
1698   }
1699 }
1700
1701 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1702 /// function arguments in the caller parameter area. For X86, aggregates
1703 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1704 /// are at 4-byte boundaries.
1705 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1706   if (Subtarget->is64Bit()) {
1707     // Max of 8 and alignment of type.
1708     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1709     if (TyAlign > 8)
1710       return TyAlign;
1711     return 8;
1712   }
1713
1714   unsigned Align = 4;
1715   if (Subtarget->hasSSE1())
1716     getMaxByValAlign(Ty, Align);
1717   return Align;
1718 }
1719
1720 /// getOptimalMemOpType - Returns the target specific optimal type for load
1721 /// and store operations as a result of memset, memcpy, and memmove
1722 /// lowering. If DstAlign is zero that means it's safe to destination
1723 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1724 /// means there isn't a need to check it against alignment requirement,
1725 /// probably because the source does not need to be loaded. If 'IsMemset' is
1726 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1727 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1728 /// source is constant so it does not need to be loaded.
1729 /// It returns EVT::Other if the type should be determined using generic
1730 /// target-independent logic.
1731 EVT
1732 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1733                                        unsigned DstAlign, unsigned SrcAlign,
1734                                        bool IsMemset, bool ZeroMemset,
1735                                        bool MemcpyStrSrc,
1736                                        MachineFunction &MF) const {
1737   const Function *F = MF.getFunction();
1738   if ((!IsMemset || ZeroMemset) &&
1739       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1740                                        Attribute::NoImplicitFloat)) {
1741     if (Size >= 16 &&
1742         (Subtarget->isUnalignedMemAccessFast() ||
1743          ((DstAlign == 0 || DstAlign >= 16) &&
1744           (SrcAlign == 0 || SrcAlign >= 16)))) {
1745       if (Size >= 32) {
1746         if (Subtarget->hasInt256())
1747           return MVT::v8i32;
1748         if (Subtarget->hasFp256())
1749           return MVT::v8f32;
1750       }
1751       if (Subtarget->hasSSE2())
1752         return MVT::v4i32;
1753       if (Subtarget->hasSSE1())
1754         return MVT::v4f32;
1755     } else if (!MemcpyStrSrc && Size >= 8 &&
1756                !Subtarget->is64Bit() &&
1757                Subtarget->hasSSE2()) {
1758       // Do not use f64 to lower memcpy if source is string constant. It's
1759       // better to use i32 to avoid the loads.
1760       return MVT::f64;
1761     }
1762   }
1763   if (Subtarget->is64Bit() && Size >= 8)
1764     return MVT::i64;
1765   return MVT::i32;
1766 }
1767
1768 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1769   if (VT == MVT::f32)
1770     return X86ScalarSSEf32;
1771   else if (VT == MVT::f64)
1772     return X86ScalarSSEf64;
1773   return true;
1774 }
1775
1776 bool
1777 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1778                                                   unsigned,
1779                                                   unsigned,
1780                                                   bool *Fast) const {
1781   if (Fast)
1782     *Fast = Subtarget->isUnalignedMemAccessFast();
1783   return true;
1784 }
1785
1786 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1787 /// current function.  The returned value is a member of the
1788 /// MachineJumpTableInfo::JTEntryKind enum.
1789 unsigned X86TargetLowering::getJumpTableEncoding() const {
1790   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1791   // symbol.
1792   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1793       Subtarget->isPICStyleGOT())
1794     return MachineJumpTableInfo::EK_Custom32;
1795
1796   // Otherwise, use the normal jump table encoding heuristics.
1797   return TargetLowering::getJumpTableEncoding();
1798 }
1799
1800 const MCExpr *
1801 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1802                                              const MachineBasicBlock *MBB,
1803                                              unsigned uid,MCContext &Ctx) const{
1804   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1805          Subtarget->isPICStyleGOT());
1806   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1807   // entries.
1808   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1809                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1810 }
1811
1812 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1813 /// jumptable.
1814 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1815                                                     SelectionDAG &DAG) const {
1816   if (!Subtarget->is64Bit())
1817     // This doesn't have SDLoc associated with it, but is not really the
1818     // same as a Register.
1819     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1820   return Table;
1821 }
1822
1823 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1824 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1825 /// MCExpr.
1826 const MCExpr *X86TargetLowering::
1827 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1828                              MCContext &Ctx) const {
1829   // X86-64 uses RIP relative addressing based on the jump table label.
1830   if (Subtarget->isPICStyleRIPRel())
1831     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1832
1833   // Otherwise, the reference is relative to the PIC base.
1834   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1835 }
1836
1837 // FIXME: Why this routine is here? Move to RegInfo!
1838 std::pair<const TargetRegisterClass*, uint8_t>
1839 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1840   const TargetRegisterClass *RRC = nullptr;
1841   uint8_t Cost = 1;
1842   switch (VT.SimpleTy) {
1843   default:
1844     return TargetLowering::findRepresentativeClass(VT);
1845   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1846     RRC = Subtarget->is64Bit() ?
1847       (const TargetRegisterClass*)&X86::GR64RegClass :
1848       (const TargetRegisterClass*)&X86::GR32RegClass;
1849     break;
1850   case MVT::x86mmx:
1851     RRC = &X86::VR64RegClass;
1852     break;
1853   case MVT::f32: case MVT::f64:
1854   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1855   case MVT::v4f32: case MVT::v2f64:
1856   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1857   case MVT::v4f64:
1858     RRC = &X86::VR128RegClass;
1859     break;
1860   }
1861   return std::make_pair(RRC, Cost);
1862 }
1863
1864 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1865                                                unsigned &Offset) const {
1866   if (!Subtarget->isTargetLinux())
1867     return false;
1868
1869   if (Subtarget->is64Bit()) {
1870     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1871     Offset = 0x28;
1872     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1873       AddressSpace = 256;
1874     else
1875       AddressSpace = 257;
1876   } else {
1877     // %gs:0x14 on i386
1878     Offset = 0x14;
1879     AddressSpace = 256;
1880   }
1881   return true;
1882 }
1883
1884 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1885                                             unsigned DestAS) const {
1886   assert(SrcAS != DestAS && "Expected different address spaces!");
1887
1888   return SrcAS < 256 && DestAS < 256;
1889 }
1890
1891 //===----------------------------------------------------------------------===//
1892 //               Return Value Calling Convention Implementation
1893 //===----------------------------------------------------------------------===//
1894
1895 #include "X86GenCallingConv.inc"
1896
1897 bool
1898 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1899                                   MachineFunction &MF, bool isVarArg,
1900                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1901                         LLVMContext &Context) const {
1902   SmallVector<CCValAssign, 16> RVLocs;
1903   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1904   return CCInfo.CheckReturn(Outs, RetCC_X86);
1905 }
1906
1907 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1908   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1909   return ScratchRegs;
1910 }
1911
1912 SDValue
1913 X86TargetLowering::LowerReturn(SDValue Chain,
1914                                CallingConv::ID CallConv, bool isVarArg,
1915                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1916                                const SmallVectorImpl<SDValue> &OutVals,
1917                                SDLoc dl, SelectionDAG &DAG) const {
1918   MachineFunction &MF = DAG.getMachineFunction();
1919   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1920
1921   SmallVector<CCValAssign, 16> RVLocs;
1922   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1923   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1924
1925   SDValue Flag;
1926   SmallVector<SDValue, 6> RetOps;
1927   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1928   // Operand #1 = Bytes To Pop
1929   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1930                    MVT::i16));
1931
1932   // Copy the result values into the output registers.
1933   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1934     CCValAssign &VA = RVLocs[i];
1935     assert(VA.isRegLoc() && "Can only return in registers!");
1936     SDValue ValToCopy = OutVals[i];
1937     EVT ValVT = ValToCopy.getValueType();
1938
1939     // Promote values to the appropriate types
1940     if (VA.getLocInfo() == CCValAssign::SExt)
1941       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1942     else if (VA.getLocInfo() == CCValAssign::ZExt)
1943       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1944     else if (VA.getLocInfo() == CCValAssign::AExt)
1945       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1946     else if (VA.getLocInfo() == CCValAssign::BCvt)
1947       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1948
1949     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1950            "Unexpected FP-extend for return value.");  
1951
1952     // If this is x86-64, and we disabled SSE, we can't return FP values,
1953     // or SSE or MMX vectors.
1954     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1955          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1956           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1957       report_fatal_error("SSE register return with SSE disabled");
1958     }
1959     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1960     // llvm-gcc has never done it right and no one has noticed, so this
1961     // should be OK for now.
1962     if (ValVT == MVT::f64 &&
1963         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1964       report_fatal_error("SSE2 register return with SSE2 disabled");
1965
1966     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1967     // the RET instruction and handled by the FP Stackifier.
1968     if (VA.getLocReg() == X86::FP0 ||
1969         VA.getLocReg() == X86::FP1) {
1970       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1971       // change the value to the FP stack register class.
1972       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1973         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1974       RetOps.push_back(ValToCopy);
1975       // Don't emit a copytoreg.
1976       continue;
1977     }
1978
1979     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1980     // which is returned in RAX / RDX.
1981     if (Subtarget->is64Bit()) {
1982       if (ValVT == MVT::x86mmx) {
1983         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1984           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1985           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1986                                   ValToCopy);
1987           // If we don't have SSE2 available, convert to v4f32 so the generated
1988           // register is legal.
1989           if (!Subtarget->hasSSE2())
1990             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1991         }
1992       }
1993     }
1994
1995     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1996     Flag = Chain.getValue(1);
1997     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1998   }
1999
2000   // The x86-64 ABIs require that for returning structs by value we copy
2001   // the sret argument into %rax/%eax (depending on ABI) for the return.
2002   // Win32 requires us to put the sret argument to %eax as well.
2003   // We saved the argument into a virtual register in the entry block,
2004   // so now we copy the value out and into %rax/%eax.
2005   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2006       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2007     MachineFunction &MF = DAG.getMachineFunction();
2008     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2009     unsigned Reg = FuncInfo->getSRetReturnReg();
2010     assert(Reg &&
2011            "SRetReturnReg should have been set in LowerFormalArguments().");
2012     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2013
2014     unsigned RetValReg
2015         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2016           X86::RAX : X86::EAX;
2017     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2018     Flag = Chain.getValue(1);
2019
2020     // RAX/EAX now acts like a return value.
2021     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2022   }
2023
2024   RetOps[0] = Chain;  // Update chain.
2025
2026   // Add the flag if we have it.
2027   if (Flag.getNode())
2028     RetOps.push_back(Flag);
2029
2030   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2031 }
2032
2033 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2034   if (N->getNumValues() != 1)
2035     return false;
2036   if (!N->hasNUsesOfValue(1, 0))
2037     return false;
2038
2039   SDValue TCChain = Chain;
2040   SDNode *Copy = *N->use_begin();
2041   if (Copy->getOpcode() == ISD::CopyToReg) {
2042     // If the copy has a glue operand, we conservatively assume it isn't safe to
2043     // perform a tail call.
2044     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2045       return false;
2046     TCChain = Copy->getOperand(0);
2047   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2048     return false;
2049
2050   bool HasRet = false;
2051   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2052        UI != UE; ++UI) {
2053     if (UI->getOpcode() != X86ISD::RET_FLAG)
2054       return false;
2055     HasRet = true;
2056   }
2057
2058   if (!HasRet)
2059     return false;
2060
2061   Chain = TCChain;
2062   return true;
2063 }
2064
2065 EVT
2066 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2067                                             ISD::NodeType ExtendKind) const {
2068   MVT ReturnMVT;
2069   // TODO: Is this also valid on 32-bit?
2070   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2071     ReturnMVT = MVT::i8;
2072   else
2073     ReturnMVT = MVT::i32;
2074
2075   EVT MinVT = getRegisterType(Context, ReturnMVT);
2076   return VT.bitsLT(MinVT) ? MinVT : VT;
2077 }
2078
2079 /// LowerCallResult - Lower the result values of a call into the
2080 /// appropriate copies out of appropriate physical registers.
2081 ///
2082 SDValue
2083 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2084                                    CallingConv::ID CallConv, bool isVarArg,
2085                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2086                                    SDLoc dl, SelectionDAG &DAG,
2087                                    SmallVectorImpl<SDValue> &InVals) const {
2088
2089   // Assign locations to each value returned by this call.
2090   SmallVector<CCValAssign, 16> RVLocs;
2091   bool Is64Bit = Subtarget->is64Bit();
2092   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2093                  *DAG.getContext());
2094   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2095
2096   // Copy all of the result registers out of their specified physreg.
2097   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2098     CCValAssign &VA = RVLocs[i];
2099     EVT CopyVT = VA.getValVT();
2100
2101     // If this is x86-64, and we disabled SSE, we can't return FP values
2102     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2103         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2104       report_fatal_error("SSE register return with SSE disabled");
2105     }
2106
2107     // If we prefer to use the value in xmm registers, copy it out as f80 and
2108     // use a truncate to move it from fp stack reg to xmm reg.
2109     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2110         isScalarFPTypeInSSEReg(VA.getValVT()))
2111       CopyVT = MVT::f80;
2112
2113     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2114                                CopyVT, InFlag).getValue(1);
2115     SDValue Val = Chain.getValue(0);
2116
2117     if (CopyVT != VA.getValVT())
2118       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2119                         // This truncation won't change the value.
2120                         DAG.getIntPtrConstant(1));
2121
2122     InFlag = Chain.getValue(2);
2123     InVals.push_back(Val);
2124   }
2125
2126   return Chain;
2127 }
2128
2129 //===----------------------------------------------------------------------===//
2130 //                C & StdCall & Fast Calling Convention implementation
2131 //===----------------------------------------------------------------------===//
2132 //  StdCall calling convention seems to be standard for many Windows' API
2133 //  routines and around. It differs from C calling convention just a little:
2134 //  callee should clean up the stack, not caller. Symbols should be also
2135 //  decorated in some fancy way :) It doesn't support any vector arguments.
2136 //  For info on fast calling convention see Fast Calling Convention (tail call)
2137 //  implementation LowerX86_32FastCCCallTo.
2138
2139 /// CallIsStructReturn - Determines whether a call uses struct return
2140 /// semantics.
2141 enum StructReturnType {
2142   NotStructReturn,
2143   RegStructReturn,
2144   StackStructReturn
2145 };
2146 static StructReturnType
2147 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2148   if (Outs.empty())
2149     return NotStructReturn;
2150
2151   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2152   if (!Flags.isSRet())
2153     return NotStructReturn;
2154   if (Flags.isInReg())
2155     return RegStructReturn;
2156   return StackStructReturn;
2157 }
2158
2159 /// ArgsAreStructReturn - Determines whether a function uses struct
2160 /// return semantics.
2161 static StructReturnType
2162 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2163   if (Ins.empty())
2164     return NotStructReturn;
2165
2166   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2167   if (!Flags.isSRet())
2168     return NotStructReturn;
2169   if (Flags.isInReg())
2170     return RegStructReturn;
2171   return StackStructReturn;
2172 }
2173
2174 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2175 /// by "Src" to address "Dst" with size and alignment information specified by
2176 /// the specific parameter attribute. The copy will be passed as a byval
2177 /// function parameter.
2178 static SDValue
2179 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2180                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2181                           SDLoc dl) {
2182   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2183
2184   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2185                        /*isVolatile*/false, /*AlwaysInline=*/true,
2186                        MachinePointerInfo(), MachinePointerInfo());
2187 }
2188
2189 /// IsTailCallConvention - Return true if the calling convention is one that
2190 /// supports tail call optimization.
2191 static bool IsTailCallConvention(CallingConv::ID CC) {
2192   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2193           CC == CallingConv::HiPE);
2194 }
2195
2196 /// \brief Return true if the calling convention is a C calling convention.
2197 static bool IsCCallConvention(CallingConv::ID CC) {
2198   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2199           CC == CallingConv::X86_64_SysV);
2200 }
2201
2202 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2203   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2204     return false;
2205
2206   CallSite CS(CI);
2207   CallingConv::ID CalleeCC = CS.getCallingConv();
2208   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2209     return false;
2210
2211   return true;
2212 }
2213
2214 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2215 /// a tailcall target by changing its ABI.
2216 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2217                                    bool GuaranteedTailCallOpt) {
2218   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2219 }
2220
2221 SDValue
2222 X86TargetLowering::LowerMemArgument(SDValue Chain,
2223                                     CallingConv::ID CallConv,
2224                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2225                                     SDLoc dl, SelectionDAG &DAG,
2226                                     const CCValAssign &VA,
2227                                     MachineFrameInfo *MFI,
2228                                     unsigned i) const {
2229   // Create the nodes corresponding to a load from this parameter slot.
2230   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2231   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2232       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2233   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2234   EVT ValVT;
2235
2236   // If value is passed by pointer we have address passed instead of the value
2237   // itself.
2238   if (VA.getLocInfo() == CCValAssign::Indirect)
2239     ValVT = VA.getLocVT();
2240   else
2241     ValVT = VA.getValVT();
2242
2243   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2244   // changed with more analysis.
2245   // In case of tail call optimization mark all arguments mutable. Since they
2246   // could be overwritten by lowering of arguments in case of a tail call.
2247   if (Flags.isByVal()) {
2248     unsigned Bytes = Flags.getByValSize();
2249     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2250     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2251     return DAG.getFrameIndex(FI, getPointerTy());
2252   } else {
2253     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2254                                     VA.getLocMemOffset(), isImmutable);
2255     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2256     return DAG.getLoad(ValVT, dl, Chain, FIN,
2257                        MachinePointerInfo::getFixedStack(FI),
2258                        false, false, false, 0);
2259   }
2260 }
2261
2262 SDValue
2263 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2264                                         CallingConv::ID CallConv,
2265                                         bool isVarArg,
2266                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2267                                         SDLoc dl,
2268                                         SelectionDAG &DAG,
2269                                         SmallVectorImpl<SDValue> &InVals)
2270                                           const {
2271   MachineFunction &MF = DAG.getMachineFunction();
2272   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2273
2274   const Function* Fn = MF.getFunction();
2275   if (Fn->hasExternalLinkage() &&
2276       Subtarget->isTargetCygMing() &&
2277       Fn->getName() == "main")
2278     FuncInfo->setForceFramePointer(true);
2279
2280   MachineFrameInfo *MFI = MF.getFrameInfo();
2281   bool Is64Bit = Subtarget->is64Bit();
2282   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2283
2284   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2285          "Var args not supported with calling convention fastcc, ghc or hipe");
2286
2287   // Assign locations to all of the incoming arguments.
2288   SmallVector<CCValAssign, 16> ArgLocs;
2289   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2290
2291   // Allocate shadow area for Win64
2292   if (IsWin64)
2293     CCInfo.AllocateStack(32, 8);
2294
2295   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2296
2297   unsigned LastVal = ~0U;
2298   SDValue ArgValue;
2299   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2300     CCValAssign &VA = ArgLocs[i];
2301     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2302     // places.
2303     assert(VA.getValNo() != LastVal &&
2304            "Don't support value assigned to multiple locs yet");
2305     (void)LastVal;
2306     LastVal = VA.getValNo();
2307
2308     if (VA.isRegLoc()) {
2309       EVT RegVT = VA.getLocVT();
2310       const TargetRegisterClass *RC;
2311       if (RegVT == MVT::i32)
2312         RC = &X86::GR32RegClass;
2313       else if (Is64Bit && RegVT == MVT::i64)
2314         RC = &X86::GR64RegClass;
2315       else if (RegVT == MVT::f32)
2316         RC = &X86::FR32RegClass;
2317       else if (RegVT == MVT::f64)
2318         RC = &X86::FR64RegClass;
2319       else if (RegVT.is512BitVector())
2320         RC = &X86::VR512RegClass;
2321       else if (RegVT.is256BitVector())
2322         RC = &X86::VR256RegClass;
2323       else if (RegVT.is128BitVector())
2324         RC = &X86::VR128RegClass;
2325       else if (RegVT == MVT::x86mmx)
2326         RC = &X86::VR64RegClass;
2327       else if (RegVT == MVT::i1)
2328         RC = &X86::VK1RegClass;
2329       else if (RegVT == MVT::v8i1)
2330         RC = &X86::VK8RegClass;
2331       else if (RegVT == MVT::v16i1)
2332         RC = &X86::VK16RegClass;
2333       else if (RegVT == MVT::v32i1)
2334         RC = &X86::VK32RegClass;
2335       else if (RegVT == MVT::v64i1)
2336         RC = &X86::VK64RegClass;
2337       else
2338         llvm_unreachable("Unknown argument type!");
2339
2340       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2341       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2342
2343       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2344       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2345       // right size.
2346       if (VA.getLocInfo() == CCValAssign::SExt)
2347         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2348                                DAG.getValueType(VA.getValVT()));
2349       else if (VA.getLocInfo() == CCValAssign::ZExt)
2350         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2351                                DAG.getValueType(VA.getValVT()));
2352       else if (VA.getLocInfo() == CCValAssign::BCvt)
2353         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2354
2355       if (VA.isExtInLoc()) {
2356         // Handle MMX values passed in XMM regs.
2357         if (RegVT.isVector())
2358           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2359         else
2360           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2361       }
2362     } else {
2363       assert(VA.isMemLoc());
2364       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2365     }
2366
2367     // If value is passed via pointer - do a load.
2368     if (VA.getLocInfo() == CCValAssign::Indirect)
2369       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2370                              MachinePointerInfo(), false, false, false, 0);
2371
2372     InVals.push_back(ArgValue);
2373   }
2374
2375   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2376     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2377       // The x86-64 ABIs require that for returning structs by value we copy
2378       // the sret argument into %rax/%eax (depending on ABI) for the return.
2379       // Win32 requires us to put the sret argument to %eax as well.
2380       // Save the argument into a virtual register so that we can access it
2381       // from the return points.
2382       if (Ins[i].Flags.isSRet()) {
2383         unsigned Reg = FuncInfo->getSRetReturnReg();
2384         if (!Reg) {
2385           MVT PtrTy = getPointerTy();
2386           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2387           FuncInfo->setSRetReturnReg(Reg);
2388         }
2389         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2390         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2391         break;
2392       }
2393     }
2394   }
2395
2396   unsigned StackSize = CCInfo.getNextStackOffset();
2397   // Align stack specially for tail calls.
2398   if (FuncIsMadeTailCallSafe(CallConv,
2399                              MF.getTarget().Options.GuaranteedTailCallOpt))
2400     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2401
2402   // If the function takes variable number of arguments, make a frame index for
2403   // the start of the first vararg value... for expansion of llvm.va_start.
2404   if (isVarArg) {
2405     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2406                     CallConv != CallingConv::X86_ThisCall)) {
2407       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2408     }
2409     if (Is64Bit) {
2410       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2411
2412       // FIXME: We should really autogenerate these arrays
2413       static const MCPhysReg GPR64ArgRegsWin64[] = {
2414         X86::RCX, X86::RDX, X86::R8,  X86::R9
2415       };
2416       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2417         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2418       };
2419       static const MCPhysReg XMMArgRegs64Bit[] = {
2420         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2421         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2422       };
2423       const MCPhysReg *GPR64ArgRegs;
2424       unsigned NumXMMRegs = 0;
2425
2426       if (IsWin64) {
2427         // The XMM registers which might contain var arg parameters are shadowed
2428         // in their paired GPR.  So we only need to save the GPR to their home
2429         // slots.
2430         TotalNumIntRegs = 4;
2431         GPR64ArgRegs = GPR64ArgRegsWin64;
2432       } else {
2433         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2434         GPR64ArgRegs = GPR64ArgRegs64Bit;
2435
2436         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2437                                                 TotalNumXMMRegs);
2438       }
2439       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2440                                                        TotalNumIntRegs);
2441
2442       bool NoImplicitFloatOps = Fn->getAttributes().
2443         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2444       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2445              "SSE register cannot be used when SSE is disabled!");
2446       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2447                NoImplicitFloatOps) &&
2448              "SSE register cannot be used when SSE is disabled!");
2449       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2450           !Subtarget->hasSSE1())
2451         // Kernel mode asks for SSE to be disabled, so don't push them
2452         // on the stack.
2453         TotalNumXMMRegs = 0;
2454
2455       if (IsWin64) {
2456         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2457         // Get to the caller-allocated home save location.  Add 8 to account
2458         // for the return address.
2459         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2460         FuncInfo->setRegSaveFrameIndex(
2461           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2462         // Fixup to set vararg frame on shadow area (4 x i64).
2463         if (NumIntRegs < 4)
2464           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2465       } else {
2466         // For X86-64, if there are vararg parameters that are passed via
2467         // registers, then we must store them to their spots on the stack so
2468         // they may be loaded by deferencing the result of va_next.
2469         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2470         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2471         FuncInfo->setRegSaveFrameIndex(
2472           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2473                                false));
2474       }
2475
2476       // Store the integer parameter registers.
2477       SmallVector<SDValue, 8> MemOps;
2478       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2479                                         getPointerTy());
2480       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2481       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2482         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2483                                   DAG.getIntPtrConstant(Offset));
2484         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2485                                      &X86::GR64RegClass);
2486         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2487         SDValue Store =
2488           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2489                        MachinePointerInfo::getFixedStack(
2490                          FuncInfo->getRegSaveFrameIndex(), Offset),
2491                        false, false, 0);
2492         MemOps.push_back(Store);
2493         Offset += 8;
2494       }
2495
2496       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2497         // Now store the XMM (fp + vector) parameter registers.
2498         SmallVector<SDValue, 12> SaveXMMOps;
2499         SaveXMMOps.push_back(Chain);
2500
2501         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2502         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2503         SaveXMMOps.push_back(ALVal);
2504
2505         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2506                                FuncInfo->getRegSaveFrameIndex()));
2507         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2508                                FuncInfo->getVarArgsFPOffset()));
2509
2510         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2511           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2512                                        &X86::VR128RegClass);
2513           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2514           SaveXMMOps.push_back(Val);
2515         }
2516         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2517                                      MVT::Other, SaveXMMOps));
2518       }
2519
2520       if (!MemOps.empty())
2521         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2522     }
2523   }
2524
2525   // Some CCs need callee pop.
2526   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2527                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2528     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2529   } else {
2530     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2531     // If this is an sret function, the return should pop the hidden pointer.
2532     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2533         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2534         argsAreStructReturn(Ins) == StackStructReturn)
2535       FuncInfo->setBytesToPopOnReturn(4);
2536   }
2537
2538   if (!Is64Bit) {
2539     // RegSaveFrameIndex is X86-64 only.
2540     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2541     if (CallConv == CallingConv::X86_FastCall ||
2542         CallConv == CallingConv::X86_ThisCall)
2543       // fastcc functions can't have varargs.
2544       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2545   }
2546
2547   FuncInfo->setArgumentStackSize(StackSize);
2548
2549   return Chain;
2550 }
2551
2552 SDValue
2553 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2554                                     SDValue StackPtr, SDValue Arg,
2555                                     SDLoc dl, SelectionDAG &DAG,
2556                                     const CCValAssign &VA,
2557                                     ISD::ArgFlagsTy Flags) const {
2558   unsigned LocMemOffset = VA.getLocMemOffset();
2559   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2560   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2561   if (Flags.isByVal())
2562     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2563
2564   return DAG.getStore(Chain, dl, Arg, PtrOff,
2565                       MachinePointerInfo::getStack(LocMemOffset),
2566                       false, false, 0);
2567 }
2568
2569 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2570 /// optimization is performed and it is required.
2571 SDValue
2572 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2573                                            SDValue &OutRetAddr, SDValue Chain,
2574                                            bool IsTailCall, bool Is64Bit,
2575                                            int FPDiff, SDLoc dl) const {
2576   // Adjust the Return address stack slot.
2577   EVT VT = getPointerTy();
2578   OutRetAddr = getReturnAddressFrameIndex(DAG);
2579
2580   // Load the "old" Return address.
2581   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2582                            false, false, false, 0);
2583   return SDValue(OutRetAddr.getNode(), 1);
2584 }
2585
2586 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2587 /// optimization is performed and it is required (FPDiff!=0).
2588 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2589                                         SDValue Chain, SDValue RetAddrFrIdx,
2590                                         EVT PtrVT, unsigned SlotSize,
2591                                         int FPDiff, SDLoc dl) {
2592   // Store the return address to the appropriate stack slot.
2593   if (!FPDiff) return Chain;
2594   // Calculate the new stack slot for the return address.
2595   int NewReturnAddrFI =
2596     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2597                                          false);
2598   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2599   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2600                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2601                        false, false, 0);
2602   return Chain;
2603 }
2604
2605 SDValue
2606 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2607                              SmallVectorImpl<SDValue> &InVals) const {
2608   SelectionDAG &DAG                     = CLI.DAG;
2609   SDLoc &dl                             = CLI.DL;
2610   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2611   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2612   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2613   SDValue Chain                         = CLI.Chain;
2614   SDValue Callee                        = CLI.Callee;
2615   CallingConv::ID CallConv              = CLI.CallConv;
2616   bool &isTailCall                      = CLI.IsTailCall;
2617   bool isVarArg                         = CLI.IsVarArg;
2618
2619   MachineFunction &MF = DAG.getMachineFunction();
2620   bool Is64Bit        = Subtarget->is64Bit();
2621   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2622   StructReturnType SR = callIsStructReturn(Outs);
2623   bool IsSibcall      = false;
2624
2625   if (MF.getTarget().Options.DisableTailCalls)
2626     isTailCall = false;
2627
2628   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2629   if (IsMustTail) {
2630     // Force this to be a tail call.  The verifier rules are enough to ensure
2631     // that we can lower this successfully without moving the return address
2632     // around.
2633     isTailCall = true;
2634   } else if (isTailCall) {
2635     // Check if it's really possible to do a tail call.
2636     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2637                     isVarArg, SR != NotStructReturn,
2638                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2639                     Outs, OutVals, Ins, DAG);
2640
2641     // Sibcalls are automatically detected tailcalls which do not require
2642     // ABI changes.
2643     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2644       IsSibcall = true;
2645
2646     if (isTailCall)
2647       ++NumTailCalls;
2648   }
2649
2650   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2651          "Var args not supported with calling convention fastcc, ghc or hipe");
2652
2653   // Analyze operands of the call, assigning locations to each operand.
2654   SmallVector<CCValAssign, 16> ArgLocs;
2655   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2656
2657   // Allocate shadow area for Win64
2658   if (IsWin64)
2659     CCInfo.AllocateStack(32, 8);
2660
2661   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2662
2663   // Get a count of how many bytes are to be pushed on the stack.
2664   unsigned NumBytes = CCInfo.getNextStackOffset();
2665   if (IsSibcall)
2666     // This is a sibcall. The memory operands are available in caller's
2667     // own caller's stack.
2668     NumBytes = 0;
2669   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2670            IsTailCallConvention(CallConv))
2671     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2672
2673   int FPDiff = 0;
2674   if (isTailCall && !IsSibcall && !IsMustTail) {
2675     // Lower arguments at fp - stackoffset + fpdiff.
2676     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2677     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2678
2679     FPDiff = NumBytesCallerPushed - NumBytes;
2680
2681     // Set the delta of movement of the returnaddr stackslot.
2682     // But only set if delta is greater than previous delta.
2683     if (FPDiff < X86Info->getTCReturnAddrDelta())
2684       X86Info->setTCReturnAddrDelta(FPDiff);
2685   }
2686
2687   unsigned NumBytesToPush = NumBytes;
2688   unsigned NumBytesToPop = NumBytes;
2689
2690   // If we have an inalloca argument, all stack space has already been allocated
2691   // for us and be right at the top of the stack.  We don't support multiple
2692   // arguments passed in memory when using inalloca.
2693   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2694     NumBytesToPush = 0;
2695     if (!ArgLocs.back().isMemLoc())
2696       report_fatal_error("cannot use inalloca attribute on a register "
2697                          "parameter");
2698     if (ArgLocs.back().getLocMemOffset() != 0)
2699       report_fatal_error("any parameter with the inalloca attribute must be "
2700                          "the only memory argument");
2701   }
2702
2703   if (!IsSibcall)
2704     Chain = DAG.getCALLSEQ_START(
2705         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2706
2707   SDValue RetAddrFrIdx;
2708   // Load return address for tail calls.
2709   if (isTailCall && FPDiff)
2710     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2711                                     Is64Bit, FPDiff, dl);
2712
2713   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2714   SmallVector<SDValue, 8> MemOpChains;
2715   SDValue StackPtr;
2716
2717   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2718   // of tail call optimization arguments are handle later.
2719   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2720       DAG.getSubtarget().getRegisterInfo());
2721   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2722     // Skip inalloca arguments, they have already been written.
2723     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2724     if (Flags.isInAlloca())
2725       continue;
2726
2727     CCValAssign &VA = ArgLocs[i];
2728     EVT RegVT = VA.getLocVT();
2729     SDValue Arg = OutVals[i];
2730     bool isByVal = Flags.isByVal();
2731
2732     // Promote the value if needed.
2733     switch (VA.getLocInfo()) {
2734     default: llvm_unreachable("Unknown loc info!");
2735     case CCValAssign::Full: break;
2736     case CCValAssign::SExt:
2737       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2738       break;
2739     case CCValAssign::ZExt:
2740       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2741       break;
2742     case CCValAssign::AExt:
2743       if (RegVT.is128BitVector()) {
2744         // Special case: passing MMX values in XMM registers.
2745         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2746         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2747         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2748       } else
2749         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2750       break;
2751     case CCValAssign::BCvt:
2752       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2753       break;
2754     case CCValAssign::Indirect: {
2755       // Store the argument.
2756       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2757       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2758       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2759                            MachinePointerInfo::getFixedStack(FI),
2760                            false, false, 0);
2761       Arg = SpillSlot;
2762       break;
2763     }
2764     }
2765
2766     if (VA.isRegLoc()) {
2767       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2768       if (isVarArg && IsWin64) {
2769         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2770         // shadow reg if callee is a varargs function.
2771         unsigned ShadowReg = 0;
2772         switch (VA.getLocReg()) {
2773         case X86::XMM0: ShadowReg = X86::RCX; break;
2774         case X86::XMM1: ShadowReg = X86::RDX; break;
2775         case X86::XMM2: ShadowReg = X86::R8; break;
2776         case X86::XMM3: ShadowReg = X86::R9; break;
2777         }
2778         if (ShadowReg)
2779           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2780       }
2781     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2782       assert(VA.isMemLoc());
2783       if (!StackPtr.getNode())
2784         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2785                                       getPointerTy());
2786       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2787                                              dl, DAG, VA, Flags));
2788     }
2789   }
2790
2791   if (!MemOpChains.empty())
2792     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2793
2794   if (Subtarget->isPICStyleGOT()) {
2795     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2796     // GOT pointer.
2797     if (!isTailCall) {
2798       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2799                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2800     } else {
2801       // If we are tail calling and generating PIC/GOT style code load the
2802       // address of the callee into ECX. The value in ecx is used as target of
2803       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2804       // for tail calls on PIC/GOT architectures. Normally we would just put the
2805       // address of GOT into ebx and then call target@PLT. But for tail calls
2806       // ebx would be restored (since ebx is callee saved) before jumping to the
2807       // target@PLT.
2808
2809       // Note: The actual moving to ECX is done further down.
2810       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2811       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2812           !G->getGlobal()->hasProtectedVisibility())
2813         Callee = LowerGlobalAddress(Callee, DAG);
2814       else if (isa<ExternalSymbolSDNode>(Callee))
2815         Callee = LowerExternalSymbol(Callee, DAG);
2816     }
2817   }
2818
2819   if (Is64Bit && isVarArg && !IsWin64) {
2820     // From AMD64 ABI document:
2821     // For calls that may call functions that use varargs or stdargs
2822     // (prototype-less calls or calls to functions containing ellipsis (...) in
2823     // the declaration) %al is used as hidden argument to specify the number
2824     // of SSE registers used. The contents of %al do not need to match exactly
2825     // the number of registers, but must be an ubound on the number of SSE
2826     // registers used and is in the range 0 - 8 inclusive.
2827
2828     // Count the number of XMM registers allocated.
2829     static const MCPhysReg XMMArgRegs[] = {
2830       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2831       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2832     };
2833     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2834     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2835            && "SSE registers cannot be used when SSE is disabled");
2836
2837     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2838                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2839   }
2840
2841   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2842   // don't need this because the eligibility check rejects calls that require
2843   // shuffling arguments passed in memory.
2844   if (!IsSibcall && isTailCall) {
2845     // Force all the incoming stack arguments to be loaded from the stack
2846     // before any new outgoing arguments are stored to the stack, because the
2847     // outgoing stack slots may alias the incoming argument stack slots, and
2848     // the alias isn't otherwise explicit. This is slightly more conservative
2849     // than necessary, because it means that each store effectively depends
2850     // on every argument instead of just those arguments it would clobber.
2851     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2852
2853     SmallVector<SDValue, 8> MemOpChains2;
2854     SDValue FIN;
2855     int FI = 0;
2856     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2857       CCValAssign &VA = ArgLocs[i];
2858       if (VA.isRegLoc())
2859         continue;
2860       assert(VA.isMemLoc());
2861       SDValue Arg = OutVals[i];
2862       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2863       // Skip inalloca arguments.  They don't require any work.
2864       if (Flags.isInAlloca())
2865         continue;
2866       // Create frame index.
2867       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2868       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2869       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2870       FIN = DAG.getFrameIndex(FI, getPointerTy());
2871
2872       if (Flags.isByVal()) {
2873         // Copy relative to framepointer.
2874         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2875         if (!StackPtr.getNode())
2876           StackPtr = DAG.getCopyFromReg(Chain, dl,
2877                                         RegInfo->getStackRegister(),
2878                                         getPointerTy());
2879         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2880
2881         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2882                                                          ArgChain,
2883                                                          Flags, DAG, dl));
2884       } else {
2885         // Store relative to framepointer.
2886         MemOpChains2.push_back(
2887           DAG.getStore(ArgChain, dl, Arg, FIN,
2888                        MachinePointerInfo::getFixedStack(FI),
2889                        false, false, 0));
2890       }
2891     }
2892
2893     if (!MemOpChains2.empty())
2894       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2895
2896     // Store the return address to the appropriate stack slot.
2897     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2898                                      getPointerTy(), RegInfo->getSlotSize(),
2899                                      FPDiff, dl);
2900   }
2901
2902   // Build a sequence of copy-to-reg nodes chained together with token chain
2903   // and flag operands which copy the outgoing args into registers.
2904   SDValue InFlag;
2905   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2906     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2907                              RegsToPass[i].second, InFlag);
2908     InFlag = Chain.getValue(1);
2909   }
2910
2911   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2912     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2913     // In the 64-bit large code model, we have to make all calls
2914     // through a register, since the call instruction's 32-bit
2915     // pc-relative offset may not be large enough to hold the whole
2916     // address.
2917   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2918     // If the callee is a GlobalAddress node (quite common, every direct call
2919     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2920     // it.
2921
2922     // We should use extra load for direct calls to dllimported functions in
2923     // non-JIT mode.
2924     const GlobalValue *GV = G->getGlobal();
2925     if (!GV->hasDLLImportStorageClass()) {
2926       unsigned char OpFlags = 0;
2927       bool ExtraLoad = false;
2928       unsigned WrapperKind = ISD::DELETED_NODE;
2929
2930       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2931       // external symbols most go through the PLT in PIC mode.  If the symbol
2932       // has hidden or protected visibility, or if it is static or local, then
2933       // we don't need to use the PLT - we can directly call it.
2934       if (Subtarget->isTargetELF() &&
2935           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2936           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2937         OpFlags = X86II::MO_PLT;
2938       } else if (Subtarget->isPICStyleStubAny() &&
2939                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
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       } else if (Subtarget->isPICStyleRIPRel() &&
2947                  isa<Function>(GV) &&
2948                  cast<Function>(GV)->getAttributes().
2949                    hasAttribute(AttributeSet::FunctionIndex,
2950                                 Attribute::NonLazyBind)) {
2951         // If the function is marked as non-lazy, generate an indirect call
2952         // which loads from the GOT directly. This avoids runtime overhead
2953         // at the cost of eager binding (and one extra byte of encoding).
2954         OpFlags = X86II::MO_GOTPCREL;
2955         WrapperKind = X86ISD::WrapperRIP;
2956         ExtraLoad = true;
2957       }
2958
2959       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2960                                           G->getOffset(), OpFlags);
2961
2962       // Add a wrapper if needed.
2963       if (WrapperKind != ISD::DELETED_NODE)
2964         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2965       // Add extra indirection if needed.
2966       if (ExtraLoad)
2967         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2968                              MachinePointerInfo::getGOT(),
2969                              false, false, false, 0);
2970     }
2971   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2972     unsigned char OpFlags = 0;
2973
2974     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2975     // external symbols should go through the PLT.
2976     if (Subtarget->isTargetELF() &&
2977         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2978       OpFlags = X86II::MO_PLT;
2979     } else if (Subtarget->isPICStyleStubAny() &&
2980                (!Subtarget->getTargetTriple().isMacOSX() ||
2981                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2982       // PC-relative references to external symbols should go through $stub,
2983       // unless we're building with the leopard linker or later, which
2984       // automatically synthesizes these stubs.
2985       OpFlags = X86II::MO_DARWIN_STUB;
2986     }
2987
2988     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2989                                          OpFlags);
2990   }
2991
2992   // Returns a chain & a flag for retval copy to use.
2993   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2994   SmallVector<SDValue, 8> Ops;
2995
2996   if (!IsSibcall && isTailCall) {
2997     Chain = DAG.getCALLSEQ_END(Chain,
2998                                DAG.getIntPtrConstant(NumBytesToPop, true),
2999                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3000     InFlag = Chain.getValue(1);
3001   }
3002
3003   Ops.push_back(Chain);
3004   Ops.push_back(Callee);
3005
3006   if (isTailCall)
3007     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3008
3009   // Add argument registers to the end of the list so that they are known live
3010   // into the call.
3011   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3012     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3013                                   RegsToPass[i].second.getValueType()));
3014
3015   // Add a register mask operand representing the call-preserved registers.
3016   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3017   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3018   assert(Mask && "Missing call preserved mask for calling convention");
3019   Ops.push_back(DAG.getRegisterMask(Mask));
3020
3021   if (InFlag.getNode())
3022     Ops.push_back(InFlag);
3023
3024   if (isTailCall) {
3025     // We used to do:
3026     //// If this is the first return lowered for this function, add the regs
3027     //// to the liveout set for the function.
3028     // This isn't right, although it's probably harmless on x86; liveouts
3029     // should be computed from returns not tail calls.  Consider a void
3030     // function making a tail call to a function returning int.
3031     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3032   }
3033
3034   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3035   InFlag = Chain.getValue(1);
3036
3037   // Create the CALLSEQ_END node.
3038   unsigned NumBytesForCalleeToPop;
3039   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3040                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3041     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3042   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3043            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3044            SR == StackStructReturn)
3045     // If this is a call to a struct-return function, the callee
3046     // pops the hidden struct pointer, so we have to push it back.
3047     // This is common for Darwin/X86, Linux & Mingw32 targets.
3048     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3049     NumBytesForCalleeToPop = 4;
3050   else
3051     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3052
3053   // Returns a flag for retval copy to use.
3054   if (!IsSibcall) {
3055     Chain = DAG.getCALLSEQ_END(Chain,
3056                                DAG.getIntPtrConstant(NumBytesToPop, true),
3057                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3058                                                      true),
3059                                InFlag, dl);
3060     InFlag = Chain.getValue(1);
3061   }
3062
3063   // Handle result values, copying them out of physregs into vregs that we
3064   // return.
3065   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3066                          Ins, dl, DAG, InVals);
3067 }
3068
3069 //===----------------------------------------------------------------------===//
3070 //                Fast Calling Convention (tail call) implementation
3071 //===----------------------------------------------------------------------===//
3072
3073 //  Like std call, callee cleans arguments, convention except that ECX is
3074 //  reserved for storing the tail called function address. Only 2 registers are
3075 //  free for argument passing (inreg). Tail call optimization is performed
3076 //  provided:
3077 //                * tailcallopt is enabled
3078 //                * caller/callee are fastcc
3079 //  On X86_64 architecture with GOT-style position independent code only local
3080 //  (within module) calls are supported at the moment.
3081 //  To keep the stack aligned according to platform abi the function
3082 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3083 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3084 //  If a tail called function callee has more arguments than the caller the
3085 //  caller needs to make sure that there is room to move the RETADDR to. This is
3086 //  achieved by reserving an area the size of the argument delta right after the
3087 //  original RETADDR, but before the saved framepointer or the spilled registers
3088 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3089 //  stack layout:
3090 //    arg1
3091 //    arg2
3092 //    RETADDR
3093 //    [ new RETADDR
3094 //      move area ]
3095 //    (possible EBP)
3096 //    ESI
3097 //    EDI
3098 //    local1 ..
3099
3100 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3101 /// for a 16 byte align requirement.
3102 unsigned
3103 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3104                                                SelectionDAG& DAG) const {
3105   MachineFunction &MF = DAG.getMachineFunction();
3106   const TargetMachine &TM = MF.getTarget();
3107   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3108       TM.getSubtargetImpl()->getRegisterInfo());
3109   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3110   unsigned StackAlignment = TFI.getStackAlignment();
3111   uint64_t AlignMask = StackAlignment - 1;
3112   int64_t Offset = StackSize;
3113   unsigned SlotSize = RegInfo->getSlotSize();
3114   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3115     // Number smaller than 12 so just add the difference.
3116     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3117   } else {
3118     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3119     Offset = ((~AlignMask) & Offset) + StackAlignment +
3120       (StackAlignment-SlotSize);
3121   }
3122   return Offset;
3123 }
3124
3125 /// MatchingStackOffset - Return true if the given stack call argument is
3126 /// already available in the same position (relatively) of the caller's
3127 /// incoming argument stack.
3128 static
3129 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3130                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3131                          const X86InstrInfo *TII) {
3132   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3133   int FI = INT_MAX;
3134   if (Arg.getOpcode() == ISD::CopyFromReg) {
3135     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3136     if (!TargetRegisterInfo::isVirtualRegister(VR))
3137       return false;
3138     MachineInstr *Def = MRI->getVRegDef(VR);
3139     if (!Def)
3140       return false;
3141     if (!Flags.isByVal()) {
3142       if (!TII->isLoadFromStackSlot(Def, FI))
3143         return false;
3144     } else {
3145       unsigned Opcode = Def->getOpcode();
3146       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3147           Def->getOperand(1).isFI()) {
3148         FI = Def->getOperand(1).getIndex();
3149         Bytes = Flags.getByValSize();
3150       } else
3151         return false;
3152     }
3153   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3154     if (Flags.isByVal())
3155       // ByVal argument is passed in as a pointer but it's now being
3156       // dereferenced. e.g.
3157       // define @foo(%struct.X* %A) {
3158       //   tail call @bar(%struct.X* byval %A)
3159       // }
3160       return false;
3161     SDValue Ptr = Ld->getBasePtr();
3162     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3163     if (!FINode)
3164       return false;
3165     FI = FINode->getIndex();
3166   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3167     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3168     FI = FINode->getIndex();
3169     Bytes = Flags.getByValSize();
3170   } else
3171     return false;
3172
3173   assert(FI != INT_MAX);
3174   if (!MFI->isFixedObjectIndex(FI))
3175     return false;
3176   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3177 }
3178
3179 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3180 /// for tail call optimization. Targets which want to do tail call
3181 /// optimization should implement this function.
3182 bool
3183 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3184                                                      CallingConv::ID CalleeCC,
3185                                                      bool isVarArg,
3186                                                      bool isCalleeStructRet,
3187                                                      bool isCallerStructRet,
3188                                                      Type *RetTy,
3189                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3190                                     const SmallVectorImpl<SDValue> &OutVals,
3191                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3192                                                      SelectionDAG &DAG) const {
3193   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3194     return false;
3195
3196   // If -tailcallopt is specified, make fastcc functions tail-callable.
3197   const MachineFunction &MF = DAG.getMachineFunction();
3198   const Function *CallerF = MF.getFunction();
3199
3200   // If the function return type is x86_fp80 and the callee return type is not,
3201   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3202   // perform a tailcall optimization here.
3203   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3204     return false;
3205
3206   CallingConv::ID CallerCC = CallerF->getCallingConv();
3207   bool CCMatch = CallerCC == CalleeCC;
3208   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3209   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3210
3211   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3212     if (IsTailCallConvention(CalleeCC) && CCMatch)
3213       return true;
3214     return false;
3215   }
3216
3217   // Look for obvious safe cases to perform tail call optimization that do not
3218   // require ABI changes. This is what gcc calls sibcall.
3219
3220   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3221   // emit a special epilogue.
3222   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3223       DAG.getSubtarget().getRegisterInfo());
3224   if (RegInfo->needsStackRealignment(MF))
3225     return false;
3226
3227   // Also avoid sibcall optimization if either caller or callee uses struct
3228   // return semantics.
3229   if (isCalleeStructRet || isCallerStructRet)
3230     return false;
3231
3232   // An stdcall/thiscall caller is expected to clean up its arguments; the
3233   // callee isn't going to do that.
3234   // FIXME: this is more restrictive than needed. We could produce a tailcall
3235   // when the stack adjustment matches. For example, with a thiscall that takes
3236   // only one argument.
3237   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3238                    CallerCC == CallingConv::X86_ThisCall))
3239     return false;
3240
3241   // Do not sibcall optimize vararg calls unless all arguments are passed via
3242   // registers.
3243   if (isVarArg && !Outs.empty()) {
3244
3245     // Optimizing for varargs on Win64 is unlikely to be safe without
3246     // additional testing.
3247     if (IsCalleeWin64 || IsCallerWin64)
3248       return false;
3249
3250     SmallVector<CCValAssign, 16> ArgLocs;
3251     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3252                    *DAG.getContext());
3253
3254     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3255     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3256       if (!ArgLocs[i].isRegLoc())
3257         return false;
3258   }
3259
3260   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3261   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3262   // this into a sibcall.
3263   bool Unused = false;
3264   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3265     if (!Ins[i].Used) {
3266       Unused = true;
3267       break;
3268     }
3269   }
3270   if (Unused) {
3271     SmallVector<CCValAssign, 16> RVLocs;
3272     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3273                    *DAG.getContext());
3274     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3275     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3276       CCValAssign &VA = RVLocs[i];
3277       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3278         return false;
3279     }
3280   }
3281
3282   // If the calling conventions do not match, then we'd better make sure the
3283   // results are returned in the same way as what the caller expects.
3284   if (!CCMatch) {
3285     SmallVector<CCValAssign, 16> RVLocs1;
3286     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3287                     *DAG.getContext());
3288     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3289
3290     SmallVector<CCValAssign, 16> RVLocs2;
3291     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3292                     *DAG.getContext());
3293     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3294
3295     if (RVLocs1.size() != RVLocs2.size())
3296       return false;
3297     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3298       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3299         return false;
3300       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3301         return false;
3302       if (RVLocs1[i].isRegLoc()) {
3303         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3304           return false;
3305       } else {
3306         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3307           return false;
3308       }
3309     }
3310   }
3311
3312   // If the callee takes no arguments then go on to check the results of the
3313   // call.
3314   if (!Outs.empty()) {
3315     // Check if stack adjustment is needed. For now, do not do this if any
3316     // argument is passed on the stack.
3317     SmallVector<CCValAssign, 16> ArgLocs;
3318     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3319                    *DAG.getContext());
3320
3321     // Allocate shadow area for Win64
3322     if (IsCalleeWin64)
3323       CCInfo.AllocateStack(32, 8);
3324
3325     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3326     if (CCInfo.getNextStackOffset()) {
3327       MachineFunction &MF = DAG.getMachineFunction();
3328       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3329         return false;
3330
3331       // Check if the arguments are already laid out in the right way as
3332       // the caller's fixed stack objects.
3333       MachineFrameInfo *MFI = MF.getFrameInfo();
3334       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3335       const X86InstrInfo *TII =
3336           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3337       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3338         CCValAssign &VA = ArgLocs[i];
3339         SDValue Arg = OutVals[i];
3340         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3341         if (VA.getLocInfo() == CCValAssign::Indirect)
3342           return false;
3343         if (!VA.isRegLoc()) {
3344           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3345                                    MFI, MRI, TII))
3346             return false;
3347         }
3348       }
3349     }
3350
3351     // If the tailcall address may be in a register, then make sure it's
3352     // possible to register allocate for it. In 32-bit, the call address can
3353     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3354     // callee-saved registers are restored. These happen to be the same
3355     // registers used to pass 'inreg' arguments so watch out for those.
3356     if (!Subtarget->is64Bit() &&
3357         ((!isa<GlobalAddressSDNode>(Callee) &&
3358           !isa<ExternalSymbolSDNode>(Callee)) ||
3359          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3360       unsigned NumInRegs = 0;
3361       // In PIC we need an extra register to formulate the address computation
3362       // for the callee.
3363       unsigned MaxInRegs =
3364         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3365
3366       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3367         CCValAssign &VA = ArgLocs[i];
3368         if (!VA.isRegLoc())
3369           continue;
3370         unsigned Reg = VA.getLocReg();
3371         switch (Reg) {
3372         default: break;
3373         case X86::EAX: case X86::EDX: case X86::ECX:
3374           if (++NumInRegs == MaxInRegs)
3375             return false;
3376           break;
3377         }
3378       }
3379     }
3380   }
3381
3382   return true;
3383 }
3384
3385 FastISel *
3386 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3387                                   const TargetLibraryInfo *libInfo) const {
3388   return X86::createFastISel(funcInfo, libInfo);
3389 }
3390
3391 //===----------------------------------------------------------------------===//
3392 //                           Other Lowering Hooks
3393 //===----------------------------------------------------------------------===//
3394
3395 static bool MayFoldLoad(SDValue Op) {
3396   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3397 }
3398
3399 static bool MayFoldIntoStore(SDValue Op) {
3400   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3401 }
3402
3403 static bool isTargetShuffle(unsigned Opcode) {
3404   switch(Opcode) {
3405   default: return false;
3406   case X86ISD::PSHUFB:
3407   case X86ISD::PSHUFD:
3408   case X86ISD::PSHUFHW:
3409   case X86ISD::PSHUFLW:
3410   case X86ISD::SHUFP:
3411   case X86ISD::PALIGNR:
3412   case X86ISD::MOVLHPS:
3413   case X86ISD::MOVLHPD:
3414   case X86ISD::MOVHLPS:
3415   case X86ISD::MOVLPS:
3416   case X86ISD::MOVLPD:
3417   case X86ISD::MOVSHDUP:
3418   case X86ISD::MOVSLDUP:
3419   case X86ISD::MOVDDUP:
3420   case X86ISD::MOVSS:
3421   case X86ISD::MOVSD:
3422   case X86ISD::UNPCKL:
3423   case X86ISD::UNPCKH:
3424   case X86ISD::VPERMILP:
3425   case X86ISD::VPERM2X128:
3426   case X86ISD::VPERMI:
3427     return true;
3428   }
3429 }
3430
3431 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3432                                     SDValue V1, SelectionDAG &DAG) {
3433   switch(Opc) {
3434   default: llvm_unreachable("Unknown x86 shuffle node");
3435   case X86ISD::MOVSHDUP:
3436   case X86ISD::MOVSLDUP:
3437   case X86ISD::MOVDDUP:
3438     return DAG.getNode(Opc, dl, VT, V1);
3439   }
3440 }
3441
3442 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3443                                     SDValue V1, unsigned TargetMask,
3444                                     SelectionDAG &DAG) {
3445   switch(Opc) {
3446   default: llvm_unreachable("Unknown x86 shuffle node");
3447   case X86ISD::PSHUFD:
3448   case X86ISD::PSHUFHW:
3449   case X86ISD::PSHUFLW:
3450   case X86ISD::VPERMILP:
3451   case X86ISD::VPERMI:
3452     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3453   }
3454 }
3455
3456 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3457                                     SDValue V1, SDValue V2, unsigned TargetMask,
3458                                     SelectionDAG &DAG) {
3459   switch(Opc) {
3460   default: llvm_unreachable("Unknown x86 shuffle node");
3461   case X86ISD::PALIGNR:
3462   case X86ISD::VALIGN:
3463   case X86ISD::SHUFP:
3464   case X86ISD::VPERM2X128:
3465     return DAG.getNode(Opc, dl, VT, V1, V2,
3466                        DAG.getConstant(TargetMask, MVT::i8));
3467   }
3468 }
3469
3470 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3471                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3472   switch(Opc) {
3473   default: llvm_unreachable("Unknown x86 shuffle node");
3474   case X86ISD::MOVLHPS:
3475   case X86ISD::MOVLHPD:
3476   case X86ISD::MOVHLPS:
3477   case X86ISD::MOVLPS:
3478   case X86ISD::MOVLPD:
3479   case X86ISD::MOVSS:
3480   case X86ISD::MOVSD:
3481   case X86ISD::UNPCKL:
3482   case X86ISD::UNPCKH:
3483     return DAG.getNode(Opc, dl, VT, V1, V2);
3484   }
3485 }
3486
3487 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3488   MachineFunction &MF = DAG.getMachineFunction();
3489   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3490       DAG.getSubtarget().getRegisterInfo());
3491   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3492   int ReturnAddrIndex = FuncInfo->getRAIndex();
3493
3494   if (ReturnAddrIndex == 0) {
3495     // Set up a frame object for the return address.
3496     unsigned SlotSize = RegInfo->getSlotSize();
3497     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3498                                                            -(int64_t)SlotSize,
3499                                                            false);
3500     FuncInfo->setRAIndex(ReturnAddrIndex);
3501   }
3502
3503   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3504 }
3505
3506 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3507                                        bool hasSymbolicDisplacement) {
3508   // Offset should fit into 32 bit immediate field.
3509   if (!isInt<32>(Offset))
3510     return false;
3511
3512   // If we don't have a symbolic displacement - we don't have any extra
3513   // restrictions.
3514   if (!hasSymbolicDisplacement)
3515     return true;
3516
3517   // FIXME: Some tweaks might be needed for medium code model.
3518   if (M != CodeModel::Small && M != CodeModel::Kernel)
3519     return false;
3520
3521   // For small code model we assume that latest object is 16MB before end of 31
3522   // bits boundary. We may also accept pretty large negative constants knowing
3523   // that all objects are in the positive half of address space.
3524   if (M == CodeModel::Small && Offset < 16*1024*1024)
3525     return true;
3526
3527   // For kernel code model we know that all object resist in the negative half
3528   // of 32bits address space. We may not accept negative offsets, since they may
3529   // be just off and we may accept pretty large positive ones.
3530   if (M == CodeModel::Kernel && Offset > 0)
3531     return true;
3532
3533   return false;
3534 }
3535
3536 /// isCalleePop - Determines whether the callee is required to pop its
3537 /// own arguments. Callee pop is necessary to support tail calls.
3538 bool X86::isCalleePop(CallingConv::ID CallingConv,
3539                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3540   if (IsVarArg)
3541     return false;
3542
3543   switch (CallingConv) {
3544   default:
3545     return false;
3546   case CallingConv::X86_StdCall:
3547     return !is64Bit;
3548   case CallingConv::X86_FastCall:
3549     return !is64Bit;
3550   case CallingConv::X86_ThisCall:
3551     return !is64Bit;
3552   case CallingConv::Fast:
3553     return TailCallOpt;
3554   case CallingConv::GHC:
3555     return TailCallOpt;
3556   case CallingConv::HiPE:
3557     return TailCallOpt;
3558   }
3559 }
3560
3561 /// \brief Return true if the condition is an unsigned comparison operation.
3562 static bool isX86CCUnsigned(unsigned X86CC) {
3563   switch (X86CC) {
3564   default: llvm_unreachable("Invalid integer condition!");
3565   case X86::COND_E:     return true;
3566   case X86::COND_G:     return false;
3567   case X86::COND_GE:    return false;
3568   case X86::COND_L:     return false;
3569   case X86::COND_LE:    return false;
3570   case X86::COND_NE:    return true;
3571   case X86::COND_B:     return true;
3572   case X86::COND_A:     return true;
3573   case X86::COND_BE:    return true;
3574   case X86::COND_AE:    return true;
3575   }
3576   llvm_unreachable("covered switch fell through?!");
3577 }
3578
3579 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3580 /// specific condition code, returning the condition code and the LHS/RHS of the
3581 /// comparison to make.
3582 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3583                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3584   if (!isFP) {
3585     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3586       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3587         // X > -1   -> X == 0, jump !sign.
3588         RHS = DAG.getConstant(0, RHS.getValueType());
3589         return X86::COND_NS;
3590       }
3591       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3592         // X < 0   -> X == 0, jump on sign.
3593         return X86::COND_S;
3594       }
3595       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3596         // X < 1   -> X <= 0
3597         RHS = DAG.getConstant(0, RHS.getValueType());
3598         return X86::COND_LE;
3599       }
3600     }
3601
3602     switch (SetCCOpcode) {
3603     default: llvm_unreachable("Invalid integer condition!");
3604     case ISD::SETEQ:  return X86::COND_E;
3605     case ISD::SETGT:  return X86::COND_G;
3606     case ISD::SETGE:  return X86::COND_GE;
3607     case ISD::SETLT:  return X86::COND_L;
3608     case ISD::SETLE:  return X86::COND_LE;
3609     case ISD::SETNE:  return X86::COND_NE;
3610     case ISD::SETULT: return X86::COND_B;
3611     case ISD::SETUGT: return X86::COND_A;
3612     case ISD::SETULE: return X86::COND_BE;
3613     case ISD::SETUGE: return X86::COND_AE;
3614     }
3615   }
3616
3617   // First determine if it is required or is profitable to flip the operands.
3618
3619   // If LHS is a foldable load, but RHS is not, flip the condition.
3620   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3621       !ISD::isNON_EXTLoad(RHS.getNode())) {
3622     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3623     std::swap(LHS, RHS);
3624   }
3625
3626   switch (SetCCOpcode) {
3627   default: break;
3628   case ISD::SETOLT:
3629   case ISD::SETOLE:
3630   case ISD::SETUGT:
3631   case ISD::SETUGE:
3632     std::swap(LHS, RHS);
3633     break;
3634   }
3635
3636   // On a floating point condition, the flags are set as follows:
3637   // ZF  PF  CF   op
3638   //  0 | 0 | 0 | X > Y
3639   //  0 | 0 | 1 | X < Y
3640   //  1 | 0 | 0 | X == Y
3641   //  1 | 1 | 1 | unordered
3642   switch (SetCCOpcode) {
3643   default: llvm_unreachable("Condcode should be pre-legalized away");
3644   case ISD::SETUEQ:
3645   case ISD::SETEQ:   return X86::COND_E;
3646   case ISD::SETOLT:              // flipped
3647   case ISD::SETOGT:
3648   case ISD::SETGT:   return X86::COND_A;
3649   case ISD::SETOLE:              // flipped
3650   case ISD::SETOGE:
3651   case ISD::SETGE:   return X86::COND_AE;
3652   case ISD::SETUGT:              // flipped
3653   case ISD::SETULT:
3654   case ISD::SETLT:   return X86::COND_B;
3655   case ISD::SETUGE:              // flipped
3656   case ISD::SETULE:
3657   case ISD::SETLE:   return X86::COND_BE;
3658   case ISD::SETONE:
3659   case ISD::SETNE:   return X86::COND_NE;
3660   case ISD::SETUO:   return X86::COND_P;
3661   case ISD::SETO:    return X86::COND_NP;
3662   case ISD::SETOEQ:
3663   case ISD::SETUNE:  return X86::COND_INVALID;
3664   }
3665 }
3666
3667 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3668 /// code. Current x86 isa includes the following FP cmov instructions:
3669 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3670 static bool hasFPCMov(unsigned X86CC) {
3671   switch (X86CC) {
3672   default:
3673     return false;
3674   case X86::COND_B:
3675   case X86::COND_BE:
3676   case X86::COND_E:
3677   case X86::COND_P:
3678   case X86::COND_A:
3679   case X86::COND_AE:
3680   case X86::COND_NE:
3681   case X86::COND_NP:
3682     return true;
3683   }
3684 }
3685
3686 /// isFPImmLegal - Returns true if the target can instruction select the
3687 /// specified FP immediate natively. If false, the legalizer will
3688 /// materialize the FP immediate as a load from a constant pool.
3689 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3690   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3691     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3692       return true;
3693   }
3694   return false;
3695 }
3696
3697 /// \brief Returns true if it is beneficial to convert a load of a constant
3698 /// to just the constant itself.
3699 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3700                                                           Type *Ty) const {
3701   assert(Ty->isIntegerTy());
3702
3703   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3704   if (BitSize == 0 || BitSize > 64)
3705     return false;
3706   return true;
3707 }
3708
3709 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3710 /// the specified range (L, H].
3711 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3712   return (Val < 0) || (Val >= Low && Val < Hi);
3713 }
3714
3715 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3716 /// specified value.
3717 static bool isUndefOrEqual(int Val, int CmpVal) {
3718   return (Val < 0 || Val == CmpVal);
3719 }
3720
3721 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3722 /// from position Pos and ending in Pos+Size, falls within the specified
3723 /// sequential range (L, L+Pos]. or is undef.
3724 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3725                                        unsigned Pos, unsigned Size, int Low) {
3726   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3727     if (!isUndefOrEqual(Mask[i], Low))
3728       return false;
3729   return true;
3730 }
3731
3732 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3733 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3734 /// the second operand.
3735 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3736   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3737     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3738   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3739     return (Mask[0] < 2 && Mask[1] < 2);
3740   return false;
3741 }
3742
3743 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3744 /// is suitable for input to PSHUFHW.
3745 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3746   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3747     return false;
3748
3749   // Lower quadword copied in order or undef.
3750   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3751     return false;
3752
3753   // Upper quadword shuffled.
3754   for (unsigned i = 4; i != 8; ++i)
3755     if (!isUndefOrInRange(Mask[i], 4, 8))
3756       return false;
3757
3758   if (VT == MVT::v16i16) {
3759     // Lower quadword copied in order or undef.
3760     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3761       return false;
3762
3763     // Upper quadword shuffled.
3764     for (unsigned i = 12; i != 16; ++i)
3765       if (!isUndefOrInRange(Mask[i], 12, 16))
3766         return false;
3767   }
3768
3769   return true;
3770 }
3771
3772 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3773 /// is suitable for input to PSHUFLW.
3774 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3775   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3776     return false;
3777
3778   // Upper quadword copied in order.
3779   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3780     return false;
3781
3782   // Lower quadword shuffled.
3783   for (unsigned i = 0; i != 4; ++i)
3784     if (!isUndefOrInRange(Mask[i], 0, 4))
3785       return false;
3786
3787   if (VT == MVT::v16i16) {
3788     // Upper quadword copied in order.
3789     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3790       return false;
3791
3792     // Lower quadword shuffled.
3793     for (unsigned i = 8; i != 12; ++i)
3794       if (!isUndefOrInRange(Mask[i], 8, 12))
3795         return false;
3796   }
3797
3798   return true;
3799 }
3800
3801 /// \brief Return true if the mask specifies a shuffle of elements that is
3802 /// suitable for input to intralane (palignr) or interlane (valign) vector
3803 /// right-shift.
3804 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3805   unsigned NumElts = VT.getVectorNumElements();
3806   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3807   unsigned NumLaneElts = NumElts/NumLanes;
3808
3809   // Do not handle 64-bit element shuffles with palignr.
3810   if (NumLaneElts == 2)
3811     return false;
3812
3813   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3814     unsigned i;
3815     for (i = 0; i != NumLaneElts; ++i) {
3816       if (Mask[i+l] >= 0)
3817         break;
3818     }
3819
3820     // Lane is all undef, go to next lane
3821     if (i == NumLaneElts)
3822       continue;
3823
3824     int Start = Mask[i+l];
3825
3826     // Make sure its in this lane in one of the sources
3827     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3828         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3829       return false;
3830
3831     // If not lane 0, then we must match lane 0
3832     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3833       return false;
3834
3835     // Correct second source to be contiguous with first source
3836     if (Start >= (int)NumElts)
3837       Start -= NumElts - NumLaneElts;
3838
3839     // Make sure we're shifting in the right direction.
3840     if (Start <= (int)(i+l))
3841       return false;
3842
3843     Start -= i;
3844
3845     // Check the rest of the elements to see if they are consecutive.
3846     for (++i; i != NumLaneElts; ++i) {
3847       int Idx = Mask[i+l];
3848
3849       // Make sure its in this lane
3850       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3851           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3852         return false;
3853
3854       // If not lane 0, then we must match lane 0
3855       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3856         return false;
3857
3858       if (Idx >= (int)NumElts)
3859         Idx -= NumElts - NumLaneElts;
3860
3861       if (!isUndefOrEqual(Idx, Start+i))
3862         return false;
3863
3864     }
3865   }
3866
3867   return true;
3868 }
3869
3870 /// \brief Return true if the node specifies a shuffle of elements that is
3871 /// suitable for input to PALIGNR.
3872 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3873                           const X86Subtarget *Subtarget) {
3874   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3875       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
3876       VT.is512BitVector())
3877     // FIXME: Add AVX512BW.
3878     return false;
3879
3880   return isAlignrMask(Mask, VT, false);
3881 }
3882
3883 /// \brief Return true if the node specifies a shuffle of elements that is
3884 /// suitable for input to VALIGN.
3885 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
3886                           const X86Subtarget *Subtarget) {
3887   // FIXME: Add AVX512VL.
3888   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
3889     return false;
3890   return isAlignrMask(Mask, VT, true);
3891 }
3892
3893 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3894 /// the two vector operands have swapped position.
3895 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3896                                      unsigned NumElems) {
3897   for (unsigned i = 0; i != NumElems; ++i) {
3898     int idx = Mask[i];
3899     if (idx < 0)
3900       continue;
3901     else if (idx < (int)NumElems)
3902       Mask[i] = idx + NumElems;
3903     else
3904       Mask[i] = idx - NumElems;
3905   }
3906 }
3907
3908 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3909 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3910 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3911 /// reverse of what x86 shuffles want.
3912 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3913
3914   unsigned NumElems = VT.getVectorNumElements();
3915   unsigned NumLanes = VT.getSizeInBits()/128;
3916   unsigned NumLaneElems = NumElems/NumLanes;
3917
3918   if (NumLaneElems != 2 && NumLaneElems != 4)
3919     return false;
3920
3921   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3922   bool symetricMaskRequired =
3923     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3924
3925   // VSHUFPSY divides the resulting vector into 4 chunks.
3926   // The sources are also splitted into 4 chunks, and each destination
3927   // chunk must come from a different source chunk.
3928   //
3929   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3930   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3931   //
3932   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3933   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3934   //
3935   // VSHUFPDY divides the resulting vector into 4 chunks.
3936   // The sources are also splitted into 4 chunks, and each destination
3937   // chunk must come from a different source chunk.
3938   //
3939   //  SRC1 =>      X3       X2       X1       X0
3940   //  SRC2 =>      Y3       Y2       Y1       Y0
3941   //
3942   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3943   //
3944   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3945   unsigned HalfLaneElems = NumLaneElems/2;
3946   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3947     for (unsigned i = 0; i != NumLaneElems; ++i) {
3948       int Idx = Mask[i+l];
3949       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3950       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3951         return false;
3952       // For VSHUFPSY, the mask of the second half must be the same as the
3953       // first but with the appropriate offsets. This works in the same way as
3954       // VPERMILPS works with masks.
3955       if (!symetricMaskRequired || Idx < 0)
3956         continue;
3957       if (MaskVal[i] < 0) {
3958         MaskVal[i] = Idx - l;
3959         continue;
3960       }
3961       if ((signed)(Idx - l) != MaskVal[i])
3962         return false;
3963     }
3964   }
3965
3966   return true;
3967 }
3968
3969 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3970 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3971 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3972   if (!VT.is128BitVector())
3973     return false;
3974
3975   unsigned NumElems = VT.getVectorNumElements();
3976
3977   if (NumElems != 4)
3978     return false;
3979
3980   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3981   return isUndefOrEqual(Mask[0], 6) &&
3982          isUndefOrEqual(Mask[1], 7) &&
3983          isUndefOrEqual(Mask[2], 2) &&
3984          isUndefOrEqual(Mask[3], 3);
3985 }
3986
3987 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3988 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3989 /// <2, 3, 2, 3>
3990 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3991   if (!VT.is128BitVector())
3992     return false;
3993
3994   unsigned NumElems = VT.getVectorNumElements();
3995
3996   if (NumElems != 4)
3997     return false;
3998
3999   return isUndefOrEqual(Mask[0], 2) &&
4000          isUndefOrEqual(Mask[1], 3) &&
4001          isUndefOrEqual(Mask[2], 2) &&
4002          isUndefOrEqual(Mask[3], 3);
4003 }
4004
4005 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4006 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4007 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4008   if (!VT.is128BitVector())
4009     return false;
4010
4011   unsigned NumElems = VT.getVectorNumElements();
4012
4013   if (NumElems != 2 && NumElems != 4)
4014     return false;
4015
4016   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4017     if (!isUndefOrEqual(Mask[i], i + NumElems))
4018       return false;
4019
4020   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4021     if (!isUndefOrEqual(Mask[i], i))
4022       return false;
4023
4024   return true;
4025 }
4026
4027 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4028 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4029 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4030   if (!VT.is128BitVector())
4031     return false;
4032
4033   unsigned NumElems = VT.getVectorNumElements();
4034
4035   if (NumElems != 2 && NumElems != 4)
4036     return false;
4037
4038   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4039     if (!isUndefOrEqual(Mask[i], i))
4040       return false;
4041
4042   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4043     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4044       return false;
4045
4046   return true;
4047 }
4048
4049 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4050 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4051 /// i. e: If all but one element come from the same vector.
4052 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4053   // TODO: Deal with AVX's VINSERTPS
4054   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4055     return false;
4056
4057   unsigned CorrectPosV1 = 0;
4058   unsigned CorrectPosV2 = 0;
4059   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4060     if (Mask[i] == -1) {
4061       ++CorrectPosV1;
4062       ++CorrectPosV2;
4063       continue;
4064     }
4065
4066     if (Mask[i] == i)
4067       ++CorrectPosV1;
4068     else if (Mask[i] == i + 4)
4069       ++CorrectPosV2;
4070   }
4071
4072   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4073     // We have 3 elements (undefs count as elements from any vector) from one
4074     // vector, and one from another.
4075     return true;
4076
4077   return false;
4078 }
4079
4080 //
4081 // Some special combinations that can be optimized.
4082 //
4083 static
4084 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4085                                SelectionDAG &DAG) {
4086   MVT VT = SVOp->getSimpleValueType(0);
4087   SDLoc dl(SVOp);
4088
4089   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4090     return SDValue();
4091
4092   ArrayRef<int> Mask = SVOp->getMask();
4093
4094   // These are the special masks that may be optimized.
4095   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4096   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4097   bool MatchEvenMask = true;
4098   bool MatchOddMask  = true;
4099   for (int i=0; i<8; ++i) {
4100     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4101       MatchEvenMask = false;
4102     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4103       MatchOddMask = false;
4104   }
4105
4106   if (!MatchEvenMask && !MatchOddMask)
4107     return SDValue();
4108
4109   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4110
4111   SDValue Op0 = SVOp->getOperand(0);
4112   SDValue Op1 = SVOp->getOperand(1);
4113
4114   if (MatchEvenMask) {
4115     // Shift the second operand right to 32 bits.
4116     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4117     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4118   } else {
4119     // Shift the first operand left to 32 bits.
4120     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4121     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4122   }
4123   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4124   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4125 }
4126
4127 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4128 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4129 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4130                          bool HasInt256, bool V2IsSplat = false) {
4131
4132   assert(VT.getSizeInBits() >= 128 &&
4133          "Unsupported vector type for unpckl");
4134
4135   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4136   unsigned NumLanes;
4137   unsigned NumOf256BitLanes;
4138   unsigned NumElts = VT.getVectorNumElements();
4139   if (VT.is256BitVector()) {
4140     if (NumElts != 4 && NumElts != 8 &&
4141         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4142     return false;
4143     NumLanes = 2;
4144     NumOf256BitLanes = 1;
4145   } else if (VT.is512BitVector()) {
4146     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4147            "Unsupported vector type for unpckh");
4148     NumLanes = 2;
4149     NumOf256BitLanes = 2;
4150   } else {
4151     NumLanes = 1;
4152     NumOf256BitLanes = 1;
4153   }
4154
4155   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4156   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4157
4158   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4159     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4160       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4161         int BitI  = Mask[l256*NumEltsInStride+l+i];
4162         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4163         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4164           return false;
4165         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4166           return false;
4167         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4168           return false;
4169       }
4170     }
4171   }
4172   return true;
4173 }
4174
4175 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4176 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4177 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4178                          bool HasInt256, bool V2IsSplat = false) {
4179   assert(VT.getSizeInBits() >= 128 &&
4180          "Unsupported vector type for unpckh");
4181
4182   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4183   unsigned NumLanes;
4184   unsigned NumOf256BitLanes;
4185   unsigned NumElts = VT.getVectorNumElements();
4186   if (VT.is256BitVector()) {
4187     if (NumElts != 4 && NumElts != 8 &&
4188         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4189     return false;
4190     NumLanes = 2;
4191     NumOf256BitLanes = 1;
4192   } else if (VT.is512BitVector()) {
4193     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4194            "Unsupported vector type for unpckh");
4195     NumLanes = 2;
4196     NumOf256BitLanes = 2;
4197   } else {
4198     NumLanes = 1;
4199     NumOf256BitLanes = 1;
4200   }
4201
4202   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4203   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4204
4205   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4206     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4207       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4208         int BitI  = Mask[l256*NumEltsInStride+l+i];
4209         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4210         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4211           return false;
4212         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4213           return false;
4214         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4215           return false;
4216       }
4217     }
4218   }
4219   return true;
4220 }
4221
4222 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4223 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4224 /// <0, 0, 1, 1>
4225 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4226   unsigned NumElts = VT.getVectorNumElements();
4227   bool Is256BitVec = VT.is256BitVector();
4228
4229   if (VT.is512BitVector())
4230     return false;
4231   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4232          "Unsupported vector type for unpckh");
4233
4234   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4235       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4236     return false;
4237
4238   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4239   // FIXME: Need a better way to get rid of this, there's no latency difference
4240   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4241   // the former later. We should also remove the "_undef" special mask.
4242   if (NumElts == 4 && Is256BitVec)
4243     return false;
4244
4245   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4246   // independently on 128-bit lanes.
4247   unsigned NumLanes = VT.getSizeInBits()/128;
4248   unsigned NumLaneElts = NumElts/NumLanes;
4249
4250   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4251     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4252       int BitI  = Mask[l+i];
4253       int BitI1 = Mask[l+i+1];
4254
4255       if (!isUndefOrEqual(BitI, j))
4256         return false;
4257       if (!isUndefOrEqual(BitI1, j))
4258         return false;
4259     }
4260   }
4261
4262   return true;
4263 }
4264
4265 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4266 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4267 /// <2, 2, 3, 3>
4268 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4269   unsigned NumElts = VT.getVectorNumElements();
4270
4271   if (VT.is512BitVector())
4272     return false;
4273
4274   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4275          "Unsupported vector type for unpckh");
4276
4277   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4278       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4279     return false;
4280
4281   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4282   // independently on 128-bit lanes.
4283   unsigned NumLanes = VT.getSizeInBits()/128;
4284   unsigned NumLaneElts = NumElts/NumLanes;
4285
4286   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4287     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4288       int BitI  = Mask[l+i];
4289       int BitI1 = Mask[l+i+1];
4290       if (!isUndefOrEqual(BitI, j))
4291         return false;
4292       if (!isUndefOrEqual(BitI1, j))
4293         return false;
4294     }
4295   }
4296   return true;
4297 }
4298
4299 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4300 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4301 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4302   if (!VT.is512BitVector())
4303     return false;
4304
4305   unsigned NumElts = VT.getVectorNumElements();
4306   unsigned HalfSize = NumElts/2;
4307   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4308     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4309       *Imm = 1;
4310       return true;
4311     }
4312   }
4313   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4314     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4315       *Imm = 0;
4316       return true;
4317     }
4318   }
4319   return false;
4320 }
4321
4322 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4323 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4324 /// MOVSD, and MOVD, i.e. setting the lowest element.
4325 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4326   if (VT.getVectorElementType().getSizeInBits() < 32)
4327     return false;
4328   if (!VT.is128BitVector())
4329     return false;
4330
4331   unsigned NumElts = VT.getVectorNumElements();
4332
4333   if (!isUndefOrEqual(Mask[0], NumElts))
4334     return false;
4335
4336   for (unsigned i = 1; i != NumElts; ++i)
4337     if (!isUndefOrEqual(Mask[i], i))
4338       return false;
4339
4340   return true;
4341 }
4342
4343 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4344 /// as permutations between 128-bit chunks or halves. As an example: this
4345 /// shuffle bellow:
4346 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4347 /// The first half comes from the second half of V1 and the second half from the
4348 /// the second half of V2.
4349 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4350   if (!HasFp256 || !VT.is256BitVector())
4351     return false;
4352
4353   // The shuffle result is divided into half A and half B. In total the two
4354   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4355   // B must come from C, D, E or F.
4356   unsigned HalfSize = VT.getVectorNumElements()/2;
4357   bool MatchA = false, MatchB = false;
4358
4359   // Check if A comes from one of C, D, E, F.
4360   for (unsigned Half = 0; Half != 4; ++Half) {
4361     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4362       MatchA = true;
4363       break;
4364     }
4365   }
4366
4367   // Check if B comes from one of C, D, E, F.
4368   for (unsigned Half = 0; Half != 4; ++Half) {
4369     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4370       MatchB = true;
4371       break;
4372     }
4373   }
4374
4375   return MatchA && MatchB;
4376 }
4377
4378 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4379 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4380 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4381   MVT VT = SVOp->getSimpleValueType(0);
4382
4383   unsigned HalfSize = VT.getVectorNumElements()/2;
4384
4385   unsigned FstHalf = 0, SndHalf = 0;
4386   for (unsigned i = 0; i < HalfSize; ++i) {
4387     if (SVOp->getMaskElt(i) > 0) {
4388       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4389       break;
4390     }
4391   }
4392   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4393     if (SVOp->getMaskElt(i) > 0) {
4394       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4395       break;
4396     }
4397   }
4398
4399   return (FstHalf | (SndHalf << 4));
4400 }
4401
4402 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4403 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4404   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4405   if (EltSize < 32)
4406     return false;
4407
4408   unsigned NumElts = VT.getVectorNumElements();
4409   Imm8 = 0;
4410   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4411     for (unsigned i = 0; i != NumElts; ++i) {
4412       if (Mask[i] < 0)
4413         continue;
4414       Imm8 |= Mask[i] << (i*2);
4415     }
4416     return true;
4417   }
4418
4419   unsigned LaneSize = 4;
4420   SmallVector<int, 4> MaskVal(LaneSize, -1);
4421
4422   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4423     for (unsigned i = 0; i != LaneSize; ++i) {
4424       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4425         return false;
4426       if (Mask[i+l] < 0)
4427         continue;
4428       if (MaskVal[i] < 0) {
4429         MaskVal[i] = Mask[i+l] - l;
4430         Imm8 |= MaskVal[i] << (i*2);
4431         continue;
4432       }
4433       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4434         return false;
4435     }
4436   }
4437   return true;
4438 }
4439
4440 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4441 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4442 /// Note that VPERMIL mask matching is different depending whether theunderlying
4443 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4444 /// to the same elements of the low, but to the higher half of the source.
4445 /// In VPERMILPD the two lanes could be shuffled independently of each other
4446 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4447 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4448   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4449   if (VT.getSizeInBits() < 256 || EltSize < 32)
4450     return false;
4451   bool symetricMaskRequired = (EltSize == 32);
4452   unsigned NumElts = VT.getVectorNumElements();
4453
4454   unsigned NumLanes = VT.getSizeInBits()/128;
4455   unsigned LaneSize = NumElts/NumLanes;
4456   // 2 or 4 elements in one lane
4457
4458   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4459   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4460     for (unsigned i = 0; i != LaneSize; ++i) {
4461       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4462         return false;
4463       if (symetricMaskRequired) {
4464         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4465           ExpectedMaskVal[i] = Mask[i+l] - l;
4466           continue;
4467         }
4468         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4469           return false;
4470       }
4471     }
4472   }
4473   return true;
4474 }
4475
4476 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4477 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4478 /// element of vector 2 and the other elements to come from vector 1 in order.
4479 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4480                                bool V2IsSplat = false, bool V2IsUndef = false) {
4481   if (!VT.is128BitVector())
4482     return false;
4483
4484   unsigned NumOps = VT.getVectorNumElements();
4485   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4486     return false;
4487
4488   if (!isUndefOrEqual(Mask[0], 0))
4489     return false;
4490
4491   for (unsigned i = 1; i != NumOps; ++i)
4492     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4493           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4494           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4495       return false;
4496
4497   return true;
4498 }
4499
4500 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4501 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4502 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4503 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4504                            const X86Subtarget *Subtarget) {
4505   if (!Subtarget->hasSSE3())
4506     return false;
4507
4508   unsigned NumElems = VT.getVectorNumElements();
4509
4510   if ((VT.is128BitVector() && NumElems != 4) ||
4511       (VT.is256BitVector() && NumElems != 8) ||
4512       (VT.is512BitVector() && NumElems != 16))
4513     return false;
4514
4515   // "i+1" is the value the indexed mask element must have
4516   for (unsigned i = 0; i != NumElems; i += 2)
4517     if (!isUndefOrEqual(Mask[i], i+1) ||
4518         !isUndefOrEqual(Mask[i+1], i+1))
4519       return false;
4520
4521   return true;
4522 }
4523
4524 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4525 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4526 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4527 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4528                            const X86Subtarget *Subtarget) {
4529   if (!Subtarget->hasSSE3())
4530     return false;
4531
4532   unsigned NumElems = VT.getVectorNumElements();
4533
4534   if ((VT.is128BitVector() && NumElems != 4) ||
4535       (VT.is256BitVector() && NumElems != 8) ||
4536       (VT.is512BitVector() && NumElems != 16))
4537     return false;
4538
4539   // "i" is the value the indexed mask element must have
4540   for (unsigned i = 0; i != NumElems; i += 2)
4541     if (!isUndefOrEqual(Mask[i], i) ||
4542         !isUndefOrEqual(Mask[i+1], i))
4543       return false;
4544
4545   return true;
4546 }
4547
4548 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4549 /// specifies a shuffle of elements that is suitable for input to 256-bit
4550 /// version of MOVDDUP.
4551 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4552   if (!HasFp256 || !VT.is256BitVector())
4553     return false;
4554
4555   unsigned NumElts = VT.getVectorNumElements();
4556   if (NumElts != 4)
4557     return false;
4558
4559   for (unsigned i = 0; i != NumElts/2; ++i)
4560     if (!isUndefOrEqual(Mask[i], 0))
4561       return false;
4562   for (unsigned i = NumElts/2; i != NumElts; ++i)
4563     if (!isUndefOrEqual(Mask[i], NumElts/2))
4564       return false;
4565   return true;
4566 }
4567
4568 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4569 /// specifies a shuffle of elements that is suitable for input to 128-bit
4570 /// version of MOVDDUP.
4571 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4572   if (!VT.is128BitVector())
4573     return false;
4574
4575   unsigned e = VT.getVectorNumElements() / 2;
4576   for (unsigned i = 0; i != e; ++i)
4577     if (!isUndefOrEqual(Mask[i], i))
4578       return false;
4579   for (unsigned i = 0; i != e; ++i)
4580     if (!isUndefOrEqual(Mask[e+i], i))
4581       return false;
4582   return true;
4583 }
4584
4585 /// isVEXTRACTIndex - Return true if the specified
4586 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4587 /// suitable for instruction that extract 128 or 256 bit vectors
4588 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4589   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4590   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4591     return false;
4592
4593   // The index should be aligned on a vecWidth-bit boundary.
4594   uint64_t Index =
4595     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4596
4597   MVT VT = N->getSimpleValueType(0);
4598   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4599   bool Result = (Index * ElSize) % vecWidth == 0;
4600
4601   return Result;
4602 }
4603
4604 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4605 /// operand specifies a subvector insert that is suitable for input to
4606 /// insertion of 128 or 256-bit subvectors
4607 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4608   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4609   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4610     return false;
4611   // The index should be aligned on a vecWidth-bit boundary.
4612   uint64_t Index =
4613     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4614
4615   MVT VT = N->getSimpleValueType(0);
4616   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4617   bool Result = (Index * ElSize) % vecWidth == 0;
4618
4619   return Result;
4620 }
4621
4622 bool X86::isVINSERT128Index(SDNode *N) {
4623   return isVINSERTIndex(N, 128);
4624 }
4625
4626 bool X86::isVINSERT256Index(SDNode *N) {
4627   return isVINSERTIndex(N, 256);
4628 }
4629
4630 bool X86::isVEXTRACT128Index(SDNode *N) {
4631   return isVEXTRACTIndex(N, 128);
4632 }
4633
4634 bool X86::isVEXTRACT256Index(SDNode *N) {
4635   return isVEXTRACTIndex(N, 256);
4636 }
4637
4638 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4639 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4640 /// Handles 128-bit and 256-bit.
4641 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4642   MVT VT = N->getSimpleValueType(0);
4643
4644   assert((VT.getSizeInBits() >= 128) &&
4645          "Unsupported vector type for PSHUF/SHUFP");
4646
4647   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4648   // independently on 128-bit lanes.
4649   unsigned NumElts = VT.getVectorNumElements();
4650   unsigned NumLanes = VT.getSizeInBits()/128;
4651   unsigned NumLaneElts = NumElts/NumLanes;
4652
4653   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4654          "Only supports 2, 4 or 8 elements per lane");
4655
4656   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4657   unsigned Mask = 0;
4658   for (unsigned i = 0; i != NumElts; ++i) {
4659     int Elt = N->getMaskElt(i);
4660     if (Elt < 0) continue;
4661     Elt &= NumLaneElts - 1;
4662     unsigned ShAmt = (i << Shift) % 8;
4663     Mask |= Elt << ShAmt;
4664   }
4665
4666   return Mask;
4667 }
4668
4669 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4670 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4671 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4672   MVT VT = N->getSimpleValueType(0);
4673
4674   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4675          "Unsupported vector type for PSHUFHW");
4676
4677   unsigned NumElts = VT.getVectorNumElements();
4678
4679   unsigned Mask = 0;
4680   for (unsigned l = 0; l != NumElts; l += 8) {
4681     // 8 nodes per lane, but we only care about the last 4.
4682     for (unsigned i = 0; i < 4; ++i) {
4683       int Elt = N->getMaskElt(l+i+4);
4684       if (Elt < 0) continue;
4685       Elt &= 0x3; // only 2-bits.
4686       Mask |= Elt << (i * 2);
4687     }
4688   }
4689
4690   return Mask;
4691 }
4692
4693 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4694 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4695 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4696   MVT VT = N->getSimpleValueType(0);
4697
4698   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4699          "Unsupported vector type for PSHUFHW");
4700
4701   unsigned NumElts = VT.getVectorNumElements();
4702
4703   unsigned Mask = 0;
4704   for (unsigned l = 0; l != NumElts; l += 8) {
4705     // 8 nodes per lane, but we only care about the first 4.
4706     for (unsigned i = 0; i < 4; ++i) {
4707       int Elt = N->getMaskElt(l+i);
4708       if (Elt < 0) continue;
4709       Elt &= 0x3; // only 2-bits
4710       Mask |= Elt << (i * 2);
4711     }
4712   }
4713
4714   return Mask;
4715 }
4716
4717 /// \brief Return the appropriate immediate to shuffle the specified
4718 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4719 /// VALIGN (if Interlane is true) instructions.
4720 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4721                                            bool InterLane) {
4722   MVT VT = SVOp->getSimpleValueType(0);
4723   unsigned EltSize = InterLane ? 1 :
4724     VT.getVectorElementType().getSizeInBits() >> 3;
4725
4726   unsigned NumElts = VT.getVectorNumElements();
4727   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4728   unsigned NumLaneElts = NumElts/NumLanes;
4729
4730   int Val = 0;
4731   unsigned i;
4732   for (i = 0; i != NumElts; ++i) {
4733     Val = SVOp->getMaskElt(i);
4734     if (Val >= 0)
4735       break;
4736   }
4737   if (Val >= (int)NumElts)
4738     Val -= NumElts - NumLaneElts;
4739
4740   assert(Val - i > 0 && "PALIGNR imm should be positive");
4741   return (Val - i) * EltSize;
4742 }
4743
4744 /// \brief Return the appropriate immediate to shuffle the specified
4745 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4746 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4747   return getShuffleAlignrImmediate(SVOp, false);
4748 }
4749
4750 /// \brief Return the appropriate immediate to shuffle the specified
4751 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4752 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4753   return getShuffleAlignrImmediate(SVOp, true);
4754 }
4755
4756
4757 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4758   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4759   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4760     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4761
4762   uint64_t Index =
4763     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4764
4765   MVT VecVT = N->getOperand(0).getSimpleValueType();
4766   MVT ElVT = VecVT.getVectorElementType();
4767
4768   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4769   return Index / NumElemsPerChunk;
4770 }
4771
4772 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4773   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4774   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4775     llvm_unreachable("Illegal insert subvector for VINSERT");
4776
4777   uint64_t Index =
4778     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4779
4780   MVT VecVT = N->getSimpleValueType(0);
4781   MVT ElVT = VecVT.getVectorElementType();
4782
4783   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4784   return Index / NumElemsPerChunk;
4785 }
4786
4787 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4788 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4789 /// and VINSERTI128 instructions.
4790 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4791   return getExtractVEXTRACTImmediate(N, 128);
4792 }
4793
4794 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4795 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4796 /// and VINSERTI64x4 instructions.
4797 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4798   return getExtractVEXTRACTImmediate(N, 256);
4799 }
4800
4801 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4802 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4803 /// and VINSERTI128 instructions.
4804 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4805   return getInsertVINSERTImmediate(N, 128);
4806 }
4807
4808 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4809 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4810 /// and VINSERTI64x4 instructions.
4811 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4812   return getInsertVINSERTImmediate(N, 256);
4813 }
4814
4815 /// isZero - Returns true if Elt is a constant integer zero
4816 static bool isZero(SDValue V) {
4817   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4818   return C && C->isNullValue();
4819 }
4820
4821 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4822 /// constant +0.0.
4823 bool X86::isZeroNode(SDValue Elt) {
4824   if (isZero(Elt))
4825     return true;
4826   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4827     return CFP->getValueAPF().isPosZero();
4828   return false;
4829 }
4830
4831 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4832 /// match movhlps. The lower half elements should come from upper half of
4833 /// V1 (and in order), and the upper half elements should come from the upper
4834 /// half of V2 (and in order).
4835 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4836   if (!VT.is128BitVector())
4837     return false;
4838   if (VT.getVectorNumElements() != 4)
4839     return false;
4840   for (unsigned i = 0, e = 2; i != e; ++i)
4841     if (!isUndefOrEqual(Mask[i], i+2))
4842       return false;
4843   for (unsigned i = 2; i != 4; ++i)
4844     if (!isUndefOrEqual(Mask[i], i+4))
4845       return false;
4846   return true;
4847 }
4848
4849 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4850 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4851 /// required.
4852 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4853   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4854     return false;
4855   N = N->getOperand(0).getNode();
4856   if (!ISD::isNON_EXTLoad(N))
4857     return false;
4858   if (LD)
4859     *LD = cast<LoadSDNode>(N);
4860   return true;
4861 }
4862
4863 // Test whether the given value is a vector value which will be legalized
4864 // into a load.
4865 static bool WillBeConstantPoolLoad(SDNode *N) {
4866   if (N->getOpcode() != ISD::BUILD_VECTOR)
4867     return false;
4868
4869   // Check for any non-constant elements.
4870   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4871     switch (N->getOperand(i).getNode()->getOpcode()) {
4872     case ISD::UNDEF:
4873     case ISD::ConstantFP:
4874     case ISD::Constant:
4875       break;
4876     default:
4877       return false;
4878     }
4879
4880   // Vectors of all-zeros and all-ones are materialized with special
4881   // instructions rather than being loaded.
4882   return !ISD::isBuildVectorAllZeros(N) &&
4883          !ISD::isBuildVectorAllOnes(N);
4884 }
4885
4886 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4887 /// match movlp{s|d}. The lower half elements should come from lower half of
4888 /// V1 (and in order), and the upper half elements should come from the upper
4889 /// half of V2 (and in order). And since V1 will become the source of the
4890 /// MOVLP, it must be either a vector load or a scalar load to vector.
4891 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4892                                ArrayRef<int> Mask, MVT VT) {
4893   if (!VT.is128BitVector())
4894     return false;
4895
4896   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4897     return false;
4898   // Is V2 is a vector load, don't do this transformation. We will try to use
4899   // load folding shufps op.
4900   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4901     return false;
4902
4903   unsigned NumElems = VT.getVectorNumElements();
4904
4905   if (NumElems != 2 && NumElems != 4)
4906     return false;
4907   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4908     if (!isUndefOrEqual(Mask[i], i))
4909       return false;
4910   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4911     if (!isUndefOrEqual(Mask[i], i+NumElems))
4912       return false;
4913   return true;
4914 }
4915
4916 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4917 /// to an zero vector.
4918 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4919 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4920   SDValue V1 = N->getOperand(0);
4921   SDValue V2 = N->getOperand(1);
4922   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4923   for (unsigned i = 0; i != NumElems; ++i) {
4924     int Idx = N->getMaskElt(i);
4925     if (Idx >= (int)NumElems) {
4926       unsigned Opc = V2.getOpcode();
4927       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4928         continue;
4929       if (Opc != ISD::BUILD_VECTOR ||
4930           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4931         return false;
4932     } else if (Idx >= 0) {
4933       unsigned Opc = V1.getOpcode();
4934       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4935         continue;
4936       if (Opc != ISD::BUILD_VECTOR ||
4937           !X86::isZeroNode(V1.getOperand(Idx)))
4938         return false;
4939     }
4940   }
4941   return true;
4942 }
4943
4944 /// getZeroVector - Returns a vector of specified type with all zero elements.
4945 ///
4946 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4947                              SelectionDAG &DAG, SDLoc dl) {
4948   assert(VT.isVector() && "Expected a vector type");
4949
4950   // Always build SSE zero vectors as <4 x i32> bitcasted
4951   // to their dest type. This ensures they get CSE'd.
4952   SDValue Vec;
4953   if (VT.is128BitVector()) {  // SSE
4954     if (Subtarget->hasSSE2()) {  // SSE2
4955       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4956       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4957     } else { // SSE1
4958       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4959       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4960     }
4961   } else if (VT.is256BitVector()) { // AVX
4962     if (Subtarget->hasInt256()) { // AVX2
4963       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4964       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4965       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4966     } else {
4967       // 256-bit logic and arithmetic instructions in AVX are all
4968       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4969       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4970       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4971       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4972     }
4973   } else if (VT.is512BitVector()) { // AVX-512
4974       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4975       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4976                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4977       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4978   } else if (VT.getScalarType() == MVT::i1) {
4979     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4980     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4981     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4982     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4983   } else
4984     llvm_unreachable("Unexpected vector type");
4985
4986   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4987 }
4988
4989 /// getOnesVector - Returns a vector of specified type with all bits set.
4990 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4991 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4992 /// Then bitcast to their original type, ensuring they get CSE'd.
4993 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4994                              SDLoc dl) {
4995   assert(VT.isVector() && "Expected a vector type");
4996
4997   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4998   SDValue Vec;
4999   if (VT.is256BitVector()) {
5000     if (HasInt256) { // AVX2
5001       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5002       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5003     } else { // AVX
5004       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5005       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5006     }
5007   } else if (VT.is128BitVector()) {
5008     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5009   } else
5010     llvm_unreachable("Unexpected vector type");
5011
5012   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5013 }
5014
5015 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5016 /// that point to V2 points to its first element.
5017 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5018   for (unsigned i = 0; i != NumElems; ++i) {
5019     if (Mask[i] > (int)NumElems) {
5020       Mask[i] = NumElems;
5021     }
5022   }
5023 }
5024
5025 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5026 /// operation of specified width.
5027 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5028                        SDValue V2) {
5029   unsigned NumElems = VT.getVectorNumElements();
5030   SmallVector<int, 8> Mask;
5031   Mask.push_back(NumElems);
5032   for (unsigned i = 1; i != NumElems; ++i)
5033     Mask.push_back(i);
5034   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5035 }
5036
5037 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5038 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5039                           SDValue V2) {
5040   unsigned NumElems = VT.getVectorNumElements();
5041   SmallVector<int, 8> Mask;
5042   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5043     Mask.push_back(i);
5044     Mask.push_back(i + NumElems);
5045   }
5046   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5047 }
5048
5049 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5050 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5051                           SDValue V2) {
5052   unsigned NumElems = VT.getVectorNumElements();
5053   SmallVector<int, 8> Mask;
5054   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5055     Mask.push_back(i + Half);
5056     Mask.push_back(i + NumElems + Half);
5057   }
5058   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5059 }
5060
5061 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5062 // a generic shuffle instruction because the target has no such instructions.
5063 // Generate shuffles which repeat i16 and i8 several times until they can be
5064 // represented by v4f32 and then be manipulated by target suported shuffles.
5065 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5066   MVT VT = V.getSimpleValueType();
5067   int NumElems = VT.getVectorNumElements();
5068   SDLoc dl(V);
5069
5070   while (NumElems > 4) {
5071     if (EltNo < NumElems/2) {
5072       V = getUnpackl(DAG, dl, VT, V, V);
5073     } else {
5074       V = getUnpackh(DAG, dl, VT, V, V);
5075       EltNo -= NumElems/2;
5076     }
5077     NumElems >>= 1;
5078   }
5079   return V;
5080 }
5081
5082 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5083 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5084   MVT VT = V.getSimpleValueType();
5085   SDLoc dl(V);
5086
5087   if (VT.is128BitVector()) {
5088     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5089     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5090     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5091                              &SplatMask[0]);
5092   } else if (VT.is256BitVector()) {
5093     // To use VPERMILPS to splat scalars, the second half of indicies must
5094     // refer to the higher part, which is a duplication of the lower one,
5095     // because VPERMILPS can only handle in-lane permutations.
5096     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5097                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5098
5099     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5100     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5101                              &SplatMask[0]);
5102   } else
5103     llvm_unreachable("Vector size not supported");
5104
5105   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5106 }
5107
5108 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5109 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5110   MVT SrcVT = SV->getSimpleValueType(0);
5111   SDValue V1 = SV->getOperand(0);
5112   SDLoc dl(SV);
5113
5114   int EltNo = SV->getSplatIndex();
5115   int NumElems = SrcVT.getVectorNumElements();
5116   bool Is256BitVec = SrcVT.is256BitVector();
5117
5118   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5119          "Unknown how to promote splat for type");
5120
5121   // Extract the 128-bit part containing the splat element and update
5122   // the splat element index when it refers to the higher register.
5123   if (Is256BitVec) {
5124     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5125     if (EltNo >= NumElems/2)
5126       EltNo -= NumElems/2;
5127   }
5128
5129   // All i16 and i8 vector types can't be used directly by a generic shuffle
5130   // instruction because the target has no such instruction. Generate shuffles
5131   // which repeat i16 and i8 several times until they fit in i32, and then can
5132   // be manipulated by target suported shuffles.
5133   MVT EltVT = SrcVT.getVectorElementType();
5134   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5135     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5136
5137   // Recreate the 256-bit vector and place the same 128-bit vector
5138   // into the low and high part. This is necessary because we want
5139   // to use VPERM* to shuffle the vectors
5140   if (Is256BitVec) {
5141     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5142   }
5143
5144   return getLegalSplat(DAG, V1, EltNo);
5145 }
5146
5147 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5148 /// vector of zero or undef vector.  This produces a shuffle where the low
5149 /// element of V2 is swizzled into the zero/undef vector, landing at element
5150 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5151 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5152                                            bool IsZero,
5153                                            const X86Subtarget *Subtarget,
5154                                            SelectionDAG &DAG) {
5155   MVT VT = V2.getSimpleValueType();
5156   SDValue V1 = IsZero
5157     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5158   unsigned NumElems = VT.getVectorNumElements();
5159   SmallVector<int, 16> MaskVec;
5160   for (unsigned i = 0; i != NumElems; ++i)
5161     // If this is the insertion idx, put the low elt of V2 here.
5162     MaskVec.push_back(i == Idx ? NumElems : i);
5163   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5164 }
5165
5166 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5167 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5168 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5169 /// shuffles which use a single input multiple times, and in those cases it will
5170 /// adjust the mask to only have indices within that single input.
5171 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5172                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5173   unsigned NumElems = VT.getVectorNumElements();
5174   SDValue ImmN;
5175
5176   IsUnary = false;
5177   bool IsFakeUnary = false;
5178   switch(N->getOpcode()) {
5179   case X86ISD::SHUFP:
5180     ImmN = N->getOperand(N->getNumOperands()-1);
5181     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5182     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5183     break;
5184   case X86ISD::UNPCKH:
5185     DecodeUNPCKHMask(VT, Mask);
5186     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5187     break;
5188   case X86ISD::UNPCKL:
5189     DecodeUNPCKLMask(VT, Mask);
5190     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5191     break;
5192   case X86ISD::MOVHLPS:
5193     DecodeMOVHLPSMask(NumElems, Mask);
5194     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5195     break;
5196   case X86ISD::MOVLHPS:
5197     DecodeMOVLHPSMask(NumElems, Mask);
5198     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5199     break;
5200   case X86ISD::PALIGNR:
5201     ImmN = N->getOperand(N->getNumOperands()-1);
5202     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5203     break;
5204   case X86ISD::PSHUFD:
5205   case X86ISD::VPERMILP:
5206     ImmN = N->getOperand(N->getNumOperands()-1);
5207     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5208     IsUnary = true;
5209     break;
5210   case X86ISD::PSHUFHW:
5211     ImmN = N->getOperand(N->getNumOperands()-1);
5212     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5213     IsUnary = true;
5214     break;
5215   case X86ISD::PSHUFLW:
5216     ImmN = N->getOperand(N->getNumOperands()-1);
5217     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5218     IsUnary = true;
5219     break;
5220   case X86ISD::PSHUFB: {
5221     IsUnary = true;
5222     SDValue MaskNode = N->getOperand(1);
5223     while (MaskNode->getOpcode() == ISD::BITCAST)
5224       MaskNode = MaskNode->getOperand(0);
5225
5226     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5227       // If we have a build-vector, then things are easy.
5228       EVT VT = MaskNode.getValueType();
5229       assert(VT.isVector() &&
5230              "Can't produce a non-vector with a build_vector!");
5231       if (!VT.isInteger())
5232         return false;
5233
5234       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5235
5236       SmallVector<uint64_t, 32> RawMask;
5237       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5238         auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5239         if (!CN)
5240           return false;
5241         APInt MaskElement = CN->getAPIntValue();
5242
5243         // We now have to decode the element which could be any integer size and
5244         // extract each byte of it.
5245         for (int j = 0; j < NumBytesPerElement; ++j) {
5246           // Note that this is x86 and so always little endian: the low byte is
5247           // the first byte of the mask.
5248           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5249           MaskElement = MaskElement.lshr(8);
5250         }
5251       }
5252       DecodePSHUFBMask(RawMask, Mask);
5253       break;
5254     }
5255
5256     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5257     if (!MaskLoad)
5258       return false;
5259
5260     SDValue Ptr = MaskLoad->getBasePtr();
5261     if (Ptr->getOpcode() == X86ISD::Wrapper)
5262       Ptr = Ptr->getOperand(0);
5263
5264     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5265     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5266       return false;
5267
5268     if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5269       // FIXME: Support AVX-512 here.
5270       if (!C->getType()->isVectorTy() ||
5271           (C->getNumElements() != 16 && C->getNumElements() != 32))
5272         return false;
5273
5274       assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5275       DecodePSHUFBMask(C, Mask);
5276       break;
5277     }
5278
5279     return false;
5280   }
5281   case X86ISD::VPERMI:
5282     ImmN = N->getOperand(N->getNumOperands()-1);
5283     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5284     IsUnary = true;
5285     break;
5286   case X86ISD::MOVSS:
5287   case X86ISD::MOVSD: {
5288     // The index 0 always comes from the first element of the second source,
5289     // this is why MOVSS and MOVSD are used in the first place. The other
5290     // elements come from the other positions of the first source vector
5291     Mask.push_back(NumElems);
5292     for (unsigned i = 1; i != NumElems; ++i) {
5293       Mask.push_back(i);
5294     }
5295     break;
5296   }
5297   case X86ISD::VPERM2X128:
5298     ImmN = N->getOperand(N->getNumOperands()-1);
5299     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5300     if (Mask.empty()) return false;
5301     break;
5302   case X86ISD::MOVDDUP:
5303   case X86ISD::MOVLHPD:
5304   case X86ISD::MOVLPD:
5305   case X86ISD::MOVLPS:
5306   case X86ISD::MOVSHDUP:
5307   case X86ISD::MOVSLDUP:
5308     // Not yet implemented
5309     return false;
5310   default: llvm_unreachable("unknown target shuffle node");
5311   }
5312
5313   // If we have a fake unary shuffle, the shuffle mask is spread across two
5314   // inputs that are actually the same node. Re-map the mask to always point
5315   // into the first input.
5316   if (IsFakeUnary)
5317     for (int &M : Mask)
5318       if (M >= (int)Mask.size())
5319         M -= Mask.size();
5320
5321   return true;
5322 }
5323
5324 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5325 /// element of the result of the vector shuffle.
5326 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5327                                    unsigned Depth) {
5328   if (Depth == 6)
5329     return SDValue();  // Limit search depth.
5330
5331   SDValue V = SDValue(N, 0);
5332   EVT VT = V.getValueType();
5333   unsigned Opcode = V.getOpcode();
5334
5335   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5336   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5337     int Elt = SV->getMaskElt(Index);
5338
5339     if (Elt < 0)
5340       return DAG.getUNDEF(VT.getVectorElementType());
5341
5342     unsigned NumElems = VT.getVectorNumElements();
5343     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5344                                          : SV->getOperand(1);
5345     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5346   }
5347
5348   // Recurse into target specific vector shuffles to find scalars.
5349   if (isTargetShuffle(Opcode)) {
5350     MVT ShufVT = V.getSimpleValueType();
5351     unsigned NumElems = ShufVT.getVectorNumElements();
5352     SmallVector<int, 16> ShuffleMask;
5353     bool IsUnary;
5354
5355     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5356       return SDValue();
5357
5358     int Elt = ShuffleMask[Index];
5359     if (Elt < 0)
5360       return DAG.getUNDEF(ShufVT.getVectorElementType());
5361
5362     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5363                                          : N->getOperand(1);
5364     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5365                                Depth+1);
5366   }
5367
5368   // Actual nodes that may contain scalar elements
5369   if (Opcode == ISD::BITCAST) {
5370     V = V.getOperand(0);
5371     EVT SrcVT = V.getValueType();
5372     unsigned NumElems = VT.getVectorNumElements();
5373
5374     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5375       return SDValue();
5376   }
5377
5378   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5379     return (Index == 0) ? V.getOperand(0)
5380                         : DAG.getUNDEF(VT.getVectorElementType());
5381
5382   if (V.getOpcode() == ISD::BUILD_VECTOR)
5383     return V.getOperand(Index);
5384
5385   return SDValue();
5386 }
5387
5388 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5389 /// shuffle operation which come from a consecutively from a zero. The
5390 /// search can start in two different directions, from left or right.
5391 /// We count undefs as zeros until PreferredNum is reached.
5392 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5393                                          unsigned NumElems, bool ZerosFromLeft,
5394                                          SelectionDAG &DAG,
5395                                          unsigned PreferredNum = -1U) {
5396   unsigned NumZeros = 0;
5397   for (unsigned i = 0; i != NumElems; ++i) {
5398     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5399     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5400     if (!Elt.getNode())
5401       break;
5402
5403     if (X86::isZeroNode(Elt))
5404       ++NumZeros;
5405     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5406       NumZeros = std::min(NumZeros + 1, PreferredNum);
5407     else
5408       break;
5409   }
5410
5411   return NumZeros;
5412 }
5413
5414 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5415 /// correspond consecutively to elements from one of the vector operands,
5416 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5417 static
5418 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5419                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5420                               unsigned NumElems, unsigned &OpNum) {
5421   bool SeenV1 = false;
5422   bool SeenV2 = false;
5423
5424   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5425     int Idx = SVOp->getMaskElt(i);
5426     // Ignore undef indicies
5427     if (Idx < 0)
5428       continue;
5429
5430     if (Idx < (int)NumElems)
5431       SeenV1 = true;
5432     else
5433       SeenV2 = true;
5434
5435     // Only accept consecutive elements from the same vector
5436     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5437       return false;
5438   }
5439
5440   OpNum = SeenV1 ? 0 : 1;
5441   return true;
5442 }
5443
5444 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5445 /// logical left shift of a vector.
5446 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5447                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5448   unsigned NumElems =
5449     SVOp->getSimpleValueType(0).getVectorNumElements();
5450   unsigned NumZeros = getNumOfConsecutiveZeros(
5451       SVOp, NumElems, false /* check zeros from right */, DAG,
5452       SVOp->getMaskElt(0));
5453   unsigned OpSrc;
5454
5455   if (!NumZeros)
5456     return false;
5457
5458   // Considering the elements in the mask that are not consecutive zeros,
5459   // check if they consecutively come from only one of the source vectors.
5460   //
5461   //               V1 = {X, A, B, C}     0
5462   //                         \  \  \    /
5463   //   vector_shuffle V1, V2 <1, 2, 3, X>
5464   //
5465   if (!isShuffleMaskConsecutive(SVOp,
5466             0,                   // Mask Start Index
5467             NumElems-NumZeros,   // Mask End Index(exclusive)
5468             NumZeros,            // Where to start looking in the src vector
5469             NumElems,            // Number of elements in vector
5470             OpSrc))              // Which source operand ?
5471     return false;
5472
5473   isLeft = false;
5474   ShAmt = NumZeros;
5475   ShVal = SVOp->getOperand(OpSrc);
5476   return true;
5477 }
5478
5479 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5480 /// logical left shift of a vector.
5481 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5482                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5483   unsigned NumElems =
5484     SVOp->getSimpleValueType(0).getVectorNumElements();
5485   unsigned NumZeros = getNumOfConsecutiveZeros(
5486       SVOp, NumElems, true /* check zeros from left */, DAG,
5487       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5488   unsigned OpSrc;
5489
5490   if (!NumZeros)
5491     return false;
5492
5493   // Considering the elements in the mask that are not consecutive zeros,
5494   // check if they consecutively come from only one of the source vectors.
5495   //
5496   //                           0    { A, B, X, X } = V2
5497   //                          / \    /  /
5498   //   vector_shuffle V1, V2 <X, X, 4, 5>
5499   //
5500   if (!isShuffleMaskConsecutive(SVOp,
5501             NumZeros,     // Mask Start Index
5502             NumElems,     // Mask End Index(exclusive)
5503             0,            // Where to start looking in the src vector
5504             NumElems,     // Number of elements in vector
5505             OpSrc))       // Which source operand ?
5506     return false;
5507
5508   isLeft = true;
5509   ShAmt = NumZeros;
5510   ShVal = SVOp->getOperand(OpSrc);
5511   return true;
5512 }
5513
5514 /// isVectorShift - Returns true if the shuffle can be implemented as a
5515 /// logical left or right shift of a vector.
5516 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5517                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5518   // Although the logic below support any bitwidth size, there are no
5519   // shift instructions which handle more than 128-bit vectors.
5520   if (!SVOp->getSimpleValueType(0).is128BitVector())
5521     return false;
5522
5523   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5524       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5525     return true;
5526
5527   return false;
5528 }
5529
5530 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5531 ///
5532 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5533                                        unsigned NumNonZero, unsigned NumZero,
5534                                        SelectionDAG &DAG,
5535                                        const X86Subtarget* Subtarget,
5536                                        const TargetLowering &TLI) {
5537   if (NumNonZero > 8)
5538     return SDValue();
5539
5540   SDLoc dl(Op);
5541   SDValue V;
5542   bool First = true;
5543   for (unsigned i = 0; i < 16; ++i) {
5544     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5545     if (ThisIsNonZero && First) {
5546       if (NumZero)
5547         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5548       else
5549         V = DAG.getUNDEF(MVT::v8i16);
5550       First = false;
5551     }
5552
5553     if ((i & 1) != 0) {
5554       SDValue ThisElt, LastElt;
5555       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5556       if (LastIsNonZero) {
5557         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5558                               MVT::i16, Op.getOperand(i-1));
5559       }
5560       if (ThisIsNonZero) {
5561         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5562         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5563                               ThisElt, DAG.getConstant(8, MVT::i8));
5564         if (LastIsNonZero)
5565           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5566       } else
5567         ThisElt = LastElt;
5568
5569       if (ThisElt.getNode())
5570         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5571                         DAG.getIntPtrConstant(i/2));
5572     }
5573   }
5574
5575   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5576 }
5577
5578 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5579 ///
5580 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5581                                      unsigned NumNonZero, unsigned NumZero,
5582                                      SelectionDAG &DAG,
5583                                      const X86Subtarget* Subtarget,
5584                                      const TargetLowering &TLI) {
5585   if (NumNonZero > 4)
5586     return SDValue();
5587
5588   SDLoc dl(Op);
5589   SDValue V;
5590   bool First = true;
5591   for (unsigned i = 0; i < 8; ++i) {
5592     bool isNonZero = (NonZeros & (1 << i)) != 0;
5593     if (isNonZero) {
5594       if (First) {
5595         if (NumZero)
5596           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5597         else
5598           V = DAG.getUNDEF(MVT::v8i16);
5599         First = false;
5600       }
5601       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5602                       MVT::v8i16, V, Op.getOperand(i),
5603                       DAG.getIntPtrConstant(i));
5604     }
5605   }
5606
5607   return V;
5608 }
5609
5610 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5611 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5612                                      unsigned NonZeros, unsigned NumNonZero,
5613                                      unsigned NumZero, SelectionDAG &DAG,
5614                                      const X86Subtarget *Subtarget,
5615                                      const TargetLowering &TLI) {
5616   // We know there's at least one non-zero element
5617   unsigned FirstNonZeroIdx = 0;
5618   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5619   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5620          X86::isZeroNode(FirstNonZero)) {
5621     ++FirstNonZeroIdx;
5622     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5623   }
5624
5625   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5626       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5627     return SDValue();
5628
5629   SDValue V = FirstNonZero.getOperand(0);
5630   MVT VVT = V.getSimpleValueType();
5631   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5632     return SDValue();
5633
5634   unsigned FirstNonZeroDst =
5635       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5636   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5637   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5638   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5639
5640   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5641     SDValue Elem = Op.getOperand(Idx);
5642     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5643       continue;
5644
5645     // TODO: What else can be here? Deal with it.
5646     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5647       return SDValue();
5648
5649     // TODO: Some optimizations are still possible here
5650     // ex: Getting one element from a vector, and the rest from another.
5651     if (Elem.getOperand(0) != V)
5652       return SDValue();
5653
5654     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5655     if (Dst == Idx)
5656       ++CorrectIdx;
5657     else if (IncorrectIdx == -1U) {
5658       IncorrectIdx = Idx;
5659       IncorrectDst = Dst;
5660     } else
5661       // There was already one element with an incorrect index.
5662       // We can't optimize this case to an insertps.
5663       return SDValue();
5664   }
5665
5666   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5667     SDLoc dl(Op);
5668     EVT VT = Op.getSimpleValueType();
5669     unsigned ElementMoveMask = 0;
5670     if (IncorrectIdx == -1U)
5671       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5672     else
5673       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5674
5675     SDValue InsertpsMask =
5676         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5677     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5678   }
5679
5680   return SDValue();
5681 }
5682
5683 /// getVShift - Return a vector logical shift node.
5684 ///
5685 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5686                          unsigned NumBits, SelectionDAG &DAG,
5687                          const TargetLowering &TLI, SDLoc dl) {
5688   assert(VT.is128BitVector() && "Unknown type for VShift");
5689   EVT ShVT = MVT::v2i64;
5690   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5691   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5692   return DAG.getNode(ISD::BITCAST, dl, VT,
5693                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5694                              DAG.getConstant(NumBits,
5695                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5696 }
5697
5698 static SDValue
5699 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5700
5701   // Check if the scalar load can be widened into a vector load. And if
5702   // the address is "base + cst" see if the cst can be "absorbed" into
5703   // the shuffle mask.
5704   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5705     SDValue Ptr = LD->getBasePtr();
5706     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5707       return SDValue();
5708     EVT PVT = LD->getValueType(0);
5709     if (PVT != MVT::i32 && PVT != MVT::f32)
5710       return SDValue();
5711
5712     int FI = -1;
5713     int64_t Offset = 0;
5714     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5715       FI = FINode->getIndex();
5716       Offset = 0;
5717     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5718                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5719       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5720       Offset = Ptr.getConstantOperandVal(1);
5721       Ptr = Ptr.getOperand(0);
5722     } else {
5723       return SDValue();
5724     }
5725
5726     // FIXME: 256-bit vector instructions don't require a strict alignment,
5727     // improve this code to support it better.
5728     unsigned RequiredAlign = VT.getSizeInBits()/8;
5729     SDValue Chain = LD->getChain();
5730     // Make sure the stack object alignment is at least 16 or 32.
5731     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5732     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5733       if (MFI->isFixedObjectIndex(FI)) {
5734         // Can't change the alignment. FIXME: It's possible to compute
5735         // the exact stack offset and reference FI + adjust offset instead.
5736         // If someone *really* cares about this. That's the way to implement it.
5737         return SDValue();
5738       } else {
5739         MFI->setObjectAlignment(FI, RequiredAlign);
5740       }
5741     }
5742
5743     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5744     // Ptr + (Offset & ~15).
5745     if (Offset < 0)
5746       return SDValue();
5747     if ((Offset % RequiredAlign) & 3)
5748       return SDValue();
5749     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5750     if (StartOffset)
5751       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5752                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5753
5754     int EltNo = (Offset - StartOffset) >> 2;
5755     unsigned NumElems = VT.getVectorNumElements();
5756
5757     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5758     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5759                              LD->getPointerInfo().getWithOffset(StartOffset),
5760                              false, false, false, 0);
5761
5762     SmallVector<int, 8> Mask;
5763     for (unsigned i = 0; i != NumElems; ++i)
5764       Mask.push_back(EltNo);
5765
5766     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5767   }
5768
5769   return SDValue();
5770 }
5771
5772 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5773 /// vector of type 'VT', see if the elements can be replaced by a single large
5774 /// load which has the same value as a build_vector whose operands are 'elts'.
5775 ///
5776 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5777 ///
5778 /// FIXME: we'd also like to handle the case where the last elements are zero
5779 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5780 /// There's even a handy isZeroNode for that purpose.
5781 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5782                                         SDLoc &DL, SelectionDAG &DAG,
5783                                         bool isAfterLegalize) {
5784   EVT EltVT = VT.getVectorElementType();
5785   unsigned NumElems = Elts.size();
5786
5787   LoadSDNode *LDBase = nullptr;
5788   unsigned LastLoadedElt = -1U;
5789
5790   // For each element in the initializer, see if we've found a load or an undef.
5791   // If we don't find an initial load element, or later load elements are
5792   // non-consecutive, bail out.
5793   for (unsigned i = 0; i < NumElems; ++i) {
5794     SDValue Elt = Elts[i];
5795
5796     if (!Elt.getNode() ||
5797         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5798       return SDValue();
5799     if (!LDBase) {
5800       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5801         return SDValue();
5802       LDBase = cast<LoadSDNode>(Elt.getNode());
5803       LastLoadedElt = i;
5804       continue;
5805     }
5806     if (Elt.getOpcode() == ISD::UNDEF)
5807       continue;
5808
5809     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5810     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5811       return SDValue();
5812     LastLoadedElt = i;
5813   }
5814
5815   // If we have found an entire vector of loads and undefs, then return a large
5816   // load of the entire vector width starting at the base pointer.  If we found
5817   // consecutive loads for the low half, generate a vzext_load node.
5818   if (LastLoadedElt == NumElems - 1) {
5819
5820     if (isAfterLegalize &&
5821         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5822       return SDValue();
5823
5824     SDValue NewLd = SDValue();
5825
5826     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5827       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5828                           LDBase->getPointerInfo(),
5829                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5830                           LDBase->isInvariant(), 0);
5831     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5832                         LDBase->getPointerInfo(),
5833                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5834                         LDBase->isInvariant(), LDBase->getAlignment());
5835
5836     if (LDBase->hasAnyUseOfValue(1)) {
5837       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5838                                      SDValue(LDBase, 1),
5839                                      SDValue(NewLd.getNode(), 1));
5840       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5841       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5842                              SDValue(NewLd.getNode(), 1));
5843     }
5844
5845     return NewLd;
5846   }
5847   if (NumElems == 4 && LastLoadedElt == 1 &&
5848       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5849     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5850     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5851     SDValue ResNode =
5852         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5853                                 LDBase->getPointerInfo(),
5854                                 LDBase->getAlignment(),
5855                                 false/*isVolatile*/, true/*ReadMem*/,
5856                                 false/*WriteMem*/);
5857
5858     // Make sure the newly-created LOAD is in the same position as LDBase in
5859     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5860     // update uses of LDBase's output chain to use the TokenFactor.
5861     if (LDBase->hasAnyUseOfValue(1)) {
5862       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5863                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5864       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5865       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5866                              SDValue(ResNode.getNode(), 1));
5867     }
5868
5869     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5870   }
5871   return SDValue();
5872 }
5873
5874 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5875 /// to generate a splat value for the following cases:
5876 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5877 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5878 /// a scalar load, or a constant.
5879 /// The VBROADCAST node is returned when a pattern is found,
5880 /// or SDValue() otherwise.
5881 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5882                                     SelectionDAG &DAG) {
5883   if (!Subtarget->hasFp256())
5884     return SDValue();
5885
5886   MVT VT = Op.getSimpleValueType();
5887   SDLoc dl(Op);
5888
5889   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5890          "Unsupported vector type for broadcast.");
5891
5892   SDValue Ld;
5893   bool ConstSplatVal;
5894
5895   switch (Op.getOpcode()) {
5896     default:
5897       // Unknown pattern found.
5898       return SDValue();
5899
5900     case ISD::BUILD_VECTOR: {
5901       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5902       BitVector UndefElements;
5903       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5904
5905       // We need a splat of a single value to use broadcast, and it doesn't
5906       // make any sense if the value is only in one element of the vector.
5907       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5908         return SDValue();
5909
5910       Ld = Splat;
5911       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5912                        Ld.getOpcode() == ISD::ConstantFP);
5913
5914       // Make sure that all of the users of a non-constant load are from the
5915       // BUILD_VECTOR node.
5916       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5917         return SDValue();
5918       break;
5919     }
5920
5921     case ISD::VECTOR_SHUFFLE: {
5922       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5923
5924       // Shuffles must have a splat mask where the first element is
5925       // broadcasted.
5926       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5927         return SDValue();
5928
5929       SDValue Sc = Op.getOperand(0);
5930       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5931           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5932
5933         if (!Subtarget->hasInt256())
5934           return SDValue();
5935
5936         // Use the register form of the broadcast instruction available on AVX2.
5937         if (VT.getSizeInBits() >= 256)
5938           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5939         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5940       }
5941
5942       Ld = Sc.getOperand(0);
5943       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5944                        Ld.getOpcode() == ISD::ConstantFP);
5945
5946       // The scalar_to_vector node and the suspected
5947       // load node must have exactly one user.
5948       // Constants may have multiple users.
5949
5950       // AVX-512 has register version of the broadcast
5951       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5952         Ld.getValueType().getSizeInBits() >= 32;
5953       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5954           !hasRegVer))
5955         return SDValue();
5956       break;
5957     }
5958   }
5959
5960   bool IsGE256 = (VT.getSizeInBits() >= 256);
5961
5962   // Handle the broadcasting a single constant scalar from the constant pool
5963   // into a vector. On Sandybridge it is still better to load a constant vector
5964   // from the constant pool and not to broadcast it from a scalar.
5965   if (ConstSplatVal && Subtarget->hasInt256()) {
5966     EVT CVT = Ld.getValueType();
5967     assert(!CVT.isVector() && "Must not broadcast a vector type");
5968     unsigned ScalarSize = CVT.getSizeInBits();
5969
5970     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5971       const Constant *C = nullptr;
5972       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5973         C = CI->getConstantIntValue();
5974       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5975         C = CF->getConstantFPValue();
5976
5977       assert(C && "Invalid constant type");
5978
5979       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5980       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5981       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5982       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5983                        MachinePointerInfo::getConstantPool(),
5984                        false, false, false, Alignment);
5985
5986       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5987     }
5988   }
5989
5990   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5991   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5992
5993   // Handle AVX2 in-register broadcasts.
5994   if (!IsLoad && Subtarget->hasInt256() &&
5995       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5996     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5997
5998   // The scalar source must be a normal load.
5999   if (!IsLoad)
6000     return SDValue();
6001
6002   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6003     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6004
6005   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6006   // double since there is no vbroadcastsd xmm
6007   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6008     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6009       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6010   }
6011
6012   // Unsupported broadcast.
6013   return SDValue();
6014 }
6015
6016 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6017 /// underlying vector and index.
6018 ///
6019 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6020 /// index.
6021 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6022                                          SDValue ExtIdx) {
6023   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6024   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6025     return Idx;
6026
6027   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6028   // lowered this:
6029   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6030   // to:
6031   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6032   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6033   //                           undef)
6034   //                       Constant<0>)
6035   // In this case the vector is the extract_subvector expression and the index
6036   // is 2, as specified by the shuffle.
6037   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6038   SDValue ShuffleVec = SVOp->getOperand(0);
6039   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6040   assert(ShuffleVecVT.getVectorElementType() ==
6041          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6042
6043   int ShuffleIdx = SVOp->getMaskElt(Idx);
6044   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6045     ExtractedFromVec = ShuffleVec;
6046     return ShuffleIdx;
6047   }
6048   return Idx;
6049 }
6050
6051 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6052   MVT VT = Op.getSimpleValueType();
6053
6054   // Skip if insert_vec_elt is not supported.
6055   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6056   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6057     return SDValue();
6058
6059   SDLoc DL(Op);
6060   unsigned NumElems = Op.getNumOperands();
6061
6062   SDValue VecIn1;
6063   SDValue VecIn2;
6064   SmallVector<unsigned, 4> InsertIndices;
6065   SmallVector<int, 8> Mask(NumElems, -1);
6066
6067   for (unsigned i = 0; i != NumElems; ++i) {
6068     unsigned Opc = Op.getOperand(i).getOpcode();
6069
6070     if (Opc == ISD::UNDEF)
6071       continue;
6072
6073     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6074       // Quit if more than 1 elements need inserting.
6075       if (InsertIndices.size() > 1)
6076         return SDValue();
6077
6078       InsertIndices.push_back(i);
6079       continue;
6080     }
6081
6082     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6083     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6084     // Quit if non-constant index.
6085     if (!isa<ConstantSDNode>(ExtIdx))
6086       return SDValue();
6087     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6088
6089     // Quit if extracted from vector of different type.
6090     if (ExtractedFromVec.getValueType() != VT)
6091       return SDValue();
6092
6093     if (!VecIn1.getNode())
6094       VecIn1 = ExtractedFromVec;
6095     else if (VecIn1 != ExtractedFromVec) {
6096       if (!VecIn2.getNode())
6097         VecIn2 = ExtractedFromVec;
6098       else if (VecIn2 != ExtractedFromVec)
6099         // Quit if more than 2 vectors to shuffle
6100         return SDValue();
6101     }
6102
6103     if (ExtractedFromVec == VecIn1)
6104       Mask[i] = Idx;
6105     else if (ExtractedFromVec == VecIn2)
6106       Mask[i] = Idx + NumElems;
6107   }
6108
6109   if (!VecIn1.getNode())
6110     return SDValue();
6111
6112   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6113   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6114   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6115     unsigned Idx = InsertIndices[i];
6116     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6117                      DAG.getIntPtrConstant(Idx));
6118   }
6119
6120   return NV;
6121 }
6122
6123 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6124 SDValue
6125 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6126
6127   MVT VT = Op.getSimpleValueType();
6128   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6129          "Unexpected type in LowerBUILD_VECTORvXi1!");
6130
6131   SDLoc dl(Op);
6132   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6133     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6134     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6135     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6136   }
6137
6138   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6139     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6140     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6141     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6142   }
6143
6144   bool AllContants = true;
6145   uint64_t Immediate = 0;
6146   int NonConstIdx = -1;
6147   bool IsSplat = true;
6148   unsigned NumNonConsts = 0;
6149   unsigned NumConsts = 0;
6150   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6151     SDValue In = Op.getOperand(idx);
6152     if (In.getOpcode() == ISD::UNDEF)
6153       continue;
6154     if (!isa<ConstantSDNode>(In)) {
6155       AllContants = false;
6156       NonConstIdx = idx;
6157       NumNonConsts++;
6158     }
6159     else {
6160       NumConsts++;
6161       if (cast<ConstantSDNode>(In)->getZExtValue())
6162       Immediate |= (1ULL << idx);
6163     }
6164     if (In != Op.getOperand(0))
6165       IsSplat = false;
6166   }
6167
6168   if (AllContants) {
6169     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6170       DAG.getConstant(Immediate, MVT::i16));
6171     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6172                        DAG.getIntPtrConstant(0));
6173   }
6174
6175   if (NumNonConsts == 1 && NonConstIdx != 0) {
6176     SDValue DstVec;
6177     if (NumConsts) {
6178       SDValue VecAsImm = DAG.getConstant(Immediate,
6179                                          MVT::getIntegerVT(VT.getSizeInBits()));
6180       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6181     }
6182     else 
6183       DstVec = DAG.getUNDEF(VT);
6184     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6185                        Op.getOperand(NonConstIdx),
6186                        DAG.getIntPtrConstant(NonConstIdx));
6187   }
6188   if (!IsSplat && (NonConstIdx != 0))
6189     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6190   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6191   SDValue Select;
6192   if (IsSplat)
6193     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6194                           DAG.getConstant(-1, SelectVT),
6195                           DAG.getConstant(0, SelectVT));
6196   else
6197     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6198                          DAG.getConstant((Immediate | 1), SelectVT),
6199                          DAG.getConstant(Immediate, SelectVT));
6200   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6201 }
6202
6203 /// \brief Return true if \p N implements a horizontal binop and return the
6204 /// operands for the horizontal binop into V0 and V1.
6205 /// 
6206 /// This is a helper function of PerformBUILD_VECTORCombine.
6207 /// This function checks that the build_vector \p N in input implements a
6208 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6209 /// operation to match.
6210 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6211 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6212 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6213 /// arithmetic sub.
6214 ///
6215 /// This function only analyzes elements of \p N whose indices are
6216 /// in range [BaseIdx, LastIdx).
6217 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6218                               SelectionDAG &DAG,
6219                               unsigned BaseIdx, unsigned LastIdx,
6220                               SDValue &V0, SDValue &V1) {
6221   EVT VT = N->getValueType(0);
6222
6223   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6224   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6225          "Invalid Vector in input!");
6226   
6227   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6228   bool CanFold = true;
6229   unsigned ExpectedVExtractIdx = BaseIdx;
6230   unsigned NumElts = LastIdx - BaseIdx;
6231   V0 = DAG.getUNDEF(VT);
6232   V1 = DAG.getUNDEF(VT);
6233
6234   // Check if N implements a horizontal binop.
6235   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6236     SDValue Op = N->getOperand(i + BaseIdx);
6237
6238     // Skip UNDEFs.
6239     if (Op->getOpcode() == ISD::UNDEF) {
6240       // Update the expected vector extract index.
6241       if (i * 2 == NumElts)
6242         ExpectedVExtractIdx = BaseIdx;
6243       ExpectedVExtractIdx += 2;
6244       continue;
6245     }
6246
6247     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6248
6249     if (!CanFold)
6250       break;
6251
6252     SDValue Op0 = Op.getOperand(0);
6253     SDValue Op1 = Op.getOperand(1);
6254
6255     // Try to match the following pattern:
6256     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6257     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6258         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6259         Op0.getOperand(0) == Op1.getOperand(0) &&
6260         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6261         isa<ConstantSDNode>(Op1.getOperand(1)));
6262     if (!CanFold)
6263       break;
6264
6265     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6266     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6267
6268     if (i * 2 < NumElts) {
6269       if (V0.getOpcode() == ISD::UNDEF)
6270         V0 = Op0.getOperand(0);
6271     } else {
6272       if (V1.getOpcode() == ISD::UNDEF)
6273         V1 = Op0.getOperand(0);
6274       if (i * 2 == NumElts)
6275         ExpectedVExtractIdx = BaseIdx;
6276     }
6277
6278     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6279     if (I0 == ExpectedVExtractIdx)
6280       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6281     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6282       // Try to match the following dag sequence:
6283       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6284       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6285     } else
6286       CanFold = false;
6287
6288     ExpectedVExtractIdx += 2;
6289   }
6290
6291   return CanFold;
6292 }
6293
6294 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6295 /// a concat_vector. 
6296 ///
6297 /// This is a helper function of PerformBUILD_VECTORCombine.
6298 /// This function expects two 256-bit vectors called V0 and V1.
6299 /// At first, each vector is split into two separate 128-bit vectors.
6300 /// Then, the resulting 128-bit vectors are used to implement two
6301 /// horizontal binary operations. 
6302 ///
6303 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6304 ///
6305 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6306 /// the two new horizontal binop.
6307 /// When Mode is set, the first horizontal binop dag node would take as input
6308 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6309 /// horizontal binop dag node would take as input the lower 128-bit of V1
6310 /// and the upper 128-bit of V1.
6311 ///   Example:
6312 ///     HADD V0_LO, V0_HI
6313 ///     HADD V1_LO, V1_HI
6314 ///
6315 /// Otherwise, the first horizontal binop dag node takes as input the lower
6316 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6317 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6318 ///   Example:
6319 ///     HADD V0_LO, V1_LO
6320 ///     HADD V0_HI, V1_HI
6321 ///
6322 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6323 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6324 /// the upper 128-bits of the result.
6325 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6326                                      SDLoc DL, SelectionDAG &DAG,
6327                                      unsigned X86Opcode, bool Mode,
6328                                      bool isUndefLO, bool isUndefHI) {
6329   EVT VT = V0.getValueType();
6330   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6331          "Invalid nodes in input!");
6332
6333   unsigned NumElts = VT.getVectorNumElements();
6334   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6335   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6336   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6337   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6338   EVT NewVT = V0_LO.getValueType();
6339
6340   SDValue LO = DAG.getUNDEF(NewVT);
6341   SDValue HI = DAG.getUNDEF(NewVT);
6342
6343   if (Mode) {
6344     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6345     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6346       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6347     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6348       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6349   } else {
6350     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6351     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6352                        V1_LO->getOpcode() != ISD::UNDEF))
6353       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6354
6355     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6356                        V1_HI->getOpcode() != ISD::UNDEF))
6357       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6358   }
6359
6360   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6361 }
6362
6363 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6364 /// sequence of 'vadd + vsub + blendi'.
6365 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6366                            const X86Subtarget *Subtarget) {
6367   SDLoc DL(BV);
6368   EVT VT = BV->getValueType(0);
6369   unsigned NumElts = VT.getVectorNumElements();
6370   SDValue InVec0 = DAG.getUNDEF(VT);
6371   SDValue InVec1 = DAG.getUNDEF(VT);
6372
6373   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6374           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6375
6376   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6377   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6378   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6379     return SDValue();
6380
6381   // Odd-numbered elements in the input build vector are obtained from
6382   // adding two integer/float elements.
6383   // Even-numbered elements in the input build vector are obtained from
6384   // subtracting two integer/float elements.
6385   unsigned ExpectedOpcode = ISD::FSUB;
6386   unsigned NextExpectedOpcode = ISD::FADD;
6387   bool AddFound = false;
6388   bool SubFound = false;
6389
6390   for (unsigned i = 0, e = NumElts; i != e; i++) {
6391     SDValue Op = BV->getOperand(i);
6392       
6393     // Skip 'undef' values.
6394     unsigned Opcode = Op.getOpcode();
6395     if (Opcode == ISD::UNDEF) {
6396       std::swap(ExpectedOpcode, NextExpectedOpcode);
6397       continue;
6398     }
6399       
6400     // Early exit if we found an unexpected opcode.
6401     if (Opcode != ExpectedOpcode)
6402       return SDValue();
6403
6404     SDValue Op0 = Op.getOperand(0);
6405     SDValue Op1 = Op.getOperand(1);
6406
6407     // Try to match the following pattern:
6408     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6409     // Early exit if we cannot match that sequence.
6410     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6411         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6412         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6413         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6414         Op0.getOperand(1) != Op1.getOperand(1))
6415       return SDValue();
6416
6417     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6418     if (I0 != i)
6419       return SDValue();
6420
6421     // We found a valid add/sub node. Update the information accordingly.
6422     if (i & 1)
6423       AddFound = true;
6424     else
6425       SubFound = true;
6426
6427     // Update InVec0 and InVec1.
6428     if (InVec0.getOpcode() == ISD::UNDEF)
6429       InVec0 = Op0.getOperand(0);
6430     if (InVec1.getOpcode() == ISD::UNDEF)
6431       InVec1 = Op1.getOperand(0);
6432
6433     // Make sure that operands in input to each add/sub node always
6434     // come from a same pair of vectors.
6435     if (InVec0 != Op0.getOperand(0)) {
6436       if (ExpectedOpcode == ISD::FSUB)
6437         return SDValue();
6438
6439       // FADD is commutable. Try to commute the operands
6440       // and then test again.
6441       std::swap(Op0, Op1);
6442       if (InVec0 != Op0.getOperand(0))
6443         return SDValue();
6444     }
6445
6446     if (InVec1 != Op1.getOperand(0))
6447       return SDValue();
6448
6449     // Update the pair of expected opcodes.
6450     std::swap(ExpectedOpcode, NextExpectedOpcode);
6451   }
6452
6453   // Don't try to fold this build_vector into a VSELECT if it has
6454   // too many UNDEF operands.
6455   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6456       InVec1.getOpcode() != ISD::UNDEF) {
6457     // Emit a sequence of vector add and sub followed by a VSELECT.
6458     // The new VSELECT will be lowered into a BLENDI.
6459     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6460     // and emit a single ADDSUB instruction.
6461     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6462     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6463
6464     // Construct the VSELECT mask.
6465     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6466     EVT SVT = MaskVT.getVectorElementType();
6467     unsigned SVTBits = SVT.getSizeInBits();
6468     SmallVector<SDValue, 8> Ops;
6469
6470     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6471       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6472                             APInt::getAllOnesValue(SVTBits);
6473       SDValue Constant = DAG.getConstant(Value, SVT);
6474       Ops.push_back(Constant);
6475     }
6476
6477     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6478     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6479   }
6480   
6481   return SDValue();
6482 }
6483
6484 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6485                                           const X86Subtarget *Subtarget) {
6486   SDLoc DL(N);
6487   EVT VT = N->getValueType(0);
6488   unsigned NumElts = VT.getVectorNumElements();
6489   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6490   SDValue InVec0, InVec1;
6491
6492   // Try to match an ADDSUB.
6493   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6494       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6495     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6496     if (Value.getNode())
6497       return Value;
6498   }
6499
6500   // Try to match horizontal ADD/SUB.
6501   unsigned NumUndefsLO = 0;
6502   unsigned NumUndefsHI = 0;
6503   unsigned Half = NumElts/2;
6504
6505   // Count the number of UNDEF operands in the build_vector in input.
6506   for (unsigned i = 0, e = Half; i != e; ++i)
6507     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6508       NumUndefsLO++;
6509
6510   for (unsigned i = Half, e = NumElts; i != e; ++i)
6511     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6512       NumUndefsHI++;
6513
6514   // Early exit if this is either a build_vector of all UNDEFs or all the
6515   // operands but one are UNDEF.
6516   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6517     return SDValue();
6518
6519   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6520     // Try to match an SSE3 float HADD/HSUB.
6521     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6522       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6523     
6524     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6525       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6526   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6527     // Try to match an SSSE3 integer HADD/HSUB.
6528     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6529       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6530     
6531     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6532       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6533   }
6534   
6535   if (!Subtarget->hasAVX())
6536     return SDValue();
6537
6538   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6539     // Try to match an AVX horizontal add/sub of packed single/double
6540     // precision floating point values from 256-bit vectors.
6541     SDValue InVec2, InVec3;
6542     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6543         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6544         ((InVec0.getOpcode() == ISD::UNDEF ||
6545           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6546         ((InVec1.getOpcode() == ISD::UNDEF ||
6547           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6548       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6549
6550     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6551         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6552         ((InVec0.getOpcode() == ISD::UNDEF ||
6553           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6554         ((InVec1.getOpcode() == ISD::UNDEF ||
6555           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6556       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6557   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6558     // Try to match an AVX2 horizontal add/sub of signed integers.
6559     SDValue InVec2, InVec3;
6560     unsigned X86Opcode;
6561     bool CanFold = true;
6562
6563     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6564         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6565         ((InVec0.getOpcode() == ISD::UNDEF ||
6566           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6567         ((InVec1.getOpcode() == ISD::UNDEF ||
6568           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6569       X86Opcode = X86ISD::HADD;
6570     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6571         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6572         ((InVec0.getOpcode() == ISD::UNDEF ||
6573           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6574         ((InVec1.getOpcode() == ISD::UNDEF ||
6575           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6576       X86Opcode = X86ISD::HSUB;
6577     else
6578       CanFold = false;
6579
6580     if (CanFold) {
6581       // Fold this build_vector into a single horizontal add/sub.
6582       // Do this only if the target has AVX2.
6583       if (Subtarget->hasAVX2())
6584         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6585  
6586       // Do not try to expand this build_vector into a pair of horizontal
6587       // add/sub if we can emit a pair of scalar add/sub.
6588       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6589         return SDValue();
6590
6591       // Convert this build_vector into a pair of horizontal binop followed by
6592       // a concat vector.
6593       bool isUndefLO = NumUndefsLO == Half;
6594       bool isUndefHI = NumUndefsHI == Half;
6595       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6596                                    isUndefLO, isUndefHI);
6597     }
6598   }
6599
6600   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6601        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6602     unsigned X86Opcode;
6603     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6604       X86Opcode = X86ISD::HADD;
6605     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6606       X86Opcode = X86ISD::HSUB;
6607     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6608       X86Opcode = X86ISD::FHADD;
6609     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6610       X86Opcode = X86ISD::FHSUB;
6611     else
6612       return SDValue();
6613
6614     // Don't try to expand this build_vector into a pair of horizontal add/sub
6615     // if we can simply emit a pair of scalar add/sub.
6616     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6617       return SDValue();
6618
6619     // Convert this build_vector into two horizontal add/sub followed by
6620     // a concat vector.
6621     bool isUndefLO = NumUndefsLO == Half;
6622     bool isUndefHI = NumUndefsHI == Half;
6623     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6624                                  isUndefLO, isUndefHI);
6625   }
6626
6627   return SDValue();
6628 }
6629
6630 SDValue
6631 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6632   SDLoc dl(Op);
6633
6634   MVT VT = Op.getSimpleValueType();
6635   MVT ExtVT = VT.getVectorElementType();
6636   unsigned NumElems = Op.getNumOperands();
6637
6638   // Generate vectors for predicate vectors.
6639   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6640     return LowerBUILD_VECTORvXi1(Op, DAG);
6641
6642   // Vectors containing all zeros can be matched by pxor and xorps later
6643   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6644     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6645     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6646     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6647       return Op;
6648
6649     return getZeroVector(VT, Subtarget, DAG, dl);
6650   }
6651
6652   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6653   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6654   // vpcmpeqd on 256-bit vectors.
6655   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6656     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6657       return Op;
6658
6659     if (!VT.is512BitVector())
6660       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6661   }
6662
6663   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6664   if (Broadcast.getNode())
6665     return Broadcast;
6666
6667   unsigned EVTBits = ExtVT.getSizeInBits();
6668
6669   unsigned NumZero  = 0;
6670   unsigned NumNonZero = 0;
6671   unsigned NonZeros = 0;
6672   bool IsAllConstants = true;
6673   SmallSet<SDValue, 8> Values;
6674   for (unsigned i = 0; i < NumElems; ++i) {
6675     SDValue Elt = Op.getOperand(i);
6676     if (Elt.getOpcode() == ISD::UNDEF)
6677       continue;
6678     Values.insert(Elt);
6679     if (Elt.getOpcode() != ISD::Constant &&
6680         Elt.getOpcode() != ISD::ConstantFP)
6681       IsAllConstants = false;
6682     if (X86::isZeroNode(Elt))
6683       NumZero++;
6684     else {
6685       NonZeros |= (1 << i);
6686       NumNonZero++;
6687     }
6688   }
6689
6690   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6691   if (NumNonZero == 0)
6692     return DAG.getUNDEF(VT);
6693
6694   // Special case for single non-zero, non-undef, element.
6695   if (NumNonZero == 1) {
6696     unsigned Idx = countTrailingZeros(NonZeros);
6697     SDValue Item = Op.getOperand(Idx);
6698
6699     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6700     // the value are obviously zero, truncate the value to i32 and do the
6701     // insertion that way.  Only do this if the value is non-constant or if the
6702     // value is a constant being inserted into element 0.  It is cheaper to do
6703     // a constant pool load than it is to do a movd + shuffle.
6704     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6705         (!IsAllConstants || Idx == 0)) {
6706       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6707         // Handle SSE only.
6708         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6709         EVT VecVT = MVT::v4i32;
6710         unsigned VecElts = 4;
6711
6712         // Truncate the value (which may itself be a constant) to i32, and
6713         // convert it to a vector with movd (S2V+shuffle to zero extend).
6714         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6715         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6716         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6717
6718         // Now we have our 32-bit value zero extended in the low element of
6719         // a vector.  If Idx != 0, swizzle it into place.
6720         if (Idx != 0) {
6721           SmallVector<int, 4> Mask;
6722           Mask.push_back(Idx);
6723           for (unsigned i = 1; i != VecElts; ++i)
6724             Mask.push_back(i);
6725           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6726                                       &Mask[0]);
6727         }
6728         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6729       }
6730     }
6731
6732     // If we have a constant or non-constant insertion into the low element of
6733     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6734     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6735     // depending on what the source datatype is.
6736     if (Idx == 0) {
6737       if (NumZero == 0)
6738         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6739
6740       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6741           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6742         if (VT.is256BitVector() || VT.is512BitVector()) {
6743           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6744           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6745                              Item, DAG.getIntPtrConstant(0));
6746         }
6747         assert(VT.is128BitVector() && "Expected an SSE value type!");
6748         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6749         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6750         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6751       }
6752
6753       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6754         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6755         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6756         if (VT.is256BitVector()) {
6757           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6758           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6759         } else {
6760           assert(VT.is128BitVector() && "Expected an SSE value type!");
6761           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6762         }
6763         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6764       }
6765     }
6766
6767     // Is it a vector logical left shift?
6768     if (NumElems == 2 && Idx == 1 &&
6769         X86::isZeroNode(Op.getOperand(0)) &&
6770         !X86::isZeroNode(Op.getOperand(1))) {
6771       unsigned NumBits = VT.getSizeInBits();
6772       return getVShift(true, VT,
6773                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6774                                    VT, Op.getOperand(1)),
6775                        NumBits/2, DAG, *this, dl);
6776     }
6777
6778     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6779       return SDValue();
6780
6781     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6782     // is a non-constant being inserted into an element other than the low one,
6783     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6784     // movd/movss) to move this into the low element, then shuffle it into
6785     // place.
6786     if (EVTBits == 32) {
6787       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6788
6789       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6790       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6791       SmallVector<int, 8> MaskVec;
6792       for (unsigned i = 0; i != NumElems; ++i)
6793         MaskVec.push_back(i == Idx ? 0 : 1);
6794       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6795     }
6796   }
6797
6798   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6799   if (Values.size() == 1) {
6800     if (EVTBits == 32) {
6801       // Instead of a shuffle like this:
6802       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6803       // Check if it's possible to issue this instead.
6804       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6805       unsigned Idx = countTrailingZeros(NonZeros);
6806       SDValue Item = Op.getOperand(Idx);
6807       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6808         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6809     }
6810     return SDValue();
6811   }
6812
6813   // A vector full of immediates; various special cases are already
6814   // handled, so this is best done with a single constant-pool load.
6815   if (IsAllConstants)
6816     return SDValue();
6817
6818   // For AVX-length vectors, build the individual 128-bit pieces and use
6819   // shuffles to put them in place.
6820   if (VT.is256BitVector() || VT.is512BitVector()) {
6821     SmallVector<SDValue, 64> V;
6822     for (unsigned i = 0; i != NumElems; ++i)
6823       V.push_back(Op.getOperand(i));
6824
6825     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6826
6827     // Build both the lower and upper subvector.
6828     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6829                                 makeArrayRef(&V[0], NumElems/2));
6830     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6831                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6832
6833     // Recreate the wider vector with the lower and upper part.
6834     if (VT.is256BitVector())
6835       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6836     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6837   }
6838
6839   // Let legalizer expand 2-wide build_vectors.
6840   if (EVTBits == 64) {
6841     if (NumNonZero == 1) {
6842       // One half is zero or undef.
6843       unsigned Idx = countTrailingZeros(NonZeros);
6844       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6845                                  Op.getOperand(Idx));
6846       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6847     }
6848     return SDValue();
6849   }
6850
6851   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6852   if (EVTBits == 8 && NumElems == 16) {
6853     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6854                                         Subtarget, *this);
6855     if (V.getNode()) return V;
6856   }
6857
6858   if (EVTBits == 16 && NumElems == 8) {
6859     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6860                                       Subtarget, *this);
6861     if (V.getNode()) return V;
6862   }
6863
6864   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6865   if (EVTBits == 32 && NumElems == 4) {
6866     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6867                                       NumZero, DAG, Subtarget, *this);
6868     if (V.getNode())
6869       return V;
6870   }
6871
6872   // If element VT is == 32 bits, turn it into a number of shuffles.
6873   SmallVector<SDValue, 8> V(NumElems);
6874   if (NumElems == 4 && NumZero > 0) {
6875     for (unsigned i = 0; i < 4; ++i) {
6876       bool isZero = !(NonZeros & (1 << i));
6877       if (isZero)
6878         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6879       else
6880         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6881     }
6882
6883     for (unsigned i = 0; i < 2; ++i) {
6884       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6885         default: break;
6886         case 0:
6887           V[i] = V[i*2];  // Must be a zero vector.
6888           break;
6889         case 1:
6890           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6891           break;
6892         case 2:
6893           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6894           break;
6895         case 3:
6896           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6897           break;
6898       }
6899     }
6900
6901     bool Reverse1 = (NonZeros & 0x3) == 2;
6902     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6903     int MaskVec[] = {
6904       Reverse1 ? 1 : 0,
6905       Reverse1 ? 0 : 1,
6906       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6907       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6908     };
6909     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6910   }
6911
6912   if (Values.size() > 1 && VT.is128BitVector()) {
6913     // Check for a build vector of consecutive loads.
6914     for (unsigned i = 0; i < NumElems; ++i)
6915       V[i] = Op.getOperand(i);
6916
6917     // Check for elements which are consecutive loads.
6918     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6919     if (LD.getNode())
6920       return LD;
6921
6922     // Check for a build vector from mostly shuffle plus few inserting.
6923     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6924     if (Sh.getNode())
6925       return Sh;
6926
6927     // For SSE 4.1, use insertps to put the high elements into the low element.
6928     if (getSubtarget()->hasSSE41()) {
6929       SDValue Result;
6930       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6931         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6932       else
6933         Result = DAG.getUNDEF(VT);
6934
6935       for (unsigned i = 1; i < NumElems; ++i) {
6936         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6937         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6938                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6939       }
6940       return Result;
6941     }
6942
6943     // Otherwise, expand into a number of unpckl*, start by extending each of
6944     // our (non-undef) elements to the full vector width with the element in the
6945     // bottom slot of the vector (which generates no code for SSE).
6946     for (unsigned i = 0; i < NumElems; ++i) {
6947       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6948         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6949       else
6950         V[i] = DAG.getUNDEF(VT);
6951     }
6952
6953     // Next, we iteratively mix elements, e.g. for v4f32:
6954     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6955     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6956     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6957     unsigned EltStride = NumElems >> 1;
6958     while (EltStride != 0) {
6959       for (unsigned i = 0; i < EltStride; ++i) {
6960         // If V[i+EltStride] is undef and this is the first round of mixing,
6961         // then it is safe to just drop this shuffle: V[i] is already in the
6962         // right place, the one element (since it's the first round) being
6963         // inserted as undef can be dropped.  This isn't safe for successive
6964         // rounds because they will permute elements within both vectors.
6965         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6966             EltStride == NumElems/2)
6967           continue;
6968
6969         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6970       }
6971       EltStride >>= 1;
6972     }
6973     return V[0];
6974   }
6975   return SDValue();
6976 }
6977
6978 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6979 // to create 256-bit vectors from two other 128-bit ones.
6980 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6981   SDLoc dl(Op);
6982   MVT ResVT = Op.getSimpleValueType();
6983
6984   assert((ResVT.is256BitVector() ||
6985           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6986
6987   SDValue V1 = Op.getOperand(0);
6988   SDValue V2 = Op.getOperand(1);
6989   unsigned NumElems = ResVT.getVectorNumElements();
6990   if(ResVT.is256BitVector())
6991     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6992
6993   if (Op.getNumOperands() == 4) {
6994     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6995                                 ResVT.getVectorNumElements()/2);
6996     SDValue V3 = Op.getOperand(2);
6997     SDValue V4 = Op.getOperand(3);
6998     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6999       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7000   }
7001   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7002 }
7003
7004 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7005   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7006   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7007          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7008           Op.getNumOperands() == 4)));
7009
7010   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7011   // from two other 128-bit ones.
7012
7013   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7014   return LowerAVXCONCAT_VECTORS(Op, DAG);
7015 }
7016
7017
7018 //===----------------------------------------------------------------------===//
7019 // Vector shuffle lowering
7020 //
7021 // This is an experimental code path for lowering vector shuffles on x86. It is
7022 // designed to handle arbitrary vector shuffles and blends, gracefully
7023 // degrading performance as necessary. It works hard to recognize idiomatic
7024 // shuffles and lower them to optimal instruction patterns without leaving
7025 // a framework that allows reasonably efficient handling of all vector shuffle
7026 // patterns.
7027 //===----------------------------------------------------------------------===//
7028
7029 /// \brief Tiny helper function to identify a no-op mask.
7030 ///
7031 /// This is a somewhat boring predicate function. It checks whether the mask
7032 /// array input, which is assumed to be a single-input shuffle mask of the kind
7033 /// used by the X86 shuffle instructions (not a fully general
7034 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7035 /// in-place shuffle are 'no-op's.
7036 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7037   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7038     if (Mask[i] != -1 && Mask[i] != i)
7039       return false;
7040   return true;
7041 }
7042
7043 /// \brief Helper function to classify a mask as a single-input mask.
7044 ///
7045 /// This isn't a generic single-input test because in the vector shuffle
7046 /// lowering we canonicalize single inputs to be the first input operand. This
7047 /// means we can more quickly test for a single input by only checking whether
7048 /// an input from the second operand exists. We also assume that the size of
7049 /// mask corresponds to the size of the input vectors which isn't true in the
7050 /// fully general case.
7051 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7052   for (int M : Mask)
7053     if (M >= (int)Mask.size())
7054       return false;
7055   return true;
7056 }
7057
7058 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7059 // 2013 will allow us to use it as a non-type template parameter.
7060 namespace {
7061
7062 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7063 ///
7064 /// See its documentation for details.
7065 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7066   if (Mask.size() != Args.size())
7067     return false;
7068   for (int i = 0, e = Mask.size(); i < e; ++i) {
7069     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7070     assert(*Args[i] < (int)Args.size() * 2 &&
7071            "Argument outside the range of possible shuffle inputs!");
7072     if (Mask[i] != -1 && Mask[i] != *Args[i])
7073       return false;
7074   }
7075   return true;
7076 }
7077
7078 } // namespace
7079
7080 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7081 /// arguments.
7082 ///
7083 /// This is a fast way to test a shuffle mask against a fixed pattern:
7084 ///
7085 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7086 ///
7087 /// It returns true if the mask is exactly as wide as the argument list, and
7088 /// each element of the mask is either -1 (signifying undef) or the value given
7089 /// in the argument.
7090 static const VariadicFunction1<
7091     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7092
7093 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7094 ///
7095 /// This helper function produces an 8-bit shuffle immediate corresponding to
7096 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7097 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7098 /// example.
7099 ///
7100 /// NB: We rely heavily on "undef" masks preserving the input lane.
7101 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7102                                           SelectionDAG &DAG) {
7103   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7104   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7105   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7106   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7107   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7108
7109   unsigned Imm = 0;
7110   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7111   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7112   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7113   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7114   return DAG.getConstant(Imm, MVT::i8);
7115 }
7116
7117 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7118 ///
7119 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7120 /// support for floating point shuffles but not integer shuffles. These
7121 /// instructions will incur a domain crossing penalty on some chips though so
7122 /// it is better to avoid lowering through this for integer vectors where
7123 /// possible.
7124 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7125                                        const X86Subtarget *Subtarget,
7126                                        SelectionDAG &DAG) {
7127   SDLoc DL(Op);
7128   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7129   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7130   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7131   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7132   ArrayRef<int> Mask = SVOp->getMask();
7133   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7134
7135   if (isSingleInputShuffleMask(Mask)) {
7136     // Straight shuffle of a single input vector. Simulate this by using the
7137     // single input as both of the "inputs" to this instruction..
7138     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7139     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7140                        DAG.getConstant(SHUFPDMask, MVT::i8));
7141   }
7142   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7143   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7144
7145   // Use dedicated unpack instructions for masks that match their pattern.
7146   if (isShuffleEquivalent(Mask, 0, 2))
7147     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7148   if (isShuffleEquivalent(Mask, 1, 3))
7149     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7150
7151   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7152   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7153                      DAG.getConstant(SHUFPDMask, MVT::i8));
7154 }
7155
7156 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7157 ///
7158 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7159 /// the integer unit to minimize domain crossing penalties. However, for blends
7160 /// it falls back to the floating point shuffle operation with appropriate bit
7161 /// casting.
7162 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7163                                        const X86Subtarget *Subtarget,
7164                                        SelectionDAG &DAG) {
7165   SDLoc DL(Op);
7166   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7167   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7168   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7169   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7170   ArrayRef<int> Mask = SVOp->getMask();
7171   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7172
7173   if (isSingleInputShuffleMask(Mask)) {
7174     // Straight shuffle of a single input vector. For everything from SSE2
7175     // onward this has a single fast instruction with no scary immediates.
7176     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7177     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7178     int WidenedMask[4] = {
7179         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7180         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7181     return DAG.getNode(
7182         ISD::BITCAST, DL, MVT::v2i64,
7183         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7184                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7185   }
7186
7187   // Use dedicated unpack instructions for masks that match their pattern.
7188   if (isShuffleEquivalent(Mask, 0, 2))
7189     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7190   if (isShuffleEquivalent(Mask, 1, 3))
7191     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7192
7193   // We implement this with SHUFPD which is pretty lame because it will likely
7194   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7195   // However, all the alternatives are still more cycles and newer chips don't
7196   // have this problem. It would be really nice if x86 had better shuffles here.
7197   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7198   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7199   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7200                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7201 }
7202
7203 /// \brief Lower 4-lane 32-bit floating point shuffles.
7204 ///
7205 /// Uses instructions exclusively from the floating point unit to minimize
7206 /// domain crossing penalties, as these are sufficient to implement all v4f32
7207 /// shuffles.
7208 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7209                                        const X86Subtarget *Subtarget,
7210                                        SelectionDAG &DAG) {
7211   SDLoc DL(Op);
7212   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7213   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7214   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7215   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7216   ArrayRef<int> Mask = SVOp->getMask();
7217   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7218
7219   SDValue LowV = V1, HighV = V2;
7220   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7221
7222   int NumV2Elements =
7223       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7224
7225   if (NumV2Elements == 0)
7226     // Straight shuffle of a single input vector. We pass the input vector to
7227     // both operands to simulate this with a SHUFPS.
7228     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7229                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7230
7231   // Use dedicated unpack instructions for masks that match their pattern.
7232   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7233     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7234   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7235     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7236
7237   if (NumV2Elements == 1) {
7238     int V2Index =
7239         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7240         Mask.begin();
7241     // Compute the index adjacent to V2Index and in the same half by toggling
7242     // the low bit.
7243     int V2AdjIndex = V2Index ^ 1;
7244
7245     if (Mask[V2AdjIndex] == -1) {
7246       // Handles all the cases where we have a single V2 element and an undef.
7247       // This will only ever happen in the high lanes because we commute the
7248       // vector otherwise.
7249       if (V2Index < 2)
7250         std::swap(LowV, HighV);
7251       NewMask[V2Index] -= 4;
7252     } else {
7253       // Handle the case where the V2 element ends up adjacent to a V1 element.
7254       // To make this work, blend them together as the first step.
7255       int V1Index = V2AdjIndex;
7256       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7257       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7258                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7259
7260       // Now proceed to reconstruct the final blend as we have the necessary
7261       // high or low half formed.
7262       if (V2Index < 2) {
7263         LowV = V2;
7264         HighV = V1;
7265       } else {
7266         HighV = V2;
7267       }
7268       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7269       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7270     }
7271   } else if (NumV2Elements == 2) {
7272     if (Mask[0] < 4 && Mask[1] < 4) {
7273       // Handle the easy case where we have V1 in the low lanes and V2 in the
7274       // high lanes. We never see this reversed because we sort the shuffle.
7275       NewMask[2] -= 4;
7276       NewMask[3] -= 4;
7277     } else {
7278       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7279       // trying to place elements directly, just blend them and set up the final
7280       // shuffle to place them.
7281
7282       // The first two blend mask elements are for V1, the second two are for
7283       // V2.
7284       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7285                           Mask[2] < 4 ? Mask[2] : Mask[3],
7286                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7287                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7288       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7289                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7290
7291       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7292       // a blend.
7293       LowV = HighV = V1;
7294       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7295       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7296       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7297       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7298     }
7299   }
7300   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7301                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7302 }
7303
7304 /// \brief Lower 4-lane i32 vector shuffles.
7305 ///
7306 /// We try to handle these with integer-domain shuffles where we can, but for
7307 /// blends we use the floating point domain blend instructions.
7308 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7309                                        const X86Subtarget *Subtarget,
7310                                        SelectionDAG &DAG) {
7311   SDLoc DL(Op);
7312   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7313   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7314   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7315   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7316   ArrayRef<int> Mask = SVOp->getMask();
7317   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7318
7319   if (isSingleInputShuffleMask(Mask))
7320     // Straight shuffle of a single input vector. For everything from SSE2
7321     // onward this has a single fast instruction with no scary immediates.
7322     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7323                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7324
7325   // Use dedicated unpack instructions for masks that match their pattern.
7326   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7327     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7328   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7329     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7330
7331   // We implement this with SHUFPS because it can blend from two vectors.
7332   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7333   // up the inputs, bypassing domain shift penalties that we would encur if we
7334   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7335   // relevant.
7336   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7337                      DAG.getVectorShuffle(
7338                          MVT::v4f32, DL,
7339                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7340                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7341 }
7342
7343 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7344 /// shuffle lowering, and the most complex part.
7345 ///
7346 /// The lowering strategy is to try to form pairs of input lanes which are
7347 /// targeted at the same half of the final vector, and then use a dword shuffle
7348 /// to place them onto the right half, and finally unpack the paired lanes into
7349 /// their final position.
7350 ///
7351 /// The exact breakdown of how to form these dword pairs and align them on the
7352 /// correct sides is really tricky. See the comments within the function for
7353 /// more of the details.
7354 static SDValue lowerV8I16SingleInputVectorShuffle(
7355     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7356     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7357   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7358   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7359   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7360
7361   SmallVector<int, 4> LoInputs;
7362   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7363                [](int M) { return M >= 0; });
7364   std::sort(LoInputs.begin(), LoInputs.end());
7365   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7366   SmallVector<int, 4> HiInputs;
7367   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7368                [](int M) { return M >= 0; });
7369   std::sort(HiInputs.begin(), HiInputs.end());
7370   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7371   int NumLToL =
7372       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7373   int NumHToL = LoInputs.size() - NumLToL;
7374   int NumLToH =
7375       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7376   int NumHToH = HiInputs.size() - NumLToH;
7377   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7378   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7379   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7380   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7381
7382   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7383   // such inputs we can swap two of the dwords across the half mark and end up
7384   // with <=2 inputs to each half in each half. Once there, we can fall through
7385   // to the generic code below. For example:
7386   //
7387   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7388   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7389   //
7390   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7391   // and an existing 2-into-2 on the other half. In this case we may have to
7392   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7393   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7394   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7395   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7396   // half than the one we target for fixing) will be fixed when we re-enter this
7397   // path. We will also combine away any sequence of PSHUFD instructions that
7398   // result into a single instruction. Here is an example of the tricky case:
7399   //
7400   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7401   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7402   //
7403   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7404   //
7405   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7406   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7407   //
7408   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7409   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7410   //
7411   // The result is fine to be handled by the generic logic.
7412   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7413                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7414                           int AOffset, int BOffset) {
7415     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7416            "Must call this with A having 3 or 1 inputs from the A half.");
7417     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7418            "Must call this with B having 1 or 3 inputs from the B half.");
7419     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7420            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7421
7422     // Compute the index of dword with only one word among the three inputs in
7423     // a half by taking the sum of the half with three inputs and subtracting
7424     // the sum of the actual three inputs. The difference is the remaining
7425     // slot.
7426     int ADWord, BDWord;
7427     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7428     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7429     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7430     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7431     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7432     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7433     int TripleNonInputIdx =
7434         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7435     TripleDWord = TripleNonInputIdx / 2;
7436
7437     // We use xor with one to compute the adjacent DWord to whichever one the
7438     // OneInput is in.
7439     OneInputDWord = (OneInput / 2) ^ 1;
7440
7441     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7442     // and BToA inputs. If there is also such a problem with the BToB and AToB
7443     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7444     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7445     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7446     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7447       // Compute how many inputs will be flipped by swapping these DWords. We
7448       // need
7449       // to balance this to ensure we don't form a 3-1 shuffle in the other
7450       // half.
7451       int NumFlippedAToBInputs =
7452           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7453           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7454       int NumFlippedBToBInputs =
7455           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7456           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7457       if ((NumFlippedAToBInputs == 1 &&
7458            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7459           (NumFlippedBToBInputs == 1 &&
7460            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7461         // We choose whether to fix the A half or B half based on whether that
7462         // half has zero flipped inputs. At zero, we may not be able to fix it
7463         // with that half. We also bias towards fixing the B half because that
7464         // will more commonly be the high half, and we have to bias one way.
7465         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7466                                                        ArrayRef<int> Inputs) {
7467           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7468           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7469                                          PinnedIdx ^ 1) != Inputs.end();
7470           // Determine whether the free index is in the flipped dword or the
7471           // unflipped dword based on where the pinned index is. We use this bit
7472           // in an xor to conditionally select the adjacent dword.
7473           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7474           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7475                                              FixFreeIdx) != Inputs.end();
7476           if (IsFixIdxInput == IsFixFreeIdxInput)
7477             FixFreeIdx += 1;
7478           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7479                                         FixFreeIdx) != Inputs.end();
7480           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7481                  "We need to be changing the number of flipped inputs!");
7482           int PSHUFHalfMask[] = {0, 1, 2, 3};
7483           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7484           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7485                           MVT::v8i16, V,
7486                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7487
7488           for (int &M : Mask)
7489             if (M != -1 && M == FixIdx)
7490               M = FixFreeIdx;
7491             else if (M != -1 && M == FixFreeIdx)
7492               M = FixIdx;
7493         };
7494         if (NumFlippedBToBInputs != 0) {
7495           int BPinnedIdx =
7496               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7497           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7498         } else {
7499           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7500           int APinnedIdx =
7501               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7502           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7503         }
7504       }
7505     }
7506
7507     int PSHUFDMask[] = {0, 1, 2, 3};
7508     PSHUFDMask[ADWord] = BDWord;
7509     PSHUFDMask[BDWord] = ADWord;
7510     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7511                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7512                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7513                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7514
7515     // Adjust the mask to match the new locations of A and B.
7516     for (int &M : Mask)
7517       if (M != -1 && M/2 == ADWord)
7518         M = 2 * BDWord + M % 2;
7519       else if (M != -1 && M/2 == BDWord)
7520         M = 2 * ADWord + M % 2;
7521
7522     // Recurse back into this routine to re-compute state now that this isn't
7523     // a 3 and 1 problem.
7524     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7525                                 Mask);
7526   };
7527   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7528     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7529   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7530     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7531
7532   // At this point there are at most two inputs to the low and high halves from
7533   // each half. That means the inputs can always be grouped into dwords and
7534   // those dwords can then be moved to the correct half with a dword shuffle.
7535   // We use at most one low and one high word shuffle to collect these paired
7536   // inputs into dwords, and finally a dword shuffle to place them.
7537   int PSHUFLMask[4] = {-1, -1, -1, -1};
7538   int PSHUFHMask[4] = {-1, -1, -1, -1};
7539   int PSHUFDMask[4] = {-1, -1, -1, -1};
7540
7541   // First fix the masks for all the inputs that are staying in their
7542   // original halves. This will then dictate the targets of the cross-half
7543   // shuffles.
7544   auto fixInPlaceInputs =
7545       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7546                     MutableArrayRef<int> SourceHalfMask,
7547                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7548     if (InPlaceInputs.empty())
7549       return;
7550     if (InPlaceInputs.size() == 1) {
7551       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7552           InPlaceInputs[0] - HalfOffset;
7553       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7554       return;
7555     }
7556     if (IncomingInputs.empty()) {
7557       // Just fix all of the in place inputs.
7558       for (int Input : InPlaceInputs) {
7559         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7560         PSHUFDMask[Input / 2] = Input / 2;
7561       }
7562       return;
7563     }
7564
7565     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7566     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7567         InPlaceInputs[0] - HalfOffset;
7568     // Put the second input next to the first so that they are packed into
7569     // a dword. We find the adjacent index by toggling the low bit.
7570     int AdjIndex = InPlaceInputs[0] ^ 1;
7571     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7572     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7573     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7574   };
7575   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7576   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7577
7578   // Now gather the cross-half inputs and place them into a free dword of
7579   // their target half.
7580   // FIXME: This operation could almost certainly be simplified dramatically to
7581   // look more like the 3-1 fixing operation.
7582   auto moveInputsToRightHalf = [&PSHUFDMask](
7583       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7584       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7585       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7586       int DestOffset) {
7587     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7588       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7589     };
7590     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7591                                                int Word) {
7592       int LowWord = Word & ~1;
7593       int HighWord = Word | 1;
7594       return isWordClobbered(SourceHalfMask, LowWord) ||
7595              isWordClobbered(SourceHalfMask, HighWord);
7596     };
7597
7598     if (IncomingInputs.empty())
7599       return;
7600
7601     if (ExistingInputs.empty()) {
7602       // Map any dwords with inputs from them into the right half.
7603       for (int Input : IncomingInputs) {
7604         // If the source half mask maps over the inputs, turn those into
7605         // swaps and use the swapped lane.
7606         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7607           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7608             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7609                 Input - SourceOffset;
7610             // We have to swap the uses in our half mask in one sweep.
7611             for (int &M : HalfMask)
7612               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7613                 M = Input;
7614               else if (M == Input)
7615                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7616           } else {
7617             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7618                        Input - SourceOffset &&
7619                    "Previous placement doesn't match!");
7620           }
7621           // Note that this correctly re-maps both when we do a swap and when
7622           // we observe the other side of the swap above. We rely on that to
7623           // avoid swapping the members of the input list directly.
7624           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7625         }
7626
7627         // Map the input's dword into the correct half.
7628         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7629           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7630         else
7631           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7632                      Input / 2 &&
7633                  "Previous placement doesn't match!");
7634       }
7635
7636       // And just directly shift any other-half mask elements to be same-half
7637       // as we will have mirrored the dword containing the element into the
7638       // same position within that half.
7639       for (int &M : HalfMask)
7640         if (M >= SourceOffset && M < SourceOffset + 4) {
7641           M = M - SourceOffset + DestOffset;
7642           assert(M >= 0 && "This should never wrap below zero!");
7643         }
7644       return;
7645     }
7646
7647     // Ensure we have the input in a viable dword of its current half. This
7648     // is particularly tricky because the original position may be clobbered
7649     // by inputs being moved and *staying* in that half.
7650     if (IncomingInputs.size() == 1) {
7651       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7652         int InputFixed = std::find(std::begin(SourceHalfMask),
7653                                    std::end(SourceHalfMask), -1) -
7654                          std::begin(SourceHalfMask) + SourceOffset;
7655         SourceHalfMask[InputFixed - SourceOffset] =
7656             IncomingInputs[0] - SourceOffset;
7657         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7658                      InputFixed);
7659         IncomingInputs[0] = InputFixed;
7660       }
7661     } else if (IncomingInputs.size() == 2) {
7662       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7663           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7664         // We have two non-adjacent or clobbered inputs we need to extract from
7665         // the source half. To do this, we need to map them into some adjacent
7666         // dword slot in the source mask.
7667         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7668                               IncomingInputs[1] - SourceOffset};
7669
7670         // If there is a free slot in the source half mask adjacent to one of
7671         // the inputs, place the other input in it. We use (Index XOR 1) to
7672         // compute an adjacent index.
7673         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7674             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7675           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7676           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7677           InputsFixed[1] = InputsFixed[0] ^ 1;
7678         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7679                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7680           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7681           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7682           InputsFixed[0] = InputsFixed[1] ^ 1;
7683         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7684                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7685           // The two inputs are in the same DWord but it is clobbered and the
7686           // adjacent DWord isn't used at all. Move both inputs to the free
7687           // slot.
7688           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7689           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7690           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7691           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7692         } else {
7693           // The only way we hit this point is if there is no clobbering
7694           // (because there are no off-half inputs to this half) and there is no
7695           // free slot adjacent to one of the inputs. In this case, we have to
7696           // swap an input with a non-input.
7697           for (int i = 0; i < 4; ++i)
7698             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7699                    "We can't handle any clobbers here!");
7700           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7701                  "Cannot have adjacent inputs here!");
7702
7703           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7704           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7705
7706           // We also have to update the final source mask in this case because
7707           // it may need to undo the above swap.
7708           for (int &M : FinalSourceHalfMask)
7709             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
7710               M = InputsFixed[1] + SourceOffset;
7711             else if (M == InputsFixed[1] + SourceOffset)
7712               M = (InputsFixed[0] ^ 1) + SourceOffset;
7713
7714           InputsFixed[1] = InputsFixed[0] ^ 1;
7715         }
7716
7717         // Point everything at the fixed inputs.
7718         for (int &M : HalfMask)
7719           if (M == IncomingInputs[0])
7720             M = InputsFixed[0] + SourceOffset;
7721           else if (M == IncomingInputs[1])
7722             M = InputsFixed[1] + SourceOffset;
7723
7724         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7725         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7726       }
7727     } else {
7728       llvm_unreachable("Unhandled input size!");
7729     }
7730
7731     // Now hoist the DWord down to the right half.
7732     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7733     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7734     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7735     for (int &M : HalfMask)
7736       for (int Input : IncomingInputs)
7737         if (M == Input)
7738           M = FreeDWord * 2 + Input % 2;
7739   };
7740   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
7741                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7742   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
7743                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7744
7745   // Now enact all the shuffles we've computed to move the inputs into their
7746   // target half.
7747   if (!isNoopShuffleMask(PSHUFLMask))
7748     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7749                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7750   if (!isNoopShuffleMask(PSHUFHMask))
7751     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7752                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7753   if (!isNoopShuffleMask(PSHUFDMask))
7754     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7755                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7756                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7757                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7758
7759   // At this point, each half should contain all its inputs, and we can then
7760   // just shuffle them into their final position.
7761   assert(std::count_if(LoMask.begin(), LoMask.end(),
7762                        [](int M) { return M >= 4; }) == 0 &&
7763          "Failed to lift all the high half inputs to the low mask!");
7764   assert(std::count_if(HiMask.begin(), HiMask.end(),
7765                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7766          "Failed to lift all the low half inputs to the high mask!");
7767
7768   // Do a half shuffle for the low mask.
7769   if (!isNoopShuffleMask(LoMask))
7770     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7771                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7772
7773   // Do a half shuffle with the high mask after shifting its values down.
7774   for (int &M : HiMask)
7775     if (M >= 0)
7776       M -= 4;
7777   if (!isNoopShuffleMask(HiMask))
7778     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7779                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7780
7781   return V;
7782 }
7783
7784 /// \brief Detect whether the mask pattern should be lowered through
7785 /// interleaving.
7786 ///
7787 /// This essentially tests whether viewing the mask as an interleaving of two
7788 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7789 /// lowering it through interleaving is a significantly better strategy.
7790 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7791   int NumEvenInputs[2] = {0, 0};
7792   int NumOddInputs[2] = {0, 0};
7793   int NumLoInputs[2] = {0, 0};
7794   int NumHiInputs[2] = {0, 0};
7795   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7796     if (Mask[i] < 0)
7797       continue;
7798
7799     int InputIdx = Mask[i] >= Size;
7800
7801     if (i < Size / 2)
7802       ++NumLoInputs[InputIdx];
7803     else
7804       ++NumHiInputs[InputIdx];
7805
7806     if ((i % 2) == 0)
7807       ++NumEvenInputs[InputIdx];
7808     else
7809       ++NumOddInputs[InputIdx];
7810   }
7811
7812   // The minimum number of cross-input results for both the interleaved and
7813   // split cases. If interleaving results in fewer cross-input results, return
7814   // true.
7815   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7816                                     NumEvenInputs[0] + NumOddInputs[1]);
7817   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7818                               NumLoInputs[0] + NumHiInputs[1]);
7819   return InterleavedCrosses < SplitCrosses;
7820 }
7821
7822 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7823 ///
7824 /// This strategy only works when the inputs from each vector fit into a single
7825 /// half of that vector, and generally there are not so many inputs as to leave
7826 /// the in-place shuffles required highly constrained (and thus expensive). It
7827 /// shifts all the inputs into a single side of both input vectors and then
7828 /// uses an unpack to interleave these inputs in a single vector. At that
7829 /// point, we will fall back on the generic single input shuffle lowering.
7830 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7831                                                  SDValue V2,
7832                                                  MutableArrayRef<int> Mask,
7833                                                  const X86Subtarget *Subtarget,
7834                                                  SelectionDAG &DAG) {
7835   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7836   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7837   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7838   for (int i = 0; i < 8; ++i)
7839     if (Mask[i] >= 0 && Mask[i] < 4)
7840       LoV1Inputs.push_back(i);
7841     else if (Mask[i] >= 4 && Mask[i] < 8)
7842       HiV1Inputs.push_back(i);
7843     else if (Mask[i] >= 8 && Mask[i] < 12)
7844       LoV2Inputs.push_back(i);
7845     else if (Mask[i] >= 12)
7846       HiV2Inputs.push_back(i);
7847
7848   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7849   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7850   (void)NumV1Inputs;
7851   (void)NumV2Inputs;
7852   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7853   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7854   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7855
7856   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7857                      HiV1Inputs.size() + HiV2Inputs.size();
7858
7859   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7860                               ArrayRef<int> HiInputs, bool MoveToLo,
7861                               int MaskOffset) {
7862     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7863     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7864     if (BadInputs.empty())
7865       return V;
7866
7867     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7868     int MoveOffset = MoveToLo ? 0 : 4;
7869
7870     if (GoodInputs.empty()) {
7871       for (int BadInput : BadInputs) {
7872         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7873         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7874       }
7875     } else {
7876       if (GoodInputs.size() == 2) {
7877         // If the low inputs are spread across two dwords, pack them into
7878         // a single dword.
7879         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
7880         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
7881         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
7882         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
7883       } else {
7884         // Otherwise pin the good inputs.
7885         for (int GoodInput : GoodInputs)
7886           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7887       }
7888
7889       if (BadInputs.size() == 2) {
7890         // If we have two bad inputs then there may be either one or two good
7891         // inputs fixed in place. Find a fixed input, and then find the *other*
7892         // two adjacent indices by using modular arithmetic.
7893         int GoodMaskIdx =
7894             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
7895                          [](int M) { return M >= 0; }) -
7896             std::begin(MoveMask);
7897         int MoveMaskIdx =
7898             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
7899         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7900         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7901         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7902         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
7903         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7904         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
7905       } else {
7906         assert(BadInputs.size() == 1 && "All sizes handled");
7907         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
7908                                     std::end(MoveMask), -1) -
7909                           std::begin(MoveMask);
7910         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7911         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7912       }
7913     }
7914
7915     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7916                                 MoveMask);
7917   };
7918   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7919                         /*MaskOffset*/ 0);
7920   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7921                         /*MaskOffset*/ 8);
7922
7923   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7924   // cross-half traffic in the final shuffle.
7925
7926   // Munge the mask to be a single-input mask after the unpack merges the
7927   // results.
7928   for (int &M : Mask)
7929     if (M != -1)
7930       M = 2 * (M % 4) + (M / 8);
7931
7932   return DAG.getVectorShuffle(
7933       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7934                                   DL, MVT::v8i16, V1, V2),
7935       DAG.getUNDEF(MVT::v8i16), Mask);
7936 }
7937
7938 /// \brief Generic lowering of 8-lane i16 shuffles.
7939 ///
7940 /// This handles both single-input shuffles and combined shuffle/blends with
7941 /// two inputs. The single input shuffles are immediately delegated to
7942 /// a dedicated lowering routine.
7943 ///
7944 /// The blends are lowered in one of three fundamental ways. If there are few
7945 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7946 /// of the input is significantly cheaper when lowered as an interleaving of
7947 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7948 /// halves of the inputs separately (making them have relatively few inputs)
7949 /// and then concatenate them.
7950 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7951                                        const X86Subtarget *Subtarget,
7952                                        SelectionDAG &DAG) {
7953   SDLoc DL(Op);
7954   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7955   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7956   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7957   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7958   ArrayRef<int> OrigMask = SVOp->getMask();
7959   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7960                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7961   MutableArrayRef<int> Mask(MaskStorage);
7962
7963   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7964
7965   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7966   auto isV2 = [](int M) { return M >= 8; };
7967
7968   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7969   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7970
7971   if (NumV2Inputs == 0)
7972     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7973
7974   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7975                             "to be V1-input shuffles.");
7976
7977   if (NumV1Inputs + NumV2Inputs <= 4)
7978     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7979
7980   // Check whether an interleaving lowering is likely to be more efficient.
7981   // This isn't perfect but it is a strong heuristic that tends to work well on
7982   // the kinds of shuffles that show up in practice.
7983   //
7984   // FIXME: Handle 1x, 2x, and 4x interleaving.
7985   if (shouldLowerAsInterleaving(Mask)) {
7986     // FIXME: Figure out whether we should pack these into the low or high
7987     // halves.
7988
7989     int EMask[8], OMask[8];
7990     for (int i = 0; i < 4; ++i) {
7991       EMask[i] = Mask[2*i];
7992       OMask[i] = Mask[2*i + 1];
7993       EMask[i + 4] = -1;
7994       OMask[i + 4] = -1;
7995     }
7996
7997     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7998     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7999
8000     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
8001   }
8002
8003   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8004   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8005
8006   for (int i = 0; i < 4; ++i) {
8007     LoBlendMask[i] = Mask[i];
8008     HiBlendMask[i] = Mask[i + 4];
8009   }
8010
8011   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8012   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8013   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
8014   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
8015
8016   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8017                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
8018 }
8019
8020 /// \brief Check whether a compaction lowering can be done by dropping even
8021 /// elements and compute how many times even elements must be dropped.
8022 ///
8023 /// This handles shuffles which take every Nth element where N is a power of
8024 /// two. Example shuffle masks:
8025 ///
8026 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8027 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8028 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8029 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8030 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8031 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8032 ///
8033 /// Any of these lanes can of course be undef.
8034 ///
8035 /// This routine only supports N <= 3.
8036 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8037 /// for larger N.
8038 ///
8039 /// \returns N above, or the number of times even elements must be dropped if
8040 /// there is such a number. Otherwise returns zero.
8041 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8042   // Figure out whether we're looping over two inputs or just one.
8043   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8044
8045   // The modulus for the shuffle vector entries is based on whether this is
8046   // a single input or not.
8047   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8048   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8049          "We should only be called with masks with a power-of-2 size!");
8050
8051   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8052
8053   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8054   // and 2^3 simultaneously. This is because we may have ambiguity with
8055   // partially undef inputs.
8056   bool ViableForN[3] = {true, true, true};
8057
8058   for (int i = 0, e = Mask.size(); i < e; ++i) {
8059     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8060     // want.
8061     if (Mask[i] == -1)
8062       continue;
8063
8064     bool IsAnyViable = false;
8065     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8066       if (ViableForN[j]) {
8067         uint64_t N = j + 1;
8068
8069         // The shuffle mask must be equal to (i * 2^N) % M.
8070         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8071           IsAnyViable = true;
8072         else
8073           ViableForN[j] = false;
8074       }
8075     // Early exit if we exhaust the possible powers of two.
8076     if (!IsAnyViable)
8077       break;
8078   }
8079
8080   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8081     if (ViableForN[j])
8082       return j + 1;
8083
8084   // Return 0 as there is no viable power of two.
8085   return 0;
8086 }
8087
8088 /// \brief Generic lowering of v16i8 shuffles.
8089 ///
8090 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8091 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8092 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8093 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8094 /// back together.
8095 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8096                                        const X86Subtarget *Subtarget,
8097                                        SelectionDAG &DAG) {
8098   SDLoc DL(Op);
8099   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8100   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8101   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8102   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8103   ArrayRef<int> OrigMask = SVOp->getMask();
8104   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8105   int MaskStorage[16] = {
8106       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
8107       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
8108       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
8109       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8110   MutableArrayRef<int> Mask(MaskStorage);
8111   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8112   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8113
8114   // For single-input shuffles, there are some nicer lowering tricks we can use.
8115   if (isSingleInputShuffleMask(Mask)) {
8116     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8117     // Notably, this handles splat and partial-splat shuffles more efficiently.
8118     // However, it only makes sense if the pre-duplication shuffle simplifies
8119     // things significantly. Currently, this means we need to be able to
8120     // express the pre-duplication shuffle as an i16 shuffle.
8121     //
8122     // FIXME: We should check for other patterns which can be widened into an
8123     // i16 shuffle as well.
8124     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8125       for (int i = 0; i < 16; i += 2) {
8126         if (Mask[i] != Mask[i + 1])
8127           return false;
8128       }
8129       return true;
8130     };
8131     auto tryToWidenViaDuplication = [&]() -> SDValue {
8132       if (!canWidenViaDuplication(Mask))
8133         return SDValue();
8134       SmallVector<int, 4> LoInputs;
8135       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8136                    [](int M) { return M >= 0 && M < 8; });
8137       std::sort(LoInputs.begin(), LoInputs.end());
8138       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8139                      LoInputs.end());
8140       SmallVector<int, 4> HiInputs;
8141       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8142                    [](int M) { return M >= 8; });
8143       std::sort(HiInputs.begin(), HiInputs.end());
8144       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8145                      HiInputs.end());
8146
8147       bool TargetLo = LoInputs.size() >= HiInputs.size();
8148       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8149       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8150
8151       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8152       SmallDenseMap<int, int, 8> LaneMap;
8153       for (int I : InPlaceInputs) {
8154         PreDupI16Shuffle[I/2] = I/2;
8155         LaneMap[I] = I;
8156       }
8157       int j = TargetLo ? 0 : 4, je = j + 4;
8158       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8159         // Check if j is already a shuffle of this input. This happens when
8160         // there are two adjacent bytes after we move the low one.
8161         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8162           // If we haven't yet mapped the input, search for a slot into which
8163           // we can map it.
8164           while (j < je && PreDupI16Shuffle[j] != -1)
8165             ++j;
8166
8167           if (j == je)
8168             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8169             return SDValue();
8170
8171           // Map this input with the i16 shuffle.
8172           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8173         }
8174
8175         // Update the lane map based on the mapping we ended up with.
8176         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8177       }
8178       V1 = DAG.getNode(
8179           ISD::BITCAST, DL, MVT::v16i8,
8180           DAG.getVectorShuffle(MVT::v8i16, DL,
8181                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8182                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8183
8184       // Unpack the bytes to form the i16s that will be shuffled into place.
8185       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8186                        MVT::v16i8, V1, V1);
8187
8188       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8189       for (int i = 0; i < 16; i += 2) {
8190         if (Mask[i] != -1)
8191           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8192         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8193       }
8194       return DAG.getNode(
8195           ISD::BITCAST, DL, MVT::v16i8,
8196           DAG.getVectorShuffle(MVT::v8i16, DL,
8197                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8198                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8199     };
8200     if (SDValue V = tryToWidenViaDuplication())
8201       return V;
8202   }
8203
8204   // Check whether an interleaving lowering is likely to be more efficient.
8205   // This isn't perfect but it is a strong heuristic that tends to work well on
8206   // the kinds of shuffles that show up in practice.
8207   //
8208   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8209   if (shouldLowerAsInterleaving(Mask)) {
8210     // FIXME: Figure out whether we should pack these into the low or high
8211     // halves.
8212
8213     int EMask[16], OMask[16];
8214     for (int i = 0; i < 8; ++i) {
8215       EMask[i] = Mask[2*i];
8216       OMask[i] = Mask[2*i + 1];
8217       EMask[i + 8] = -1;
8218       OMask[i + 8] = -1;
8219     }
8220
8221     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8222     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8223
8224     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8225   }
8226
8227   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8228   // with PSHUFB. It is important to do this before we attempt to generate any
8229   // blends but after all of the single-input lowerings. If the single input
8230   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8231   // want to preserve that and we can DAG combine any longer sequences into
8232   // a PSHUFB in the end. But once we start blending from multiple inputs,
8233   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8234   // and there are *very* few patterns that would actually be faster than the
8235   // PSHUFB approach because of its ability to zero lanes.
8236   //
8237   // FIXME: The only exceptions to the above are blends which are exact
8238   // interleavings with direct instructions supporting them. We currently don't
8239   // handle those well here.
8240   if (Subtarget->hasSSSE3()) {
8241     SDValue V1Mask[16];
8242     SDValue V2Mask[16];
8243     for (int i = 0; i < 16; ++i)
8244       if (Mask[i] == -1) {
8245         V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8246       } else {
8247         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8248         V2Mask[i] =
8249             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8250       }
8251     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8252                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8253     if (isSingleInputShuffleMask(Mask))
8254       return V1; // Single inputs are easy.
8255
8256     // Otherwise, blend the two.
8257     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8258                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8259     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8260   }
8261
8262   // Check whether a compaction lowering can be done. This handles shuffles
8263   // which take every Nth element for some even N. See the helper function for
8264   // details.
8265   //
8266   // We special case these as they can be particularly efficiently handled with
8267   // the PACKUSB instruction on x86 and they show up in common patterns of
8268   // rearranging bytes to truncate wide elements.
8269   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8270     // NumEvenDrops is the power of two stride of the elements. Another way of
8271     // thinking about it is that we need to drop the even elements this many
8272     // times to get the original input.
8273     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8274
8275     // First we need to zero all the dropped bytes.
8276     assert(NumEvenDrops <= 3 &&
8277            "No support for dropping even elements more than 3 times.");
8278     // We use the mask type to pick which bytes are preserved based on how many
8279     // elements are dropped.
8280     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8281     SDValue ByteClearMask =
8282         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8283                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8284     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8285     if (!IsSingleInput)
8286       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8287
8288     // Now pack things back together.
8289     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8290     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8291     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8292     for (int i = 1; i < NumEvenDrops; ++i) {
8293       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8294       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8295     }
8296
8297     return Result;
8298   }
8299
8300   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8301   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8302   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8303   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8304
8305   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8306                             MutableArrayRef<int> V1HalfBlendMask,
8307                             MutableArrayRef<int> V2HalfBlendMask) {
8308     for (int i = 0; i < 8; ++i)
8309       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8310         V1HalfBlendMask[i] = HalfMask[i];
8311         HalfMask[i] = i;
8312       } else if (HalfMask[i] >= 16) {
8313         V2HalfBlendMask[i] = HalfMask[i] - 16;
8314         HalfMask[i] = i + 8;
8315       }
8316   };
8317   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8318   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8319
8320   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8321
8322   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8323                              MutableArrayRef<int> HiBlendMask) {
8324     SDValue V1, V2;
8325     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8326     // them out and avoid using UNPCK{L,H} to extract the elements of V as
8327     // i16s.
8328     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8329                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
8330         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8331                      [](int M) { return M >= 0 && M % 2 == 1; })) {
8332       // Use a mask to drop the high bytes.
8333       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8334       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8335                        DAG.getConstant(0x00FF, MVT::v8i16));
8336
8337       // This will be a single vector shuffle instead of a blend so nuke V2.
8338       V2 = DAG.getUNDEF(MVT::v8i16);
8339
8340       // Squash the masks to point directly into V1.
8341       for (int &M : LoBlendMask)
8342         if (M >= 0)
8343           M /= 2;
8344       for (int &M : HiBlendMask)
8345         if (M >= 0)
8346           M /= 2;
8347     } else {
8348       // Otherwise just unpack the low half of V into V1 and the high half into
8349       // V2 so that we can blend them as i16s.
8350       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8351                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8352       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8353                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8354     }
8355
8356     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8357     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8358     return std::make_pair(BlendedLo, BlendedHi);
8359   };
8360   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8361   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8362   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8363
8364   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8365   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8366
8367   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8368 }
8369
8370 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8371 ///
8372 /// This routine breaks down the specific type of 128-bit shuffle and
8373 /// dispatches to the lowering routines accordingly.
8374 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8375                                         MVT VT, const X86Subtarget *Subtarget,
8376                                         SelectionDAG &DAG) {
8377   switch (VT.SimpleTy) {
8378   case MVT::v2i64:
8379     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8380   case MVT::v2f64:
8381     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8382   case MVT::v4i32:
8383     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8384   case MVT::v4f32:
8385     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8386   case MVT::v8i16:
8387     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8388   case MVT::v16i8:
8389     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8390
8391   default:
8392     llvm_unreachable("Unimplemented!");
8393   }
8394 }
8395
8396 static bool isHalfCrossingShuffleMask(ArrayRef<int> Mask) {
8397   int Size = Mask.size();
8398   for (int M : Mask.slice(0, Size / 2))
8399     if (M >= 0 && (M % Size) >= Size / 2)
8400       return true;
8401   for (int M : Mask.slice(Size / 2, Size / 2))
8402     if (M >= 0 && (M % Size) < Size / 2)
8403       return true;
8404   return false;
8405 }
8406
8407 /// \brief Generic routine to split a 256-bit vector shuffle into 128-bit
8408 /// shuffles.
8409 ///
8410 /// There is a severely limited set of shuffles available in AVX1 for 256-bit
8411 /// vectors resulting in routinely needing to split the shuffle into two 128-bit
8412 /// shuffles. This can be done generically for any 256-bit vector shuffle and so
8413 /// we encode the logic here for specific shuffle lowering routines to bail to
8414 /// when they exhaust the features avaible to more directly handle the shuffle.
8415 static SDValue splitAndLower256BitVectorShuffle(SDValue Op, SDValue V1,
8416                                                 SDValue V2,
8417                                                 const X86Subtarget *Subtarget,
8418                                                 SelectionDAG &DAG) {
8419   SDLoc DL(Op);
8420   MVT VT = Op.getSimpleValueType();
8421   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8422   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8423   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8424   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8425   ArrayRef<int> Mask = SVOp->getMask();
8426
8427   ArrayRef<int> LoMask = Mask.slice(0, Mask.size()/2);
8428   ArrayRef<int> HiMask = Mask.slice(Mask.size()/2);
8429
8430   int NumElements = VT.getVectorNumElements();
8431   int SplitNumElements = NumElements / 2;
8432   MVT ScalarVT = VT.getScalarType();
8433   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8434
8435   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8436                              DAG.getIntPtrConstant(0));
8437   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8438                              DAG.getIntPtrConstant(SplitNumElements));
8439   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8440                              DAG.getIntPtrConstant(0));
8441   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8442                              DAG.getIntPtrConstant(SplitNumElements));
8443
8444   // Now create two 4-way blends of these half-width vectors.
8445   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8446     SmallVector<int, 16> V1BlendMask, V2BlendMask, BlendMask;
8447     for (int i = 0; i < SplitNumElements; ++i) {
8448       int M = HalfMask[i];
8449       if (M >= NumElements) {
8450         V2BlendMask.push_back(M - NumElements);
8451         V1BlendMask.push_back(-1);
8452         BlendMask.push_back(SplitNumElements + i);
8453       } else if (M >= 0) {
8454         V2BlendMask.push_back(-1);
8455         V1BlendMask.push_back(M);
8456         BlendMask.push_back(i);
8457       } else {
8458         V2BlendMask.push_back(-1);
8459         V1BlendMask.push_back(-1);
8460         BlendMask.push_back(-1);
8461       }
8462     }
8463     SDValue V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8464     SDValue V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8465     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8466   };
8467   SDValue Lo = HalfBlend(LoMask);
8468   SDValue Hi = HalfBlend(HiMask);
8469   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8470 }
8471
8472 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
8473 ///
8474 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
8475 /// isn't available.
8476 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8477                                        const X86Subtarget *Subtarget,
8478                                        SelectionDAG &DAG) {
8479   SDLoc DL(Op);
8480   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8481   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8482   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8483   ArrayRef<int> Mask = SVOp->getMask();
8484   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8485
8486   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8487   // shuffles aren't a problem and FP and int have the same patterns.
8488
8489   // FIXME: We can handle these more cleverly than splitting for v4f64.
8490   if (isHalfCrossingShuffleMask(Mask))
8491     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8492
8493   if (isSingleInputShuffleMask(Mask)) {
8494     // Non-half-crossing single input shuffles can be lowerid with an
8495     // interleaved permutation.
8496     unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
8497                             ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
8498     return DAG.getNode(X86ISD::VPERMILP, DL, MVT::v4f64, V1,
8499                        DAG.getConstant(VPERMILPMask, MVT::i8));
8500   }
8501
8502   // X86 has dedicated unpack instructions that can handle specific blend
8503   // operations: UNPCKH and UNPCKL.
8504   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
8505     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
8506   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
8507     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
8508   // FIXME: It would be nice to find a way to get canonicalization to commute
8509   // these patterns.
8510   if (isShuffleEquivalent(Mask, 4, 0, 6, 2))
8511     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
8512   if (isShuffleEquivalent(Mask, 5, 1, 7, 3))
8513     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
8514
8515   // Check if the blend happens to exactly fit that of SHUFPD.
8516   if (Mask[0] < 4 && (Mask[1] == -1 || Mask[1] >= 4) &&
8517       Mask[2] < 4 && (Mask[3] == -1 || Mask[3] >= 4)) {
8518     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
8519                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
8520     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
8521                        DAG.getConstant(SHUFPDMask, MVT::i8));
8522   }
8523   if ((Mask[0] == -1 || Mask[0] >= 4) && Mask[1] < 4 &&
8524       (Mask[2] == -1 || Mask[2] >= 4) && Mask[3] < 4) {
8525     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
8526                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
8527     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
8528                        DAG.getConstant(SHUFPDMask, MVT::i8));
8529   }
8530
8531   // Shuffle the input elements into the desired positions in V1 and V2 and
8532   // blend them together.
8533   int V1Mask[] = {-1, -1, -1, -1};
8534   int V2Mask[] = {-1, -1, -1, -1};
8535   for (int i = 0; i < 4; ++i)
8536     if (Mask[i] >= 0 && Mask[i] < 4)
8537       V1Mask[i] = Mask[i];
8538     else if (Mask[i] >= 4)
8539       V2Mask[i] = Mask[i] - 4;
8540
8541   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, V1, DAG.getUNDEF(MVT::v4f64), V1Mask);
8542   V2 = DAG.getVectorShuffle(MVT::v4f64, DL, V2, DAG.getUNDEF(MVT::v4f64), V2Mask);
8543
8544   unsigned BlendMask = 0;
8545   for (int i = 0; i < 4; ++i)
8546     if (Mask[i] >= 4)
8547       BlendMask |= 1 << i;
8548
8549   return DAG.getNode(X86ISD::BLENDI, DL, MVT::v4f64, V1, V2,
8550                      DAG.getConstant(BlendMask, MVT::i8));
8551 }
8552
8553 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
8554 ///
8555 /// Largely delegates to common code when we have AVX2 and to the floating-point
8556 /// code when we only have AVX.
8557 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8558                                        const X86Subtarget *Subtarget,
8559                                        SelectionDAG &DAG) {
8560   SDLoc DL(Op);
8561   assert(Op.getSimpleValueType() == MVT::v4i64 && "Bad shuffle type!");
8562   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8563   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8564   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8565   ArrayRef<int> Mask = SVOp->getMask();
8566   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8567
8568   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8569   // shuffles aren't a problem and FP and int have the same patterns.
8570
8571   if (isHalfCrossingShuffleMask(Mask))
8572     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8573
8574   // AVX1 doesn't provide any facilities for v4i64 shuffles, bitcast and
8575   // delegate to floating point code.
8576   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V1);
8577   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V2);
8578   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i64,
8579                      lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG));
8580 }
8581
8582 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
8583 ///
8584 /// This routine either breaks down the specific type of a 256-bit x86 vector
8585 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
8586 /// together based on the available instructions.
8587 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8588                                         MVT VT, const X86Subtarget *Subtarget,
8589                                         SelectionDAG &DAG) {
8590   switch (VT.SimpleTy) {
8591   case MVT::v4f64:
8592     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8593   case MVT::v4i64:
8594     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8595   case MVT::v8i32:
8596   case MVT::v8f32:
8597   case MVT::v16i16:
8598   case MVT::v32i8:
8599     // Fall back to the basic pattern of extracting the high half and forming
8600     // a 4-way blend.
8601     // FIXME: Add targeted lowering for each type that can document rationale
8602     // for delegating to this when necessary.
8603     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8604
8605   default:
8606     llvm_unreachable("Not a valid 256-bit x86 vector type!");
8607   }
8608 }
8609
8610 /// \brief Tiny helper function to test whether a shuffle mask could be
8611 /// simplified by widening the elements being shuffled.
8612 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8613   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8614     if (Mask[i] % 2 != 0 || Mask[i] + 1 != Mask[i+1])
8615       return false;
8616
8617   return true;
8618 }
8619
8620 /// \brief Top-level lowering for x86 vector shuffles.
8621 ///
8622 /// This handles decomposition, canonicalization, and lowering of all x86
8623 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8624 /// above in helper routines. The canonicalization attempts to widen shuffles
8625 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8626 /// s.t. only one of the two inputs needs to be tested, etc.
8627 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8628                                   SelectionDAG &DAG) {
8629   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8630   ArrayRef<int> Mask = SVOp->getMask();
8631   SDValue V1 = Op.getOperand(0);
8632   SDValue V2 = Op.getOperand(1);
8633   MVT VT = Op.getSimpleValueType();
8634   int NumElements = VT.getVectorNumElements();
8635   SDLoc dl(Op);
8636
8637   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8638
8639   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8640   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8641   if (V1IsUndef && V2IsUndef)
8642     return DAG.getUNDEF(VT);
8643
8644   // When we create a shuffle node we put the UNDEF node to second operand,
8645   // but in some cases the first operand may be transformed to UNDEF.
8646   // In this case we should just commute the node.
8647   if (V1IsUndef)
8648     return DAG.getCommutedVectorShuffle(*SVOp);
8649
8650   // Check for non-undef masks pointing at an undef vector and make the masks
8651   // undef as well. This makes it easier to match the shuffle based solely on
8652   // the mask.
8653   if (V2IsUndef)
8654     for (int M : Mask)
8655       if (M >= NumElements) {
8656         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8657         for (int &M : NewMask)
8658           if (M >= NumElements)
8659             M = -1;
8660         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8661       }
8662
8663   // For integer vector shuffles, try to collapse them into a shuffle of fewer
8664   // lanes but wider integers. We cap this to not form integers larger than i64
8665   // but it might be interesting to form i128 integers to handle flipping the
8666   // low and high halves of AVX 256-bit vectors.
8667   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8668       canWidenShuffleElements(Mask)) {
8669     SmallVector<int, 8> NewMask;
8670     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8671       NewMask.push_back(Mask[i] / 2);
8672     MVT NewVT =
8673         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8674                          VT.getVectorNumElements() / 2);
8675     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8676     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8677     return DAG.getNode(ISD::BITCAST, dl, VT,
8678                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8679   }
8680
8681   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8682   for (int M : SVOp->getMask())
8683     if (M < 0)
8684       ++NumUndefElements;
8685     else if (M < NumElements)
8686       ++NumV1Elements;
8687     else
8688       ++NumV2Elements;
8689
8690   // Commute the shuffle as needed such that more elements come from V1 than
8691   // V2. This allows us to match the shuffle pattern strictly on how many
8692   // elements come from V1 without handling the symmetric cases.
8693   if (NumV2Elements > NumV1Elements)
8694     return DAG.getCommutedVectorShuffle(*SVOp);
8695
8696   // When the number of V1 and V2 elements are the same, try to minimize the
8697   // number of uses of V2 in the low half of the vector.
8698   if (NumV1Elements == NumV2Elements) {
8699     int LowV1Elements = 0, LowV2Elements = 0;
8700     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8701       if (M >= NumElements)
8702         ++LowV2Elements;
8703       else if (M >= 0)
8704         ++LowV1Elements;
8705     if (LowV2Elements > LowV1Elements)
8706       return DAG.getCommutedVectorShuffle(*SVOp);
8707   }
8708
8709   // For each vector width, delegate to a specialized lowering routine.
8710   if (VT.getSizeInBits() == 128)
8711     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8712
8713   if (VT.getSizeInBits() == 256)
8714     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8715
8716   llvm_unreachable("Unimplemented!");
8717 }
8718
8719
8720 //===----------------------------------------------------------------------===//
8721 // Legacy vector shuffle lowering
8722 //
8723 // This code is the legacy code handling vector shuffles until the above
8724 // replaces its functionality and performance.
8725 //===----------------------------------------------------------------------===//
8726
8727 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8728                         bool hasInt256, unsigned *MaskOut = nullptr) {
8729   MVT EltVT = VT.getVectorElementType();
8730
8731   // There is no blend with immediate in AVX-512.
8732   if (VT.is512BitVector())
8733     return false;
8734
8735   if (!hasSSE41 || EltVT == MVT::i8)
8736     return false;
8737   if (!hasInt256 && VT == MVT::v16i16)
8738     return false;
8739
8740   unsigned MaskValue = 0;
8741   unsigned NumElems = VT.getVectorNumElements();
8742   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8743   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8744   unsigned NumElemsInLane = NumElems / NumLanes;
8745
8746   // Blend for v16i16 should be symetric for the both lanes.
8747   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8748
8749     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8750     int EltIdx = MaskVals[i];
8751
8752     if ((EltIdx < 0 || EltIdx == (int)i) &&
8753         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8754       continue;
8755
8756     if (((unsigned)EltIdx == (i + NumElems)) &&
8757         (SndLaneEltIdx < 0 ||
8758          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8759       MaskValue |= (1 << i);
8760     else
8761       return false;
8762   }
8763
8764   if (MaskOut)
8765     *MaskOut = MaskValue;
8766   return true;
8767 }
8768
8769 // Try to lower a shuffle node into a simple blend instruction.
8770 // This function assumes isBlendMask returns true for this
8771 // SuffleVectorSDNode
8772 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8773                                           unsigned MaskValue,
8774                                           const X86Subtarget *Subtarget,
8775                                           SelectionDAG &DAG) {
8776   MVT VT = SVOp->getSimpleValueType(0);
8777   MVT EltVT = VT.getVectorElementType();
8778   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8779                      Subtarget->hasInt256() && "Trying to lower a "
8780                                                "VECTOR_SHUFFLE to a Blend but "
8781                                                "with the wrong mask"));
8782   SDValue V1 = SVOp->getOperand(0);
8783   SDValue V2 = SVOp->getOperand(1);
8784   SDLoc dl(SVOp);
8785   unsigned NumElems = VT.getVectorNumElements();
8786
8787   // Convert i32 vectors to floating point if it is not AVX2.
8788   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8789   MVT BlendVT = VT;
8790   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8791     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8792                                NumElems);
8793     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8794     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8795   }
8796
8797   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8798                             DAG.getConstant(MaskValue, MVT::i32));
8799   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8800 }
8801
8802 /// In vector type \p VT, return true if the element at index \p InputIdx
8803 /// falls on a different 128-bit lane than \p OutputIdx.
8804 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8805                                      unsigned OutputIdx) {
8806   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8807   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8808 }
8809
8810 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8811 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8812 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8813 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8814 /// zero.
8815 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8816                          SelectionDAG &DAG) {
8817   MVT VT = V1.getSimpleValueType();
8818   assert(VT.is128BitVector() || VT.is256BitVector());
8819
8820   MVT EltVT = VT.getVectorElementType();
8821   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8822   unsigned NumElts = VT.getVectorNumElements();
8823
8824   SmallVector<SDValue, 32> PshufbMask;
8825   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8826     int InputIdx = MaskVals[OutputIdx];
8827     unsigned InputByteIdx;
8828
8829     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8830       InputByteIdx = 0x80;
8831     else {
8832       // Cross lane is not allowed.
8833       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8834         return SDValue();
8835       InputByteIdx = InputIdx * EltSizeInBytes;
8836       // Index is an byte offset within the 128-bit lane.
8837       InputByteIdx &= 0xf;
8838     }
8839
8840     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8841       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8842       if (InputByteIdx != 0x80)
8843         ++InputByteIdx;
8844     }
8845   }
8846
8847   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8848   if (ShufVT != VT)
8849     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8850   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8851                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8852 }
8853
8854 // v8i16 shuffles - Prefer shuffles in the following order:
8855 // 1. [all]   pshuflw, pshufhw, optional move
8856 // 2. [ssse3] 1 x pshufb
8857 // 3. [ssse3] 2 x pshufb + 1 x por
8858 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8859 static SDValue
8860 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8861                          SelectionDAG &DAG) {
8862   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8863   SDValue V1 = SVOp->getOperand(0);
8864   SDValue V2 = SVOp->getOperand(1);
8865   SDLoc dl(SVOp);
8866   SmallVector<int, 8> MaskVals;
8867
8868   // Determine if more than 1 of the words in each of the low and high quadwords
8869   // of the result come from the same quadword of one of the two inputs.  Undef
8870   // mask values count as coming from any quadword, for better codegen.
8871   //
8872   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8873   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8874   unsigned LoQuad[] = { 0, 0, 0, 0 };
8875   unsigned HiQuad[] = { 0, 0, 0, 0 };
8876   // Indices of quads used.
8877   std::bitset<4> InputQuads;
8878   for (unsigned i = 0; i < 8; ++i) {
8879     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8880     int EltIdx = SVOp->getMaskElt(i);
8881     MaskVals.push_back(EltIdx);
8882     if (EltIdx < 0) {
8883       ++Quad[0];
8884       ++Quad[1];
8885       ++Quad[2];
8886       ++Quad[3];
8887       continue;
8888     }
8889     ++Quad[EltIdx / 4];
8890     InputQuads.set(EltIdx / 4);
8891   }
8892
8893   int BestLoQuad = -1;
8894   unsigned MaxQuad = 1;
8895   for (unsigned i = 0; i < 4; ++i) {
8896     if (LoQuad[i] > MaxQuad) {
8897       BestLoQuad = i;
8898       MaxQuad = LoQuad[i];
8899     }
8900   }
8901
8902   int BestHiQuad = -1;
8903   MaxQuad = 1;
8904   for (unsigned i = 0; i < 4; ++i) {
8905     if (HiQuad[i] > MaxQuad) {
8906       BestHiQuad = i;
8907       MaxQuad = HiQuad[i];
8908     }
8909   }
8910
8911   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8912   // of the two input vectors, shuffle them into one input vector so only a
8913   // single pshufb instruction is necessary. If there are more than 2 input
8914   // quads, disable the next transformation since it does not help SSSE3.
8915   bool V1Used = InputQuads[0] || InputQuads[1];
8916   bool V2Used = InputQuads[2] || InputQuads[3];
8917   if (Subtarget->hasSSSE3()) {
8918     if (InputQuads.count() == 2 && V1Used && V2Used) {
8919       BestLoQuad = InputQuads[0] ? 0 : 1;
8920       BestHiQuad = InputQuads[2] ? 2 : 3;
8921     }
8922     if (InputQuads.count() > 2) {
8923       BestLoQuad = -1;
8924       BestHiQuad = -1;
8925     }
8926   }
8927
8928   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8929   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8930   // words from all 4 input quadwords.
8931   SDValue NewV;
8932   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8933     int MaskV[] = {
8934       BestLoQuad < 0 ? 0 : BestLoQuad,
8935       BestHiQuad < 0 ? 1 : BestHiQuad
8936     };
8937     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8938                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8939                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8940     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8941
8942     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8943     // source words for the shuffle, to aid later transformations.
8944     bool AllWordsInNewV = true;
8945     bool InOrder[2] = { true, true };
8946     for (unsigned i = 0; i != 8; ++i) {
8947       int idx = MaskVals[i];
8948       if (idx != (int)i)
8949         InOrder[i/4] = false;
8950       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8951         continue;
8952       AllWordsInNewV = false;
8953       break;
8954     }
8955
8956     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8957     if (AllWordsInNewV) {
8958       for (int i = 0; i != 8; ++i) {
8959         int idx = MaskVals[i];
8960         if (idx < 0)
8961           continue;
8962         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8963         if ((idx != i) && idx < 4)
8964           pshufhw = false;
8965         if ((idx != i) && idx > 3)
8966           pshuflw = false;
8967       }
8968       V1 = NewV;
8969       V2Used = false;
8970       BestLoQuad = 0;
8971       BestHiQuad = 1;
8972     }
8973
8974     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8975     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8976     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8977       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8978       unsigned TargetMask = 0;
8979       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8980                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8981       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8982       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8983                              getShufflePSHUFLWImmediate(SVOp);
8984       V1 = NewV.getOperand(0);
8985       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8986     }
8987   }
8988
8989   // Promote splats to a larger type which usually leads to more efficient code.
8990   // FIXME: Is this true if pshufb is available?
8991   if (SVOp->isSplat())
8992     return PromoteSplat(SVOp, DAG);
8993
8994   // If we have SSSE3, and all words of the result are from 1 input vector,
8995   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8996   // is present, fall back to case 4.
8997   if (Subtarget->hasSSSE3()) {
8998     SmallVector<SDValue,16> pshufbMask;
8999
9000     // If we have elements from both input vectors, set the high bit of the
9001     // shuffle mask element to zero out elements that come from V2 in the V1
9002     // mask, and elements that come from V1 in the V2 mask, so that the two
9003     // results can be OR'd together.
9004     bool TwoInputs = V1Used && V2Used;
9005     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
9006     if (!TwoInputs)
9007       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9008
9009     // Calculate the shuffle mask for the second input, shuffle it, and
9010     // OR it with the first shuffled input.
9011     CommuteVectorShuffleMask(MaskVals, 8);
9012     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
9013     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9014     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9015   }
9016
9017   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
9018   // and update MaskVals with new element order.
9019   std::bitset<8> InOrder;
9020   if (BestLoQuad >= 0) {
9021     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
9022     for (int i = 0; i != 4; ++i) {
9023       int idx = MaskVals[i];
9024       if (idx < 0) {
9025         InOrder.set(i);
9026       } else if ((idx / 4) == BestLoQuad) {
9027         MaskV[i] = idx & 3;
9028         InOrder.set(i);
9029       }
9030     }
9031     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9032                                 &MaskV[0]);
9033
9034     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9035       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9036       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
9037                                   NewV.getOperand(0),
9038                                   getShufflePSHUFLWImmediate(SVOp), DAG);
9039     }
9040   }
9041
9042   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
9043   // and update MaskVals with the new element order.
9044   if (BestHiQuad >= 0) {
9045     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
9046     for (unsigned i = 4; i != 8; ++i) {
9047       int idx = MaskVals[i];
9048       if (idx < 0) {
9049         InOrder.set(i);
9050       } else if ((idx / 4) == BestHiQuad) {
9051         MaskV[i] = (idx & 3) + 4;
9052         InOrder.set(i);
9053       }
9054     }
9055     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9056                                 &MaskV[0]);
9057
9058     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9059       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9060       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
9061                                   NewV.getOperand(0),
9062                                   getShufflePSHUFHWImmediate(SVOp), DAG);
9063     }
9064   }
9065
9066   // In case BestHi & BestLo were both -1, which means each quadword has a word
9067   // from each of the four input quadwords, calculate the InOrder bitvector now
9068   // before falling through to the insert/extract cleanup.
9069   if (BestLoQuad == -1 && BestHiQuad == -1) {
9070     NewV = V1;
9071     for (int i = 0; i != 8; ++i)
9072       if (MaskVals[i] < 0 || MaskVals[i] == i)
9073         InOrder.set(i);
9074   }
9075
9076   // The other elements are put in the right place using pextrw and pinsrw.
9077   for (unsigned i = 0; i != 8; ++i) {
9078     if (InOrder[i])
9079       continue;
9080     int EltIdx = MaskVals[i];
9081     if (EltIdx < 0)
9082       continue;
9083     SDValue ExtOp = (EltIdx < 8) ?
9084       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
9085                   DAG.getIntPtrConstant(EltIdx)) :
9086       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
9087                   DAG.getIntPtrConstant(EltIdx - 8));
9088     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
9089                        DAG.getIntPtrConstant(i));
9090   }
9091   return NewV;
9092 }
9093
9094 /// \brief v16i16 shuffles
9095 ///
9096 /// FIXME: We only support generation of a single pshufb currently.  We can
9097 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
9098 /// well (e.g 2 x pshufb + 1 x por).
9099 static SDValue
9100 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
9101   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9102   SDValue V1 = SVOp->getOperand(0);
9103   SDValue V2 = SVOp->getOperand(1);
9104   SDLoc dl(SVOp);
9105
9106   if (V2.getOpcode() != ISD::UNDEF)
9107     return SDValue();
9108
9109   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9110   return getPSHUFB(MaskVals, V1, dl, DAG);
9111 }
9112
9113 // v16i8 shuffles - Prefer shuffles in the following order:
9114 // 1. [ssse3] 1 x pshufb
9115 // 2. [ssse3] 2 x pshufb + 1 x por
9116 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
9117 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
9118                                         const X86Subtarget* Subtarget,
9119                                         SelectionDAG &DAG) {
9120   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9121   SDValue V1 = SVOp->getOperand(0);
9122   SDValue V2 = SVOp->getOperand(1);
9123   SDLoc dl(SVOp);
9124   ArrayRef<int> MaskVals = SVOp->getMask();
9125
9126   // Promote splats to a larger type which usually leads to more efficient code.
9127   // FIXME: Is this true if pshufb is available?
9128   if (SVOp->isSplat())
9129     return PromoteSplat(SVOp, DAG);
9130
9131   // If we have SSSE3, case 1 is generated when all result bytes come from
9132   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
9133   // present, fall back to case 3.
9134
9135   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
9136   if (Subtarget->hasSSSE3()) {
9137     SmallVector<SDValue,16> pshufbMask;
9138
9139     // If all result elements are from one input vector, then only translate
9140     // undef mask values to 0x80 (zero out result) in the pshufb mask.
9141     //
9142     // Otherwise, we have elements from both input vectors, and must zero out
9143     // elements that come from V2 in the first mask, and V1 in the second mask
9144     // so that we can OR them together.
9145     for (unsigned i = 0; i != 16; ++i) {
9146       int EltIdx = MaskVals[i];
9147       if (EltIdx < 0 || EltIdx >= 16)
9148         EltIdx = 0x80;
9149       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9150     }
9151     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
9152                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9153                                  MVT::v16i8, pshufbMask));
9154
9155     // As PSHUFB will zero elements with negative indices, it's safe to ignore
9156     // the 2nd operand if it's undefined or zero.
9157     if (V2.getOpcode() == ISD::UNDEF ||
9158         ISD::isBuildVectorAllZeros(V2.getNode()))
9159       return V1;
9160
9161     // Calculate the shuffle mask for the second input, shuffle it, and
9162     // OR it with the first shuffled input.
9163     pshufbMask.clear();
9164     for (unsigned i = 0; i != 16; ++i) {
9165       int EltIdx = MaskVals[i];
9166       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
9167       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9168     }
9169     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
9170                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9171                                  MVT::v16i8, pshufbMask));
9172     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9173   }
9174
9175   // No SSSE3 - Calculate in place words and then fix all out of place words
9176   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
9177   // the 16 different words that comprise the two doublequadword input vectors.
9178   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9179   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9180   SDValue NewV = V1;
9181   for (int i = 0; i != 8; ++i) {
9182     int Elt0 = MaskVals[i*2];
9183     int Elt1 = MaskVals[i*2+1];
9184
9185     // This word of the result is all undef, skip it.
9186     if (Elt0 < 0 && Elt1 < 0)
9187       continue;
9188
9189     // This word of the result is already in the correct place, skip it.
9190     if ((Elt0 == i*2) && (Elt1 == i*2+1))
9191       continue;
9192
9193     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
9194     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
9195     SDValue InsElt;
9196
9197     // If Elt0 and Elt1 are defined, are consecutive, and can be load
9198     // using a single extract together, load it and store it.
9199     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
9200       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9201                            DAG.getIntPtrConstant(Elt1 / 2));
9202       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9203                         DAG.getIntPtrConstant(i));
9204       continue;
9205     }
9206
9207     // If Elt1 is defined, extract it from the appropriate source.  If the
9208     // source byte is not also odd, shift the extracted word left 8 bits
9209     // otherwise clear the bottom 8 bits if we need to do an or.
9210     if (Elt1 >= 0) {
9211       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9212                            DAG.getIntPtrConstant(Elt1 / 2));
9213       if ((Elt1 & 1) == 0)
9214         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
9215                              DAG.getConstant(8,
9216                                   TLI.getShiftAmountTy(InsElt.getValueType())));
9217       else if (Elt0 >= 0)
9218         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
9219                              DAG.getConstant(0xFF00, MVT::i16));
9220     }
9221     // If Elt0 is defined, extract it from the appropriate source.  If the
9222     // source byte is not also even, shift the extracted word right 8 bits. If
9223     // Elt1 was also defined, OR the extracted values together before
9224     // inserting them in the result.
9225     if (Elt0 >= 0) {
9226       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
9227                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
9228       if ((Elt0 & 1) != 0)
9229         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
9230                               DAG.getConstant(8,
9231                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
9232       else if (Elt1 >= 0)
9233         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
9234                              DAG.getConstant(0x00FF, MVT::i16));
9235       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
9236                          : InsElt0;
9237     }
9238     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9239                        DAG.getIntPtrConstant(i));
9240   }
9241   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
9242 }
9243
9244 // v32i8 shuffles - Translate to VPSHUFB if possible.
9245 static
9246 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
9247                                  const X86Subtarget *Subtarget,
9248                                  SelectionDAG &DAG) {
9249   MVT VT = SVOp->getSimpleValueType(0);
9250   SDValue V1 = SVOp->getOperand(0);
9251   SDValue V2 = SVOp->getOperand(1);
9252   SDLoc dl(SVOp);
9253   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9254
9255   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9256   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
9257   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
9258
9259   // VPSHUFB may be generated if
9260   // (1) one of input vector is undefined or zeroinitializer.
9261   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
9262   // And (2) the mask indexes don't cross the 128-bit lane.
9263   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
9264       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
9265     return SDValue();
9266
9267   if (V1IsAllZero && !V2IsAllZero) {
9268     CommuteVectorShuffleMask(MaskVals, 32);
9269     V1 = V2;
9270   }
9271   return getPSHUFB(MaskVals, V1, dl, DAG);
9272 }
9273
9274 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
9275 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
9276 /// done when every pair / quad of shuffle mask elements point to elements in
9277 /// the right sequence. e.g.
9278 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
9279 static
9280 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
9281                                  SelectionDAG &DAG) {
9282   MVT VT = SVOp->getSimpleValueType(0);
9283   SDLoc dl(SVOp);
9284   unsigned NumElems = VT.getVectorNumElements();
9285   MVT NewVT;
9286   unsigned Scale;
9287   switch (VT.SimpleTy) {
9288   default: llvm_unreachable("Unexpected!");
9289   case MVT::v2i64:
9290   case MVT::v2f64:
9291            return SDValue(SVOp, 0);
9292   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
9293   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
9294   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
9295   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
9296   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
9297   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
9298   }
9299
9300   SmallVector<int, 8> MaskVec;
9301   for (unsigned i = 0; i != NumElems; i += Scale) {
9302     int StartIdx = -1;
9303     for (unsigned j = 0; j != Scale; ++j) {
9304       int EltIdx = SVOp->getMaskElt(i+j);
9305       if (EltIdx < 0)
9306         continue;
9307       if (StartIdx < 0)
9308         StartIdx = (EltIdx / Scale);
9309       if (EltIdx != (int)(StartIdx*Scale + j))
9310         return SDValue();
9311     }
9312     MaskVec.push_back(StartIdx);
9313   }
9314
9315   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
9316   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
9317   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
9318 }
9319
9320 /// getVZextMovL - Return a zero-extending vector move low node.
9321 ///
9322 static SDValue getVZextMovL(MVT VT, MVT OpVT,
9323                             SDValue SrcOp, SelectionDAG &DAG,
9324                             const X86Subtarget *Subtarget, SDLoc dl) {
9325   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
9326     LoadSDNode *LD = nullptr;
9327     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
9328       LD = dyn_cast<LoadSDNode>(SrcOp);
9329     if (!LD) {
9330       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
9331       // instead.
9332       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
9333       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
9334           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9335           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
9336           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
9337         // PR2108
9338         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
9339         return DAG.getNode(ISD::BITCAST, dl, VT,
9340                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9341                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9342                                                    OpVT,
9343                                                    SrcOp.getOperand(0)
9344                                                           .getOperand(0))));
9345       }
9346     }
9347   }
9348
9349   return DAG.getNode(ISD::BITCAST, dl, VT,
9350                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9351                                  DAG.getNode(ISD::BITCAST, dl,
9352                                              OpVT, SrcOp)));
9353 }
9354
9355 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
9356 /// which could not be matched by any known target speficic shuffle
9357 static SDValue
9358 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9359
9360   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
9361   if (NewOp.getNode())
9362     return NewOp;
9363
9364   MVT VT = SVOp->getSimpleValueType(0);
9365
9366   unsigned NumElems = VT.getVectorNumElements();
9367   unsigned NumLaneElems = NumElems / 2;
9368
9369   SDLoc dl(SVOp);
9370   MVT EltVT = VT.getVectorElementType();
9371   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
9372   SDValue Output[2];
9373
9374   SmallVector<int, 16> Mask;
9375   for (unsigned l = 0; l < 2; ++l) {
9376     // Build a shuffle mask for the output, discovering on the fly which
9377     // input vectors to use as shuffle operands (recorded in InputUsed).
9378     // If building a suitable shuffle vector proves too hard, then bail
9379     // out with UseBuildVector set.
9380     bool UseBuildVector = false;
9381     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9382     unsigned LaneStart = l * NumLaneElems;
9383     for (unsigned i = 0; i != NumLaneElems; ++i) {
9384       // The mask element.  This indexes into the input.
9385       int Idx = SVOp->getMaskElt(i+LaneStart);
9386       if (Idx < 0) {
9387         // the mask element does not index into any input vector.
9388         Mask.push_back(-1);
9389         continue;
9390       }
9391
9392       // The input vector this mask element indexes into.
9393       int Input = Idx / NumLaneElems;
9394
9395       // Turn the index into an offset from the start of the input vector.
9396       Idx -= Input * NumLaneElems;
9397
9398       // Find or create a shuffle vector operand to hold this input.
9399       unsigned OpNo;
9400       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9401         if (InputUsed[OpNo] == Input)
9402           // This input vector is already an operand.
9403           break;
9404         if (InputUsed[OpNo] < 0) {
9405           // Create a new operand for this input vector.
9406           InputUsed[OpNo] = Input;
9407           break;
9408         }
9409       }
9410
9411       if (OpNo >= array_lengthof(InputUsed)) {
9412         // More than two input vectors used!  Give up on trying to create a
9413         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
9414         UseBuildVector = true;
9415         break;
9416       }
9417
9418       // Add the mask index for the new shuffle vector.
9419       Mask.push_back(Idx + OpNo * NumLaneElems);
9420     }
9421
9422     if (UseBuildVector) {
9423       SmallVector<SDValue, 16> SVOps;
9424       for (unsigned i = 0; i != NumLaneElems; ++i) {
9425         // The mask element.  This indexes into the input.
9426         int Idx = SVOp->getMaskElt(i+LaneStart);
9427         if (Idx < 0) {
9428           SVOps.push_back(DAG.getUNDEF(EltVT));
9429           continue;
9430         }
9431
9432         // The input vector this mask element indexes into.
9433         int Input = Idx / NumElems;
9434
9435         // Turn the index into an offset from the start of the input vector.
9436         Idx -= Input * NumElems;
9437
9438         // Extract the vector element by hand.
9439         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9440                                     SVOp->getOperand(Input),
9441                                     DAG.getIntPtrConstant(Idx)));
9442       }
9443
9444       // Construct the output using a BUILD_VECTOR.
9445       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9446     } else if (InputUsed[0] < 0) {
9447       // No input vectors were used! The result is undefined.
9448       Output[l] = DAG.getUNDEF(NVT);
9449     } else {
9450       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9451                                         (InputUsed[0] % 2) * NumLaneElems,
9452                                         DAG, dl);
9453       // If only one input was used, use an undefined vector for the other.
9454       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9455         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9456                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9457       // At least one input vector was used. Create a new shuffle vector.
9458       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9459     }
9460
9461     Mask.clear();
9462   }
9463
9464   // Concatenate the result back
9465   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9466 }
9467
9468 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9469 /// 4 elements, and match them with several different shuffle types.
9470 static SDValue
9471 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9472   SDValue V1 = SVOp->getOperand(0);
9473   SDValue V2 = SVOp->getOperand(1);
9474   SDLoc dl(SVOp);
9475   MVT VT = SVOp->getSimpleValueType(0);
9476
9477   assert(VT.is128BitVector() && "Unsupported vector size");
9478
9479   std::pair<int, int> Locs[4];
9480   int Mask1[] = { -1, -1, -1, -1 };
9481   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9482
9483   unsigned NumHi = 0;
9484   unsigned NumLo = 0;
9485   for (unsigned i = 0; i != 4; ++i) {
9486     int Idx = PermMask[i];
9487     if (Idx < 0) {
9488       Locs[i] = std::make_pair(-1, -1);
9489     } else {
9490       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9491       if (Idx < 4) {
9492         Locs[i] = std::make_pair(0, NumLo);
9493         Mask1[NumLo] = Idx;
9494         NumLo++;
9495       } else {
9496         Locs[i] = std::make_pair(1, NumHi);
9497         if (2+NumHi < 4)
9498           Mask1[2+NumHi] = Idx;
9499         NumHi++;
9500       }
9501     }
9502   }
9503
9504   if (NumLo <= 2 && NumHi <= 2) {
9505     // If no more than two elements come from either vector. This can be
9506     // implemented with two shuffles. First shuffle gather the elements.
9507     // The second shuffle, which takes the first shuffle as both of its
9508     // vector operands, put the elements into the right order.
9509     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9510
9511     int Mask2[] = { -1, -1, -1, -1 };
9512
9513     for (unsigned i = 0; i != 4; ++i)
9514       if (Locs[i].first != -1) {
9515         unsigned Idx = (i < 2) ? 0 : 4;
9516         Idx += Locs[i].first * 2 + Locs[i].second;
9517         Mask2[i] = Idx;
9518       }
9519
9520     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9521   }
9522
9523   if (NumLo == 3 || NumHi == 3) {
9524     // Otherwise, we must have three elements from one vector, call it X, and
9525     // one element from the other, call it Y.  First, use a shufps to build an
9526     // intermediate vector with the one element from Y and the element from X
9527     // that will be in the same half in the final destination (the indexes don't
9528     // matter). Then, use a shufps to build the final vector, taking the half
9529     // containing the element from Y from the intermediate, and the other half
9530     // from X.
9531     if (NumHi == 3) {
9532       // Normalize it so the 3 elements come from V1.
9533       CommuteVectorShuffleMask(PermMask, 4);
9534       std::swap(V1, V2);
9535     }
9536
9537     // Find the element from V2.
9538     unsigned HiIndex;
9539     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9540       int Val = PermMask[HiIndex];
9541       if (Val < 0)
9542         continue;
9543       if (Val >= 4)
9544         break;
9545     }
9546
9547     Mask1[0] = PermMask[HiIndex];
9548     Mask1[1] = -1;
9549     Mask1[2] = PermMask[HiIndex^1];
9550     Mask1[3] = -1;
9551     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9552
9553     if (HiIndex >= 2) {
9554       Mask1[0] = PermMask[0];
9555       Mask1[1] = PermMask[1];
9556       Mask1[2] = HiIndex & 1 ? 6 : 4;
9557       Mask1[3] = HiIndex & 1 ? 4 : 6;
9558       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9559     }
9560
9561     Mask1[0] = HiIndex & 1 ? 2 : 0;
9562     Mask1[1] = HiIndex & 1 ? 0 : 2;
9563     Mask1[2] = PermMask[2];
9564     Mask1[3] = PermMask[3];
9565     if (Mask1[2] >= 0)
9566       Mask1[2] += 4;
9567     if (Mask1[3] >= 0)
9568       Mask1[3] += 4;
9569     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9570   }
9571
9572   // Break it into (shuffle shuffle_hi, shuffle_lo).
9573   int LoMask[] = { -1, -1, -1, -1 };
9574   int HiMask[] = { -1, -1, -1, -1 };
9575
9576   int *MaskPtr = LoMask;
9577   unsigned MaskIdx = 0;
9578   unsigned LoIdx = 0;
9579   unsigned HiIdx = 2;
9580   for (unsigned i = 0; i != 4; ++i) {
9581     if (i == 2) {
9582       MaskPtr = HiMask;
9583       MaskIdx = 1;
9584       LoIdx = 0;
9585       HiIdx = 2;
9586     }
9587     int Idx = PermMask[i];
9588     if (Idx < 0) {
9589       Locs[i] = std::make_pair(-1, -1);
9590     } else if (Idx < 4) {
9591       Locs[i] = std::make_pair(MaskIdx, LoIdx);
9592       MaskPtr[LoIdx] = Idx;
9593       LoIdx++;
9594     } else {
9595       Locs[i] = std::make_pair(MaskIdx, HiIdx);
9596       MaskPtr[HiIdx] = Idx;
9597       HiIdx++;
9598     }
9599   }
9600
9601   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9602   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9603   int MaskOps[] = { -1, -1, -1, -1 };
9604   for (unsigned i = 0; i != 4; ++i)
9605     if (Locs[i].first != -1)
9606       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9607   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9608 }
9609
9610 static bool MayFoldVectorLoad(SDValue V) {
9611   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9612     V = V.getOperand(0);
9613
9614   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9615     V = V.getOperand(0);
9616   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9617       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9618     // BUILD_VECTOR (load), undef
9619     V = V.getOperand(0);
9620
9621   return MayFoldLoad(V);
9622 }
9623
9624 static
9625 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9626   MVT VT = Op.getSimpleValueType();
9627
9628   // Canonizalize to v2f64.
9629   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9630   return DAG.getNode(ISD::BITCAST, dl, VT,
9631                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9632                                           V1, DAG));
9633 }
9634
9635 static
9636 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9637                         bool HasSSE2) {
9638   SDValue V1 = Op.getOperand(0);
9639   SDValue V2 = Op.getOperand(1);
9640   MVT VT = Op.getSimpleValueType();
9641
9642   assert(VT != MVT::v2i64 && "unsupported shuffle type");
9643
9644   if (HasSSE2 && VT == MVT::v2f64)
9645     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9646
9647   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9648   return DAG.getNode(ISD::BITCAST, dl, VT,
9649                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9650                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9651                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9652 }
9653
9654 static
9655 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9656   SDValue V1 = Op.getOperand(0);
9657   SDValue V2 = Op.getOperand(1);
9658   MVT VT = Op.getSimpleValueType();
9659
9660   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9661          "unsupported shuffle type");
9662
9663   if (V2.getOpcode() == ISD::UNDEF)
9664     V2 = V1;
9665
9666   // v4i32 or v4f32
9667   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9668 }
9669
9670 static
9671 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9672   SDValue V1 = Op.getOperand(0);
9673   SDValue V2 = Op.getOperand(1);
9674   MVT VT = Op.getSimpleValueType();
9675   unsigned NumElems = VT.getVectorNumElements();
9676
9677   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9678   // operand of these instructions is only memory, so check if there's a
9679   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9680   // same masks.
9681   bool CanFoldLoad = false;
9682
9683   // Trivial case, when V2 comes from a load.
9684   if (MayFoldVectorLoad(V2))
9685     CanFoldLoad = true;
9686
9687   // When V1 is a load, it can be folded later into a store in isel, example:
9688   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9689   //    turns into:
9690   //  (MOVLPSmr addr:$src1, VR128:$src2)
9691   // So, recognize this potential and also use MOVLPS or MOVLPD
9692   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9693     CanFoldLoad = true;
9694
9695   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9696   if (CanFoldLoad) {
9697     if (HasSSE2 && NumElems == 2)
9698       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9699
9700     if (NumElems == 4)
9701       // If we don't care about the second element, proceed to use movss.
9702       if (SVOp->getMaskElt(1) != -1)
9703         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9704   }
9705
9706   // movl and movlp will both match v2i64, but v2i64 is never matched by
9707   // movl earlier because we make it strict to avoid messing with the movlp load
9708   // folding logic (see the code above getMOVLP call). Match it here then,
9709   // this is horrible, but will stay like this until we move all shuffle
9710   // matching to x86 specific nodes. Note that for the 1st condition all
9711   // types are matched with movsd.
9712   if (HasSSE2) {
9713     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9714     // as to remove this logic from here, as much as possible
9715     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9716       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9717     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9718   }
9719
9720   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9721
9722   // Invert the operand order and use SHUFPS to match it.
9723   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9724                               getShuffleSHUFImmediate(SVOp), DAG);
9725 }
9726
9727 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9728                                          SelectionDAG &DAG) {
9729   SDLoc dl(Load);
9730   MVT VT = Load->getSimpleValueType(0);
9731   MVT EVT = VT.getVectorElementType();
9732   SDValue Addr = Load->getOperand(1);
9733   SDValue NewAddr = DAG.getNode(
9734       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9735       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9736
9737   SDValue NewLoad =
9738       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9739                   DAG.getMachineFunction().getMachineMemOperand(
9740                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9741   return NewLoad;
9742 }
9743
9744 // It is only safe to call this function if isINSERTPSMask is true for
9745 // this shufflevector mask.
9746 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9747                            SelectionDAG &DAG) {
9748   // Generate an insertps instruction when inserting an f32 from memory onto a
9749   // v4f32 or when copying a member from one v4f32 to another.
9750   // We also use it for transferring i32 from one register to another,
9751   // since it simply copies the same bits.
9752   // If we're transferring an i32 from memory to a specific element in a
9753   // register, we output a generic DAG that will match the PINSRD
9754   // instruction.
9755   MVT VT = SVOp->getSimpleValueType(0);
9756   MVT EVT = VT.getVectorElementType();
9757   SDValue V1 = SVOp->getOperand(0);
9758   SDValue V2 = SVOp->getOperand(1);
9759   auto Mask = SVOp->getMask();
9760   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9761          "unsupported vector type for insertps/pinsrd");
9762
9763   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9764   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9765   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9766
9767   SDValue From;
9768   SDValue To;
9769   unsigned DestIndex;
9770   if (FromV1 == 1) {
9771     From = V1;
9772     To = V2;
9773     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9774                 Mask.begin();
9775
9776     // If we have 1 element from each vector, we have to check if we're
9777     // changing V1's element's place. If so, we're done. Otherwise, we
9778     // should assume we're changing V2's element's place and behave
9779     // accordingly.
9780     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9781     assert(DestIndex <= INT32_MAX && "truncated destination index");
9782     if (FromV1 == FromV2 &&
9783         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9784       From = V2;
9785       To = V1;
9786       DestIndex =
9787           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9788     }
9789   } else {
9790     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9791            "More than one element from V1 and from V2, or no elements from one "
9792            "of the vectors. This case should not have returned true from "
9793            "isINSERTPSMask");
9794     From = V2;
9795     To = V1;
9796     DestIndex =
9797         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9798   }
9799
9800   // Get an index into the source vector in the range [0,4) (the mask is
9801   // in the range [0,8) because it can address V1 and V2)
9802   unsigned SrcIndex = Mask[DestIndex] % 4;
9803   if (MayFoldLoad(From)) {
9804     // Trivial case, when From comes from a load and is only used by the
9805     // shuffle. Make it use insertps from the vector that we need from that
9806     // load.
9807     SDValue NewLoad =
9808         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9809     if (!NewLoad.getNode())
9810       return SDValue();
9811
9812     if (EVT == MVT::f32) {
9813       // Create this as a scalar to vector to match the instruction pattern.
9814       SDValue LoadScalarToVector =
9815           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9816       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9817       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9818                          InsertpsMask);
9819     } else { // EVT == MVT::i32
9820       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9821       // instruction, to match the PINSRD instruction, which loads an i32 to a
9822       // certain vector element.
9823       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9824                          DAG.getConstant(DestIndex, MVT::i32));
9825     }
9826   }
9827
9828   // Vector-element-to-vector
9829   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9830   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9831 }
9832
9833 // Reduce a vector shuffle to zext.
9834 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9835                                     SelectionDAG &DAG) {
9836   // PMOVZX is only available from SSE41.
9837   if (!Subtarget->hasSSE41())
9838     return SDValue();
9839
9840   MVT VT = Op.getSimpleValueType();
9841
9842   // Only AVX2 support 256-bit vector integer extending.
9843   if (!Subtarget->hasInt256() && VT.is256BitVector())
9844     return SDValue();
9845
9846   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9847   SDLoc DL(Op);
9848   SDValue V1 = Op.getOperand(0);
9849   SDValue V2 = Op.getOperand(1);
9850   unsigned NumElems = VT.getVectorNumElements();
9851
9852   // Extending is an unary operation and the element type of the source vector
9853   // won't be equal to or larger than i64.
9854   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9855       VT.getVectorElementType() == MVT::i64)
9856     return SDValue();
9857
9858   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9859   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9860   while ((1U << Shift) < NumElems) {
9861     if (SVOp->getMaskElt(1U << Shift) == 1)
9862       break;
9863     Shift += 1;
9864     // The maximal ratio is 8, i.e. from i8 to i64.
9865     if (Shift > 3)
9866       return SDValue();
9867   }
9868
9869   // Check the shuffle mask.
9870   unsigned Mask = (1U << Shift) - 1;
9871   for (unsigned i = 0; i != NumElems; ++i) {
9872     int EltIdx = SVOp->getMaskElt(i);
9873     if ((i & Mask) != 0 && EltIdx != -1)
9874       return SDValue();
9875     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9876       return SDValue();
9877   }
9878
9879   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9880   MVT NeVT = MVT::getIntegerVT(NBits);
9881   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9882
9883   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9884     return SDValue();
9885
9886   // Simplify the operand as it's prepared to be fed into shuffle.
9887   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9888   if (V1.getOpcode() == ISD::BITCAST &&
9889       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9890       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9891       V1.getOperand(0).getOperand(0)
9892         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9893     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9894     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9895     ConstantSDNode *CIdx =
9896       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9897     // If it's foldable, i.e. normal load with single use, we will let code
9898     // selection to fold it. Otherwise, we will short the conversion sequence.
9899     if (CIdx && CIdx->getZExtValue() == 0 &&
9900         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9901       MVT FullVT = V.getSimpleValueType();
9902       MVT V1VT = V1.getSimpleValueType();
9903       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9904         // The "ext_vec_elt" node is wider than the result node.
9905         // In this case we should extract subvector from V.
9906         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9907         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9908         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9909                                         FullVT.getVectorNumElements()/Ratio);
9910         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9911                         DAG.getIntPtrConstant(0));
9912       }
9913       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9914     }
9915   }
9916
9917   return DAG.getNode(ISD::BITCAST, DL, VT,
9918                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9919 }
9920
9921 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9922                                       SelectionDAG &DAG) {
9923   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9924   MVT VT = Op.getSimpleValueType();
9925   SDLoc dl(Op);
9926   SDValue V1 = Op.getOperand(0);
9927   SDValue V2 = Op.getOperand(1);
9928
9929   if (isZeroShuffle(SVOp))
9930     return getZeroVector(VT, Subtarget, DAG, dl);
9931
9932   // Handle splat operations
9933   if (SVOp->isSplat()) {
9934     // Use vbroadcast whenever the splat comes from a foldable load
9935     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9936     if (Broadcast.getNode())
9937       return Broadcast;
9938   }
9939
9940   // Check integer expanding shuffles.
9941   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9942   if (NewOp.getNode())
9943     return NewOp;
9944
9945   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9946   // do it!
9947   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9948       VT == MVT::v32i8) {
9949     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9950     if (NewOp.getNode())
9951       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9952   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9953     // FIXME: Figure out a cleaner way to do this.
9954     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9955       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9956       if (NewOp.getNode()) {
9957         MVT NewVT = NewOp.getSimpleValueType();
9958         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9959                                NewVT, true, false))
9960           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9961                               dl);
9962       }
9963     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9964       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9965       if (NewOp.getNode()) {
9966         MVT NewVT = NewOp.getSimpleValueType();
9967         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9968           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9969                               dl);
9970       }
9971     }
9972   }
9973   return SDValue();
9974 }
9975
9976 SDValue
9977 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9978   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9979   SDValue V1 = Op.getOperand(0);
9980   SDValue V2 = Op.getOperand(1);
9981   MVT VT = Op.getSimpleValueType();
9982   SDLoc dl(Op);
9983   unsigned NumElems = VT.getVectorNumElements();
9984   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9985   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9986   bool V1IsSplat = false;
9987   bool V2IsSplat = false;
9988   bool HasSSE2 = Subtarget->hasSSE2();
9989   bool HasFp256    = Subtarget->hasFp256();
9990   bool HasInt256   = Subtarget->hasInt256();
9991   MachineFunction &MF = DAG.getMachineFunction();
9992   bool OptForSize = MF.getFunction()->getAttributes().
9993     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9994
9995   // Check if we should use the experimental vector shuffle lowering. If so,
9996   // delegate completely to that code path.
9997   if (ExperimentalVectorShuffleLowering)
9998     return lowerVectorShuffle(Op, Subtarget, DAG);
9999
10000   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10001
10002   if (V1IsUndef && V2IsUndef)
10003     return DAG.getUNDEF(VT);
10004
10005   // When we create a shuffle node we put the UNDEF node to second operand,
10006   // but in some cases the first operand may be transformed to UNDEF.
10007   // In this case we should just commute the node.
10008   if (V1IsUndef)
10009     return DAG.getCommutedVectorShuffle(*SVOp);
10010
10011   // Vector shuffle lowering takes 3 steps:
10012   //
10013   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
10014   //    narrowing and commutation of operands should be handled.
10015   // 2) Matching of shuffles with known shuffle masks to x86 target specific
10016   //    shuffle nodes.
10017   // 3) Rewriting of unmatched masks into new generic shuffle operations,
10018   //    so the shuffle can be broken into other shuffles and the legalizer can
10019   //    try the lowering again.
10020   //
10021   // The general idea is that no vector_shuffle operation should be left to
10022   // be matched during isel, all of them must be converted to a target specific
10023   // node here.
10024
10025   // Normalize the input vectors. Here splats, zeroed vectors, profitable
10026   // narrowing and commutation of operands should be handled. The actual code
10027   // doesn't include all of those, work in progress...
10028   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
10029   if (NewOp.getNode())
10030     return NewOp;
10031
10032   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
10033
10034   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
10035   // unpckh_undef). Only use pshufd if speed is more important than size.
10036   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10037     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10038   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10039     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10040
10041   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
10042       V2IsUndef && MayFoldVectorLoad(V1))
10043     return getMOVDDup(Op, dl, V1, DAG);
10044
10045   if (isMOVHLPS_v_undef_Mask(M, VT))
10046     return getMOVHighToLow(Op, dl, DAG);
10047
10048   // Use to match splats
10049   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
10050       (VT == MVT::v2f64 || VT == MVT::v2i64))
10051     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10052
10053   if (isPSHUFDMask(M, VT)) {
10054     // The actual implementation will match the mask in the if above and then
10055     // during isel it can match several different instructions, not only pshufd
10056     // as its name says, sad but true, emulate the behavior for now...
10057     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
10058       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
10059
10060     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
10061
10062     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
10063       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
10064
10065     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
10066       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
10067                                   DAG);
10068
10069     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
10070                                 TargetMask, DAG);
10071   }
10072
10073   if (isPALIGNRMask(M, VT, Subtarget))
10074     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
10075                                 getShufflePALIGNRImmediate(SVOp),
10076                                 DAG);
10077
10078   if (isVALIGNMask(M, VT, Subtarget))
10079     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
10080                                 getShuffleVALIGNImmediate(SVOp),
10081                                 DAG);
10082
10083   // Check if this can be converted into a logical shift.
10084   bool isLeft = false;
10085   unsigned ShAmt = 0;
10086   SDValue ShVal;
10087   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
10088   if (isShift && ShVal.hasOneUse()) {
10089     // If the shifted value has multiple uses, it may be cheaper to use
10090     // v_set0 + movlhps or movhlps, etc.
10091     MVT EltVT = VT.getVectorElementType();
10092     ShAmt *= EltVT.getSizeInBits();
10093     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10094   }
10095
10096   if (isMOVLMask(M, VT)) {
10097     if (ISD::isBuildVectorAllZeros(V1.getNode()))
10098       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
10099     if (!isMOVLPMask(M, VT)) {
10100       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
10101         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10102
10103       if (VT == MVT::v4i32 || VT == MVT::v4f32)
10104         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10105     }
10106   }
10107
10108   // FIXME: fold these into legal mask.
10109   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
10110     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
10111
10112   if (isMOVHLPSMask(M, VT))
10113     return getMOVHighToLow(Op, dl, DAG);
10114
10115   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
10116     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
10117
10118   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
10119     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
10120
10121   if (isMOVLPMask(M, VT))
10122     return getMOVLP(Op, dl, DAG, HasSSE2);
10123
10124   if (ShouldXformToMOVHLPS(M, VT) ||
10125       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
10126     return DAG.getCommutedVectorShuffle(*SVOp);
10127
10128   if (isShift) {
10129     // No better options. Use a vshldq / vsrldq.
10130     MVT EltVT = VT.getVectorElementType();
10131     ShAmt *= EltVT.getSizeInBits();
10132     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10133   }
10134
10135   bool Commuted = false;
10136   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
10137   // 1,1,1,1 -> v8i16 though.
10138   BitVector UndefElements;
10139   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
10140     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10141       V1IsSplat = true;
10142   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
10143     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10144       V2IsSplat = true;
10145
10146   // Canonicalize the splat or undef, if present, to be on the RHS.
10147   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
10148     CommuteVectorShuffleMask(M, NumElems);
10149     std::swap(V1, V2);
10150     std::swap(V1IsSplat, V2IsSplat);
10151     Commuted = true;
10152   }
10153
10154   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
10155     // Shuffling low element of v1 into undef, just return v1.
10156     if (V2IsUndef)
10157       return V1;
10158     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
10159     // the instruction selector will not match, so get a canonical MOVL with
10160     // swapped operands to undo the commute.
10161     return getMOVL(DAG, dl, VT, V2, V1);
10162   }
10163
10164   if (isUNPCKLMask(M, VT, HasInt256))
10165     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10166
10167   if (isUNPCKHMask(M, VT, HasInt256))
10168     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10169
10170   if (V2IsSplat) {
10171     // Normalize mask so all entries that point to V2 points to its first
10172     // element then try to match unpck{h|l} again. If match, return a
10173     // new vector_shuffle with the corrected mask.p
10174     SmallVector<int, 8> NewMask(M.begin(), M.end());
10175     NormalizeMask(NewMask, NumElems);
10176     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
10177       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10178     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
10179       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10180   }
10181
10182   if (Commuted) {
10183     // Commute is back and try unpck* again.
10184     // FIXME: this seems wrong.
10185     CommuteVectorShuffleMask(M, NumElems);
10186     std::swap(V1, V2);
10187     std::swap(V1IsSplat, V2IsSplat);
10188
10189     if (isUNPCKLMask(M, VT, HasInt256))
10190       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10191
10192     if (isUNPCKHMask(M, VT, HasInt256))
10193       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10194   }
10195
10196   // Normalize the node to match x86 shuffle ops if needed
10197   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
10198     return DAG.getCommutedVectorShuffle(*SVOp);
10199
10200   // The checks below are all present in isShuffleMaskLegal, but they are
10201   // inlined here right now to enable us to directly emit target specific
10202   // nodes, and remove one by one until they don't return Op anymore.
10203
10204   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
10205       SVOp->getSplatIndex() == 0 && V2IsUndef) {
10206     if (VT == MVT::v2f64 || VT == MVT::v2i64)
10207       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10208   }
10209
10210   if (isPSHUFHWMask(M, VT, HasInt256))
10211     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
10212                                 getShufflePSHUFHWImmediate(SVOp),
10213                                 DAG);
10214
10215   if (isPSHUFLWMask(M, VT, HasInt256))
10216     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
10217                                 getShufflePSHUFLWImmediate(SVOp),
10218                                 DAG);
10219
10220   unsigned MaskValue;
10221   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
10222                   &MaskValue))
10223     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
10224
10225   if (isSHUFPMask(M, VT))
10226     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
10227                                 getShuffleSHUFImmediate(SVOp), DAG);
10228
10229   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10230     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10231   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10232     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10233
10234   //===--------------------------------------------------------------------===//
10235   // Generate target specific nodes for 128 or 256-bit shuffles only
10236   // supported in the AVX instruction set.
10237   //
10238
10239   // Handle VMOVDDUPY permutations
10240   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
10241     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
10242
10243   // Handle VPERMILPS/D* permutations
10244   if (isVPERMILPMask(M, VT)) {
10245     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
10246       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
10247                                   getShuffleSHUFImmediate(SVOp), DAG);
10248     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
10249                                 getShuffleSHUFImmediate(SVOp), DAG);
10250   }
10251
10252   unsigned Idx;
10253   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
10254     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
10255                               Idx*(NumElems/2), DAG, dl);
10256
10257   // Handle VPERM2F128/VPERM2I128 permutations
10258   if (isVPERM2X128Mask(M, VT, HasFp256))
10259     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
10260                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
10261
10262   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
10263     return getINSERTPS(SVOp, dl, DAG);
10264
10265   unsigned Imm8;
10266   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
10267     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
10268
10269   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
10270       VT.is512BitVector()) {
10271     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
10272     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
10273     SmallVector<SDValue, 16> permclMask;
10274     for (unsigned i = 0; i != NumElems; ++i) {
10275       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
10276     }
10277
10278     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
10279     if (V2IsUndef)
10280       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
10281       return DAG.getNode(X86ISD::VPERMV, dl, VT,
10282                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
10283     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
10284                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
10285   }
10286
10287   //===--------------------------------------------------------------------===//
10288   // Since no target specific shuffle was selected for this generic one,
10289   // lower it into other known shuffles. FIXME: this isn't true yet, but
10290   // this is the plan.
10291   //
10292
10293   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
10294   if (VT == MVT::v8i16) {
10295     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
10296     if (NewOp.getNode())
10297       return NewOp;
10298   }
10299
10300   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
10301     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
10302     if (NewOp.getNode())
10303       return NewOp;
10304   }
10305
10306   if (VT == MVT::v16i8) {
10307     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
10308     if (NewOp.getNode())
10309       return NewOp;
10310   }
10311
10312   if (VT == MVT::v32i8) {
10313     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
10314     if (NewOp.getNode())
10315       return NewOp;
10316   }
10317
10318   // Handle all 128-bit wide vectors with 4 elements, and match them with
10319   // several different shuffle types.
10320   if (NumElems == 4 && VT.is128BitVector())
10321     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
10322
10323   // Handle general 256-bit shuffles
10324   if (VT.is256BitVector())
10325     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
10326
10327   return SDValue();
10328 }
10329
10330 // This function assumes its argument is a BUILD_VECTOR of constants or
10331 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10332 // true.
10333 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10334                                     unsigned &MaskValue) {
10335   MaskValue = 0;
10336   unsigned NumElems = BuildVector->getNumOperands();
10337   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10338   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10339   unsigned NumElemsInLane = NumElems / NumLanes;
10340
10341   // Blend for v16i16 should be symetric for the both lanes.
10342   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10343     SDValue EltCond = BuildVector->getOperand(i);
10344     SDValue SndLaneEltCond =
10345         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10346
10347     int Lane1Cond = -1, Lane2Cond = -1;
10348     if (isa<ConstantSDNode>(EltCond))
10349       Lane1Cond = !isZero(EltCond);
10350     if (isa<ConstantSDNode>(SndLaneEltCond))
10351       Lane2Cond = !isZero(SndLaneEltCond);
10352
10353     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10354       // Lane1Cond != 0, means we want the first argument.
10355       // Lane1Cond == 0, means we want the second argument.
10356       // The encoding of this argument is 0 for the first argument, 1
10357       // for the second. Therefore, invert the condition.
10358       MaskValue |= !Lane1Cond << i;
10359     else if (Lane1Cond < 0)
10360       MaskValue |= !Lane2Cond << i;
10361     else
10362       return false;
10363   }
10364   return true;
10365 }
10366
10367 // Try to lower a vselect node into a simple blend instruction.
10368 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
10369                                    SelectionDAG &DAG) {
10370   SDValue Cond = Op.getOperand(0);
10371   SDValue LHS = Op.getOperand(1);
10372   SDValue RHS = Op.getOperand(2);
10373   SDLoc dl(Op);
10374   MVT VT = Op.getSimpleValueType();
10375   MVT EltVT = VT.getVectorElementType();
10376   unsigned NumElems = VT.getVectorNumElements();
10377
10378   // There is no blend with immediate in AVX-512.
10379   if (VT.is512BitVector())
10380     return SDValue();
10381
10382   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10383     return SDValue();
10384   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10385     return SDValue();
10386
10387   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10388     return SDValue();
10389
10390   // Check the mask for BLEND and build the value.
10391   unsigned MaskValue = 0;
10392   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10393     return SDValue();
10394
10395   // Convert i32 vectors to floating point if it is not AVX2.
10396   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10397   MVT BlendVT = VT;
10398   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10399     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10400                                NumElems);
10401     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10402     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10403   }
10404
10405   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10406                             DAG.getConstant(MaskValue, MVT::i32));
10407   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10408 }
10409
10410 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10411   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10412   if (BlendOp.getNode())
10413     return BlendOp;
10414
10415   // Some types for vselect were previously set to Expand, not Legal or
10416   // Custom. Return an empty SDValue so we fall-through to Expand, after
10417   // the Custom lowering phase.
10418   MVT VT = Op.getSimpleValueType();
10419   switch (VT.SimpleTy) {
10420   default:
10421     break;
10422   case MVT::v8i16:
10423   case MVT::v16i16:
10424     return SDValue();
10425   }
10426
10427   // We couldn't create a "Blend with immediate" node.
10428   // This node should still be legal, but we'll have to emit a blendv*
10429   // instruction.
10430   return Op;
10431 }
10432
10433 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10434   MVT VT = Op.getSimpleValueType();
10435   SDLoc dl(Op);
10436
10437   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10438     return SDValue();
10439
10440   if (VT.getSizeInBits() == 8) {
10441     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10442                                   Op.getOperand(0), Op.getOperand(1));
10443     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10444                                   DAG.getValueType(VT));
10445     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10446   }
10447
10448   if (VT.getSizeInBits() == 16) {
10449     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10450     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10451     if (Idx == 0)
10452       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10453                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10454                                      DAG.getNode(ISD::BITCAST, dl,
10455                                                  MVT::v4i32,
10456                                                  Op.getOperand(0)),
10457                                      Op.getOperand(1)));
10458     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10459                                   Op.getOperand(0), Op.getOperand(1));
10460     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10461                                   DAG.getValueType(VT));
10462     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10463   }
10464
10465   if (VT == MVT::f32) {
10466     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10467     // the result back to FR32 register. It's only worth matching if the
10468     // result has a single use which is a store or a bitcast to i32.  And in
10469     // the case of a store, it's not worth it if the index is a constant 0,
10470     // because a MOVSSmr can be used instead, which is smaller and faster.
10471     if (!Op.hasOneUse())
10472       return SDValue();
10473     SDNode *User = *Op.getNode()->use_begin();
10474     if ((User->getOpcode() != ISD::STORE ||
10475          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10476           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10477         (User->getOpcode() != ISD::BITCAST ||
10478          User->getValueType(0) != MVT::i32))
10479       return SDValue();
10480     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10481                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10482                                               Op.getOperand(0)),
10483                                               Op.getOperand(1));
10484     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10485   }
10486
10487   if (VT == MVT::i32 || VT == MVT::i64) {
10488     // ExtractPS/pextrq works with constant index.
10489     if (isa<ConstantSDNode>(Op.getOperand(1)))
10490       return Op;
10491   }
10492   return SDValue();
10493 }
10494
10495 /// Extract one bit from mask vector, like v16i1 or v8i1.
10496 /// AVX-512 feature.
10497 SDValue
10498 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10499   SDValue Vec = Op.getOperand(0);
10500   SDLoc dl(Vec);
10501   MVT VecVT = Vec.getSimpleValueType();
10502   SDValue Idx = Op.getOperand(1);
10503   MVT EltVT = Op.getSimpleValueType();
10504
10505   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10506
10507   // variable index can't be handled in mask registers,
10508   // extend vector to VR512
10509   if (!isa<ConstantSDNode>(Idx)) {
10510     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10511     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10512     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10513                               ExtVT.getVectorElementType(), Ext, Idx);
10514     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10515   }
10516
10517   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10518   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10519   unsigned MaxSift = rc->getSize()*8 - 1;
10520   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10521                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10522   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10523                     DAG.getConstant(MaxSift, MVT::i8));
10524   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10525                        DAG.getIntPtrConstant(0));
10526 }
10527
10528 SDValue
10529 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10530                                            SelectionDAG &DAG) const {
10531   SDLoc dl(Op);
10532   SDValue Vec = Op.getOperand(0);
10533   MVT VecVT = Vec.getSimpleValueType();
10534   SDValue Idx = Op.getOperand(1);
10535
10536   if (Op.getSimpleValueType() == MVT::i1)
10537     return ExtractBitFromMaskVector(Op, DAG);
10538
10539   if (!isa<ConstantSDNode>(Idx)) {
10540     if (VecVT.is512BitVector() ||
10541         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10542          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10543
10544       MVT MaskEltVT =
10545         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10546       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10547                                     MaskEltVT.getSizeInBits());
10548
10549       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10550       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10551                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10552                                 Idx, DAG.getConstant(0, getPointerTy()));
10553       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10554       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10555                         Perm, DAG.getConstant(0, getPointerTy()));
10556     }
10557     return SDValue();
10558   }
10559
10560   // If this is a 256-bit vector result, first extract the 128-bit vector and
10561   // then extract the element from the 128-bit vector.
10562   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10563
10564     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10565     // Get the 128-bit vector.
10566     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10567     MVT EltVT = VecVT.getVectorElementType();
10568
10569     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10570
10571     //if (IdxVal >= NumElems/2)
10572     //  IdxVal -= NumElems/2;
10573     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10574     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10575                        DAG.getConstant(IdxVal, MVT::i32));
10576   }
10577
10578   assert(VecVT.is128BitVector() && "Unexpected vector length");
10579
10580   if (Subtarget->hasSSE41()) {
10581     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10582     if (Res.getNode())
10583       return Res;
10584   }
10585
10586   MVT VT = Op.getSimpleValueType();
10587   // TODO: handle v16i8.
10588   if (VT.getSizeInBits() == 16) {
10589     SDValue Vec = Op.getOperand(0);
10590     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10591     if (Idx == 0)
10592       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10593                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10594                                      DAG.getNode(ISD::BITCAST, dl,
10595                                                  MVT::v4i32, Vec),
10596                                      Op.getOperand(1)));
10597     // Transform it so it match pextrw which produces a 32-bit result.
10598     MVT EltVT = MVT::i32;
10599     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10600                                   Op.getOperand(0), Op.getOperand(1));
10601     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10602                                   DAG.getValueType(VT));
10603     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10604   }
10605
10606   if (VT.getSizeInBits() == 32) {
10607     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10608     if (Idx == 0)
10609       return Op;
10610
10611     // SHUFPS the element to the lowest double word, then movss.
10612     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10613     MVT VVT = Op.getOperand(0).getSimpleValueType();
10614     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10615                                        DAG.getUNDEF(VVT), Mask);
10616     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10617                        DAG.getIntPtrConstant(0));
10618   }
10619
10620   if (VT.getSizeInBits() == 64) {
10621     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10622     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10623     //        to match extract_elt for f64.
10624     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10625     if (Idx == 0)
10626       return Op;
10627
10628     // UNPCKHPD the element to the lowest double word, then movsd.
10629     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10630     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10631     int Mask[2] = { 1, -1 };
10632     MVT VVT = Op.getOperand(0).getSimpleValueType();
10633     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10634                                        DAG.getUNDEF(VVT), Mask);
10635     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10636                        DAG.getIntPtrConstant(0));
10637   }
10638
10639   return SDValue();
10640 }
10641
10642 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10643   MVT VT = Op.getSimpleValueType();
10644   MVT EltVT = VT.getVectorElementType();
10645   SDLoc dl(Op);
10646
10647   SDValue N0 = Op.getOperand(0);
10648   SDValue N1 = Op.getOperand(1);
10649   SDValue N2 = Op.getOperand(2);
10650
10651   if (!VT.is128BitVector())
10652     return SDValue();
10653
10654   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
10655       isa<ConstantSDNode>(N2)) {
10656     unsigned Opc;
10657     if (VT == MVT::v8i16)
10658       Opc = X86ISD::PINSRW;
10659     else if (VT == MVT::v16i8)
10660       Opc = X86ISD::PINSRB;
10661     else
10662       Opc = X86ISD::PINSRB;
10663
10664     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10665     // argument.
10666     if (N1.getValueType() != MVT::i32)
10667       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10668     if (N2.getValueType() != MVT::i32)
10669       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10670     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10671   }
10672
10673   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
10674     // Bits [7:6] of the constant are the source select.  This will always be
10675     //  zero here.  The DAG Combiner may combine an extract_elt index into these
10676     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
10677     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10678     // Bits [5:4] of the constant are the destination select.  This is the
10679     //  value of the incoming immediate.
10680     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10681     //   combine either bitwise AND or insert of float 0.0 to set these bits.
10682     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10683     // Create this as a scalar to vector..
10684     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10685     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10686   }
10687
10688   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10689     // PINSR* works with constant index.
10690     return Op;
10691   }
10692   return SDValue();
10693 }
10694
10695 /// Insert one bit to mask vector, like v16i1 or v8i1.
10696 /// AVX-512 feature.
10697 SDValue 
10698 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10699   SDLoc dl(Op);
10700   SDValue Vec = Op.getOperand(0);
10701   SDValue Elt = Op.getOperand(1);
10702   SDValue Idx = Op.getOperand(2);
10703   MVT VecVT = Vec.getSimpleValueType();
10704
10705   if (!isa<ConstantSDNode>(Idx)) {
10706     // Non constant index. Extend source and destination,
10707     // insert element and then truncate the result.
10708     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10709     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10710     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10711       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10712       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10713     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10714   }
10715
10716   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10717   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10718   if (Vec.getOpcode() == ISD::UNDEF)
10719     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10720                        DAG.getConstant(IdxVal, MVT::i8));
10721   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10722   unsigned MaxSift = rc->getSize()*8 - 1;
10723   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10724                     DAG.getConstant(MaxSift, MVT::i8));
10725   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10726                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10727   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10728 }
10729 SDValue
10730 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10731   MVT VT = Op.getSimpleValueType();
10732   MVT EltVT = VT.getVectorElementType();
10733   
10734   if (EltVT == MVT::i1)
10735     return InsertBitToMaskVector(Op, DAG);
10736
10737   SDLoc dl(Op);
10738   SDValue N0 = Op.getOperand(0);
10739   SDValue N1 = Op.getOperand(1);
10740   SDValue N2 = Op.getOperand(2);
10741
10742   // If this is a 256-bit vector result, first extract the 128-bit vector,
10743   // insert the element into the extracted half and then place it back.
10744   if (VT.is256BitVector() || VT.is512BitVector()) {
10745     if (!isa<ConstantSDNode>(N2))
10746       return SDValue();
10747
10748     // Get the desired 128-bit vector half.
10749     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10750     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10751
10752     // Insert the element into the desired half.
10753     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10754     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10755
10756     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10757                     DAG.getConstant(IdxIn128, MVT::i32));
10758
10759     // Insert the changed part back to the 256-bit vector
10760     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10761   }
10762
10763   if (Subtarget->hasSSE41())
10764     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10765
10766   if (EltVT == MVT::i8)
10767     return SDValue();
10768
10769   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10770     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10771     // as its second argument.
10772     if (N1.getValueType() != MVT::i32)
10773       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10774     if (N2.getValueType() != MVT::i32)
10775       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10776     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10777   }
10778   return SDValue();
10779 }
10780
10781 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10782   SDLoc dl(Op);
10783   MVT OpVT = Op.getSimpleValueType();
10784
10785   // If this is a 256-bit vector result, first insert into a 128-bit
10786   // vector and then insert into the 256-bit vector.
10787   if (!OpVT.is128BitVector()) {
10788     // Insert into a 128-bit vector.
10789     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10790     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10791                                  OpVT.getVectorNumElements() / SizeFactor);
10792
10793     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10794
10795     // Insert the 128-bit vector.
10796     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10797   }
10798
10799   if (OpVT == MVT::v1i64 &&
10800       Op.getOperand(0).getValueType() == MVT::i64)
10801     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10802
10803   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10804   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10805   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10806                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10807 }
10808
10809 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10810 // a simple subregister reference or explicit instructions to grab
10811 // upper bits of a vector.
10812 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10813                                       SelectionDAG &DAG) {
10814   SDLoc dl(Op);
10815   SDValue In =  Op.getOperand(0);
10816   SDValue Idx = Op.getOperand(1);
10817   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10818   MVT ResVT   = Op.getSimpleValueType();
10819   MVT InVT    = In.getSimpleValueType();
10820
10821   if (Subtarget->hasFp256()) {
10822     if (ResVT.is128BitVector() &&
10823         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10824         isa<ConstantSDNode>(Idx)) {
10825       return Extract128BitVector(In, IdxVal, DAG, dl);
10826     }
10827     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10828         isa<ConstantSDNode>(Idx)) {
10829       return Extract256BitVector(In, IdxVal, DAG, dl);
10830     }
10831   }
10832   return SDValue();
10833 }
10834
10835 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10836 // simple superregister reference or explicit instructions to insert
10837 // the upper bits of a vector.
10838 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10839                                      SelectionDAG &DAG) {
10840   if (Subtarget->hasFp256()) {
10841     SDLoc dl(Op.getNode());
10842     SDValue Vec = Op.getNode()->getOperand(0);
10843     SDValue SubVec = Op.getNode()->getOperand(1);
10844     SDValue Idx = Op.getNode()->getOperand(2);
10845
10846     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10847          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10848         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10849         isa<ConstantSDNode>(Idx)) {
10850       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10851       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10852     }
10853
10854     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10855         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10856         isa<ConstantSDNode>(Idx)) {
10857       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10858       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10859     }
10860   }
10861   return SDValue();
10862 }
10863
10864 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10865 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10866 // one of the above mentioned nodes. It has to be wrapped because otherwise
10867 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10868 // be used to form addressing mode. These wrapped nodes will be selected
10869 // into MOV32ri.
10870 SDValue
10871 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10872   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10873
10874   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10875   // global base reg.
10876   unsigned char OpFlag = 0;
10877   unsigned WrapperKind = X86ISD::Wrapper;
10878   CodeModel::Model M = DAG.getTarget().getCodeModel();
10879
10880   if (Subtarget->isPICStyleRIPRel() &&
10881       (M == CodeModel::Small || M == CodeModel::Kernel))
10882     WrapperKind = X86ISD::WrapperRIP;
10883   else if (Subtarget->isPICStyleGOT())
10884     OpFlag = X86II::MO_GOTOFF;
10885   else if (Subtarget->isPICStyleStubPIC())
10886     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10887
10888   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10889                                              CP->getAlignment(),
10890                                              CP->getOffset(), OpFlag);
10891   SDLoc DL(CP);
10892   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10893   // With PIC, the address is actually $g + Offset.
10894   if (OpFlag) {
10895     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10896                          DAG.getNode(X86ISD::GlobalBaseReg,
10897                                      SDLoc(), getPointerTy()),
10898                          Result);
10899   }
10900
10901   return Result;
10902 }
10903
10904 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10905   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10906
10907   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10908   // global base reg.
10909   unsigned char OpFlag = 0;
10910   unsigned WrapperKind = X86ISD::Wrapper;
10911   CodeModel::Model M = DAG.getTarget().getCodeModel();
10912
10913   if (Subtarget->isPICStyleRIPRel() &&
10914       (M == CodeModel::Small || M == CodeModel::Kernel))
10915     WrapperKind = X86ISD::WrapperRIP;
10916   else if (Subtarget->isPICStyleGOT())
10917     OpFlag = X86II::MO_GOTOFF;
10918   else if (Subtarget->isPICStyleStubPIC())
10919     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10920
10921   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10922                                           OpFlag);
10923   SDLoc DL(JT);
10924   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10925
10926   // With PIC, the address is actually $g + Offset.
10927   if (OpFlag)
10928     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10929                          DAG.getNode(X86ISD::GlobalBaseReg,
10930                                      SDLoc(), getPointerTy()),
10931                          Result);
10932
10933   return Result;
10934 }
10935
10936 SDValue
10937 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10938   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10939
10940   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10941   // global base reg.
10942   unsigned char OpFlag = 0;
10943   unsigned WrapperKind = X86ISD::Wrapper;
10944   CodeModel::Model M = DAG.getTarget().getCodeModel();
10945
10946   if (Subtarget->isPICStyleRIPRel() &&
10947       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10948     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10949       OpFlag = X86II::MO_GOTPCREL;
10950     WrapperKind = X86ISD::WrapperRIP;
10951   } else if (Subtarget->isPICStyleGOT()) {
10952     OpFlag = X86II::MO_GOT;
10953   } else if (Subtarget->isPICStyleStubPIC()) {
10954     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10955   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10956     OpFlag = X86II::MO_DARWIN_NONLAZY;
10957   }
10958
10959   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10960
10961   SDLoc DL(Op);
10962   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10963
10964   // With PIC, the address is actually $g + Offset.
10965   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10966       !Subtarget->is64Bit()) {
10967     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10968                          DAG.getNode(X86ISD::GlobalBaseReg,
10969                                      SDLoc(), getPointerTy()),
10970                          Result);
10971   }
10972
10973   // For symbols that require a load from a stub to get the address, emit the
10974   // load.
10975   if (isGlobalStubReference(OpFlag))
10976     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10977                          MachinePointerInfo::getGOT(), false, false, false, 0);
10978
10979   return Result;
10980 }
10981
10982 SDValue
10983 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10984   // Create the TargetBlockAddressAddress node.
10985   unsigned char OpFlags =
10986     Subtarget->ClassifyBlockAddressReference();
10987   CodeModel::Model M = DAG.getTarget().getCodeModel();
10988   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10989   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10990   SDLoc dl(Op);
10991   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10992                                              OpFlags);
10993
10994   if (Subtarget->isPICStyleRIPRel() &&
10995       (M == CodeModel::Small || M == CodeModel::Kernel))
10996     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10997   else
10998     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10999
11000   // With PIC, the address is actually $g + Offset.
11001   if (isGlobalRelativeToPICBase(OpFlags)) {
11002     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11003                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11004                          Result);
11005   }
11006
11007   return Result;
11008 }
11009
11010 SDValue
11011 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11012                                       int64_t Offset, SelectionDAG &DAG) const {
11013   // Create the TargetGlobalAddress node, folding in the constant
11014   // offset if it is legal.
11015   unsigned char OpFlags =
11016       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11017   CodeModel::Model M = DAG.getTarget().getCodeModel();
11018   SDValue Result;
11019   if (OpFlags == X86II::MO_NO_FLAG &&
11020       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11021     // A direct static reference to a global.
11022     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11023     Offset = 0;
11024   } else {
11025     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11026   }
11027
11028   if (Subtarget->isPICStyleRIPRel() &&
11029       (M == CodeModel::Small || M == CodeModel::Kernel))
11030     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11031   else
11032     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11033
11034   // With PIC, the address is actually $g + Offset.
11035   if (isGlobalRelativeToPICBase(OpFlags)) {
11036     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11037                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11038                          Result);
11039   }
11040
11041   // For globals that require a load from a stub to get the address, emit the
11042   // load.
11043   if (isGlobalStubReference(OpFlags))
11044     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11045                          MachinePointerInfo::getGOT(), false, false, false, 0);
11046
11047   // If there was a non-zero offset that we didn't fold, create an explicit
11048   // addition for it.
11049   if (Offset != 0)
11050     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11051                          DAG.getConstant(Offset, getPointerTy()));
11052
11053   return Result;
11054 }
11055
11056 SDValue
11057 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11058   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11059   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11060   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11061 }
11062
11063 static SDValue
11064 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11065            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11066            unsigned char OperandFlags, bool LocalDynamic = false) {
11067   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11068   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11069   SDLoc dl(GA);
11070   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11071                                            GA->getValueType(0),
11072                                            GA->getOffset(),
11073                                            OperandFlags);
11074
11075   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11076                                            : X86ISD::TLSADDR;
11077
11078   if (InFlag) {
11079     SDValue Ops[] = { Chain,  TGA, *InFlag };
11080     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11081   } else {
11082     SDValue Ops[]  = { Chain, TGA };
11083     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11084   }
11085
11086   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11087   MFI->setAdjustsStack(true);
11088
11089   SDValue Flag = Chain.getValue(1);
11090   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11091 }
11092
11093 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11094 static SDValue
11095 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11096                                 const EVT PtrVT) {
11097   SDValue InFlag;
11098   SDLoc dl(GA);  // ? function entry point might be better
11099   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11100                                    DAG.getNode(X86ISD::GlobalBaseReg,
11101                                                SDLoc(), PtrVT), InFlag);
11102   InFlag = Chain.getValue(1);
11103
11104   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11105 }
11106
11107 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11108 static SDValue
11109 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11110                                 const EVT PtrVT) {
11111   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11112                     X86::RAX, X86II::MO_TLSGD);
11113 }
11114
11115 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11116                                            SelectionDAG &DAG,
11117                                            const EVT PtrVT,
11118                                            bool is64Bit) {
11119   SDLoc dl(GA);
11120
11121   // Get the start address of the TLS block for this module.
11122   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11123       .getInfo<X86MachineFunctionInfo>();
11124   MFI->incNumLocalDynamicTLSAccesses();
11125
11126   SDValue Base;
11127   if (is64Bit) {
11128     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11129                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11130   } else {
11131     SDValue InFlag;
11132     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11133         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11134     InFlag = Chain.getValue(1);
11135     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11136                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11137   }
11138
11139   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11140   // of Base.
11141
11142   // Build x@dtpoff.
11143   unsigned char OperandFlags = X86II::MO_DTPOFF;
11144   unsigned WrapperKind = X86ISD::Wrapper;
11145   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11146                                            GA->getValueType(0),
11147                                            GA->getOffset(), OperandFlags);
11148   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11149
11150   // Add x@dtpoff with the base.
11151   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11152 }
11153
11154 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11155 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11156                                    const EVT PtrVT, TLSModel::Model model,
11157                                    bool is64Bit, bool isPIC) {
11158   SDLoc dl(GA);
11159
11160   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11161   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11162                                                          is64Bit ? 257 : 256));
11163
11164   SDValue ThreadPointer =
11165       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11166                   MachinePointerInfo(Ptr), false, false, false, 0);
11167
11168   unsigned char OperandFlags = 0;
11169   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11170   // initialexec.
11171   unsigned WrapperKind = X86ISD::Wrapper;
11172   if (model == TLSModel::LocalExec) {
11173     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11174   } else if (model == TLSModel::InitialExec) {
11175     if (is64Bit) {
11176       OperandFlags = X86II::MO_GOTTPOFF;
11177       WrapperKind = X86ISD::WrapperRIP;
11178     } else {
11179       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11180     }
11181   } else {
11182     llvm_unreachable("Unexpected model");
11183   }
11184
11185   // emit "addl x@ntpoff,%eax" (local exec)
11186   // or "addl x@indntpoff,%eax" (initial exec)
11187   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11188   SDValue TGA =
11189       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11190                                  GA->getOffset(), OperandFlags);
11191   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11192
11193   if (model == TLSModel::InitialExec) {
11194     if (isPIC && !is64Bit) {
11195       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11196                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11197                            Offset);
11198     }
11199
11200     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11201                          MachinePointerInfo::getGOT(), false, false, false, 0);
11202   }
11203
11204   // The address of the thread local variable is the add of the thread
11205   // pointer with the offset of the variable.
11206   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11207 }
11208
11209 SDValue
11210 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11211
11212   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11213   const GlobalValue *GV = GA->getGlobal();
11214
11215   if (Subtarget->isTargetELF()) {
11216     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11217
11218     switch (model) {
11219       case TLSModel::GeneralDynamic:
11220         if (Subtarget->is64Bit())
11221           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11222         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11223       case TLSModel::LocalDynamic:
11224         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11225                                            Subtarget->is64Bit());
11226       case TLSModel::InitialExec:
11227       case TLSModel::LocalExec:
11228         return LowerToTLSExecModel(
11229             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11230             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11231     }
11232     llvm_unreachable("Unknown TLS model.");
11233   }
11234
11235   if (Subtarget->isTargetDarwin()) {
11236     // Darwin only has one model of TLS.  Lower to that.
11237     unsigned char OpFlag = 0;
11238     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11239                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11240
11241     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11242     // global base reg.
11243     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11244                  !Subtarget->is64Bit();
11245     if (PIC32)
11246       OpFlag = X86II::MO_TLVP_PIC_BASE;
11247     else
11248       OpFlag = X86II::MO_TLVP;
11249     SDLoc DL(Op);
11250     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11251                                                 GA->getValueType(0),
11252                                                 GA->getOffset(), OpFlag);
11253     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11254
11255     // With PIC32, the address is actually $g + Offset.
11256     if (PIC32)
11257       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11258                            DAG.getNode(X86ISD::GlobalBaseReg,
11259                                        SDLoc(), getPointerTy()),
11260                            Offset);
11261
11262     // Lowering the machine isd will make sure everything is in the right
11263     // location.
11264     SDValue Chain = DAG.getEntryNode();
11265     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11266     SDValue Args[] = { Chain, Offset };
11267     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11268
11269     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11270     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11271     MFI->setAdjustsStack(true);
11272
11273     // And our return value (tls address) is in the standard call return value
11274     // location.
11275     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11276     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11277                               Chain.getValue(1));
11278   }
11279
11280   if (Subtarget->isTargetKnownWindowsMSVC() ||
11281       Subtarget->isTargetWindowsGNU()) {
11282     // Just use the implicit TLS architecture
11283     // Need to generate someting similar to:
11284     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11285     //                                  ; from TEB
11286     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11287     //   mov     rcx, qword [rdx+rcx*8]
11288     //   mov     eax, .tls$:tlsvar
11289     //   [rax+rcx] contains the address
11290     // Windows 64bit: gs:0x58
11291     // Windows 32bit: fs:__tls_array
11292
11293     SDLoc dl(GA);
11294     SDValue Chain = DAG.getEntryNode();
11295
11296     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11297     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11298     // use its literal value of 0x2C.
11299     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11300                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11301                                                              256)
11302                                         : Type::getInt32PtrTy(*DAG.getContext(),
11303                                                               257));
11304
11305     SDValue TlsArray =
11306         Subtarget->is64Bit()
11307             ? DAG.getIntPtrConstant(0x58)
11308             : (Subtarget->isTargetWindowsGNU()
11309                    ? DAG.getIntPtrConstant(0x2C)
11310                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11311
11312     SDValue ThreadPointer =
11313         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11314                     MachinePointerInfo(Ptr), false, false, false, 0);
11315
11316     // Load the _tls_index variable
11317     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11318     if (Subtarget->is64Bit())
11319       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11320                            IDX, MachinePointerInfo(), MVT::i32,
11321                            false, false, false, 0);
11322     else
11323       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11324                         false, false, false, 0);
11325
11326     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11327                                     getPointerTy());
11328     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11329
11330     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11331     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11332                       false, false, false, 0);
11333
11334     // Get the offset of start of .tls section
11335     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11336                                              GA->getValueType(0),
11337                                              GA->getOffset(), X86II::MO_SECREL);
11338     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11339
11340     // The address of the thread local variable is the add of the thread
11341     // pointer with the offset of the variable.
11342     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11343   }
11344
11345   llvm_unreachable("TLS not implemented for this target.");
11346 }
11347
11348 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11349 /// and take a 2 x i32 value to shift plus a shift amount.
11350 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11351   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11352   MVT VT = Op.getSimpleValueType();
11353   unsigned VTBits = VT.getSizeInBits();
11354   SDLoc dl(Op);
11355   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11356   SDValue ShOpLo = Op.getOperand(0);
11357   SDValue ShOpHi = Op.getOperand(1);
11358   SDValue ShAmt  = Op.getOperand(2);
11359   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11360   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11361   // during isel.
11362   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11363                                   DAG.getConstant(VTBits - 1, MVT::i8));
11364   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11365                                      DAG.getConstant(VTBits - 1, MVT::i8))
11366                        : DAG.getConstant(0, VT);
11367
11368   SDValue Tmp2, Tmp3;
11369   if (Op.getOpcode() == ISD::SHL_PARTS) {
11370     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11371     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11372   } else {
11373     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11374     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11375   }
11376
11377   // If the shift amount is larger or equal than the width of a part we can't
11378   // rely on the results of shld/shrd. Insert a test and select the appropriate
11379   // values for large shift amounts.
11380   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11381                                 DAG.getConstant(VTBits, MVT::i8));
11382   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11383                              AndNode, DAG.getConstant(0, MVT::i8));
11384
11385   SDValue Hi, Lo;
11386   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11387   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11388   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11389
11390   if (Op.getOpcode() == ISD::SHL_PARTS) {
11391     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11392     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11393   } else {
11394     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11395     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11396   }
11397
11398   SDValue Ops[2] = { Lo, Hi };
11399   return DAG.getMergeValues(Ops, dl);
11400 }
11401
11402 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11403                                            SelectionDAG &DAG) const {
11404   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11405
11406   if (SrcVT.isVector())
11407     return SDValue();
11408
11409   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11410          "Unknown SINT_TO_FP to lower!");
11411
11412   // These are really Legal; return the operand so the caller accepts it as
11413   // Legal.
11414   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11415     return Op;
11416   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11417       Subtarget->is64Bit()) {
11418     return Op;
11419   }
11420
11421   SDLoc dl(Op);
11422   unsigned Size = SrcVT.getSizeInBits()/8;
11423   MachineFunction &MF = DAG.getMachineFunction();
11424   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11425   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11426   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11427                                StackSlot,
11428                                MachinePointerInfo::getFixedStack(SSFI),
11429                                false, false, 0);
11430   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11431 }
11432
11433 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11434                                      SDValue StackSlot,
11435                                      SelectionDAG &DAG) const {
11436   // Build the FILD
11437   SDLoc DL(Op);
11438   SDVTList Tys;
11439   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11440   if (useSSE)
11441     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11442   else
11443     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11444
11445   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11446
11447   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11448   MachineMemOperand *MMO;
11449   if (FI) {
11450     int SSFI = FI->getIndex();
11451     MMO =
11452       DAG.getMachineFunction()
11453       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11454                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11455   } else {
11456     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11457     StackSlot = StackSlot.getOperand(1);
11458   }
11459   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11460   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11461                                            X86ISD::FILD, DL,
11462                                            Tys, Ops, SrcVT, MMO);
11463
11464   if (useSSE) {
11465     Chain = Result.getValue(1);
11466     SDValue InFlag = Result.getValue(2);
11467
11468     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11469     // shouldn't be necessary except that RFP cannot be live across
11470     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11471     MachineFunction &MF = DAG.getMachineFunction();
11472     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11473     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11474     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11475     Tys = DAG.getVTList(MVT::Other);
11476     SDValue Ops[] = {
11477       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11478     };
11479     MachineMemOperand *MMO =
11480       DAG.getMachineFunction()
11481       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11482                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11483
11484     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11485                                     Ops, Op.getValueType(), MMO);
11486     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11487                          MachinePointerInfo::getFixedStack(SSFI),
11488                          false, false, false, 0);
11489   }
11490
11491   return Result;
11492 }
11493
11494 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11495 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11496                                                SelectionDAG &DAG) const {
11497   // This algorithm is not obvious. Here it is what we're trying to output:
11498   /*
11499      movq       %rax,  %xmm0
11500      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11501      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11502      #ifdef __SSE3__
11503        haddpd   %xmm0, %xmm0
11504      #else
11505        pshufd   $0x4e, %xmm0, %xmm1
11506        addpd    %xmm1, %xmm0
11507      #endif
11508   */
11509
11510   SDLoc dl(Op);
11511   LLVMContext *Context = DAG.getContext();
11512
11513   // Build some magic constants.
11514   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11515   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11516   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11517
11518   SmallVector<Constant*,2> CV1;
11519   CV1.push_back(
11520     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11521                                       APInt(64, 0x4330000000000000ULL))));
11522   CV1.push_back(
11523     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11524                                       APInt(64, 0x4530000000000000ULL))));
11525   Constant *C1 = ConstantVector::get(CV1);
11526   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11527
11528   // Load the 64-bit value into an XMM register.
11529   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11530                             Op.getOperand(0));
11531   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11532                               MachinePointerInfo::getConstantPool(),
11533                               false, false, false, 16);
11534   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11535                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11536                               CLod0);
11537
11538   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11539                               MachinePointerInfo::getConstantPool(),
11540                               false, false, false, 16);
11541   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11542   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11543   SDValue Result;
11544
11545   if (Subtarget->hasSSE3()) {
11546     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11547     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11548   } else {
11549     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11550     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11551                                            S2F, 0x4E, DAG);
11552     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11553                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11554                          Sub);
11555   }
11556
11557   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11558                      DAG.getIntPtrConstant(0));
11559 }
11560
11561 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11562 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11563                                                SelectionDAG &DAG) const {
11564   SDLoc dl(Op);
11565   // FP constant to bias correct the final result.
11566   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11567                                    MVT::f64);
11568
11569   // Load the 32-bit value into an XMM register.
11570   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11571                              Op.getOperand(0));
11572
11573   // Zero out the upper parts of the register.
11574   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11575
11576   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11577                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11578                      DAG.getIntPtrConstant(0));
11579
11580   // Or the load with the bias.
11581   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11582                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11583                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11584                                                    MVT::v2f64, Load)),
11585                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11586                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11587                                                    MVT::v2f64, Bias)));
11588   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11589                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11590                    DAG.getIntPtrConstant(0));
11591
11592   // Subtract the bias.
11593   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11594
11595   // Handle final rounding.
11596   EVT DestVT = Op.getValueType();
11597
11598   if (DestVT.bitsLT(MVT::f64))
11599     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11600                        DAG.getIntPtrConstant(0));
11601   if (DestVT.bitsGT(MVT::f64))
11602     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11603
11604   // Handle final rounding.
11605   return Sub;
11606 }
11607
11608 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11609                                                SelectionDAG &DAG) const {
11610   SDValue N0 = Op.getOperand(0);
11611   MVT SVT = N0.getSimpleValueType();
11612   SDLoc dl(Op);
11613
11614   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11615           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11616          "Custom UINT_TO_FP is not supported!");
11617
11618   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11619   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11620                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11621 }
11622
11623 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11624                                            SelectionDAG &DAG) const {
11625   SDValue N0 = Op.getOperand(0);
11626   SDLoc dl(Op);
11627
11628   if (Op.getValueType().isVector())
11629     return lowerUINT_TO_FP_vec(Op, DAG);
11630
11631   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11632   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11633   // the optimization here.
11634   if (DAG.SignBitIsZero(N0))
11635     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11636
11637   MVT SrcVT = N0.getSimpleValueType();
11638   MVT DstVT = Op.getSimpleValueType();
11639   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11640     return LowerUINT_TO_FP_i64(Op, DAG);
11641   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11642     return LowerUINT_TO_FP_i32(Op, DAG);
11643   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11644     return SDValue();
11645
11646   // Make a 64-bit buffer, and use it to build an FILD.
11647   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11648   if (SrcVT == MVT::i32) {
11649     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11650     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11651                                      getPointerTy(), StackSlot, WordOff);
11652     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11653                                   StackSlot, MachinePointerInfo(),
11654                                   false, false, 0);
11655     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11656                                   OffsetSlot, MachinePointerInfo(),
11657                                   false, false, 0);
11658     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11659     return Fild;
11660   }
11661
11662   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11663   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11664                                StackSlot, MachinePointerInfo(),
11665                                false, false, 0);
11666   // For i64 source, we need to add the appropriate power of 2 if the input
11667   // was negative.  This is the same as the optimization in
11668   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11669   // we must be careful to do the computation in x87 extended precision, not
11670   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11671   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11672   MachineMemOperand *MMO =
11673     DAG.getMachineFunction()
11674     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11675                           MachineMemOperand::MOLoad, 8, 8);
11676
11677   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11678   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11679   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11680                                          MVT::i64, MMO);
11681
11682   APInt FF(32, 0x5F800000ULL);
11683
11684   // Check whether the sign bit is set.
11685   SDValue SignSet = DAG.getSetCC(dl,
11686                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11687                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11688                                  ISD::SETLT);
11689
11690   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11691   SDValue FudgePtr = DAG.getConstantPool(
11692                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11693                                          getPointerTy());
11694
11695   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11696   SDValue Zero = DAG.getIntPtrConstant(0);
11697   SDValue Four = DAG.getIntPtrConstant(4);
11698   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11699                                Zero, Four);
11700   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11701
11702   // Load the value out, extending it from f32 to f80.
11703   // FIXME: Avoid the extend by constructing the right constant pool?
11704   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11705                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11706                                  MVT::f32, false, false, false, 4);
11707   // Extend everything to 80 bits to force it to be done on x87.
11708   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11709   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11710 }
11711
11712 std::pair<SDValue,SDValue>
11713 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11714                                     bool IsSigned, bool IsReplace) const {
11715   SDLoc DL(Op);
11716
11717   EVT DstTy = Op.getValueType();
11718
11719   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11720     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11721     DstTy = MVT::i64;
11722   }
11723
11724   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11725          DstTy.getSimpleVT() >= MVT::i16 &&
11726          "Unknown FP_TO_INT to lower!");
11727
11728   // These are really Legal.
11729   if (DstTy == MVT::i32 &&
11730       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11731     return std::make_pair(SDValue(), SDValue());
11732   if (Subtarget->is64Bit() &&
11733       DstTy == MVT::i64 &&
11734       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11735     return std::make_pair(SDValue(), SDValue());
11736
11737   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11738   // stack slot, or into the FTOL runtime function.
11739   MachineFunction &MF = DAG.getMachineFunction();
11740   unsigned MemSize = DstTy.getSizeInBits()/8;
11741   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11742   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11743
11744   unsigned Opc;
11745   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11746     Opc = X86ISD::WIN_FTOL;
11747   else
11748     switch (DstTy.getSimpleVT().SimpleTy) {
11749     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11750     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11751     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11752     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11753     }
11754
11755   SDValue Chain = DAG.getEntryNode();
11756   SDValue Value = Op.getOperand(0);
11757   EVT TheVT = Op.getOperand(0).getValueType();
11758   // FIXME This causes a redundant load/store if the SSE-class value is already
11759   // in memory, such as if it is on the callstack.
11760   if (isScalarFPTypeInSSEReg(TheVT)) {
11761     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11762     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11763                          MachinePointerInfo::getFixedStack(SSFI),
11764                          false, false, 0);
11765     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11766     SDValue Ops[] = {
11767       Chain, StackSlot, DAG.getValueType(TheVT)
11768     };
11769
11770     MachineMemOperand *MMO =
11771       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11772                               MachineMemOperand::MOLoad, MemSize, MemSize);
11773     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11774     Chain = Value.getValue(1);
11775     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11776     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11777   }
11778
11779   MachineMemOperand *MMO =
11780     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11781                             MachineMemOperand::MOStore, MemSize, MemSize);
11782
11783   if (Opc != X86ISD::WIN_FTOL) {
11784     // Build the FP_TO_INT*_IN_MEM
11785     SDValue Ops[] = { Chain, Value, StackSlot };
11786     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11787                                            Ops, DstTy, MMO);
11788     return std::make_pair(FIST, StackSlot);
11789   } else {
11790     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11791       DAG.getVTList(MVT::Other, MVT::Glue),
11792       Chain, Value);
11793     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11794       MVT::i32, ftol.getValue(1));
11795     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11796       MVT::i32, eax.getValue(2));
11797     SDValue Ops[] = { eax, edx };
11798     SDValue pair = IsReplace
11799       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11800       : DAG.getMergeValues(Ops, DL);
11801     return std::make_pair(pair, SDValue());
11802   }
11803 }
11804
11805 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11806                               const X86Subtarget *Subtarget) {
11807   MVT VT = Op->getSimpleValueType(0);
11808   SDValue In = Op->getOperand(0);
11809   MVT InVT = In.getSimpleValueType();
11810   SDLoc dl(Op);
11811
11812   // Optimize vectors in AVX mode:
11813   //
11814   //   v8i16 -> v8i32
11815   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11816   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11817   //   Concat upper and lower parts.
11818   //
11819   //   v4i32 -> v4i64
11820   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11821   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11822   //   Concat upper and lower parts.
11823   //
11824
11825   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11826       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11827       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11828     return SDValue();
11829
11830   if (Subtarget->hasInt256())
11831     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11832
11833   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11834   SDValue Undef = DAG.getUNDEF(InVT);
11835   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11836   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11837   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11838
11839   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11840                              VT.getVectorNumElements()/2);
11841
11842   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11843   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11844
11845   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11846 }
11847
11848 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11849                                         SelectionDAG &DAG) {
11850   MVT VT = Op->getSimpleValueType(0);
11851   SDValue In = Op->getOperand(0);
11852   MVT InVT = In.getSimpleValueType();
11853   SDLoc DL(Op);
11854   unsigned int NumElts = VT.getVectorNumElements();
11855   if (NumElts != 8 && NumElts != 16)
11856     return SDValue();
11857
11858   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11859     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11860
11861   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11862   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11863   // Now we have only mask extension
11864   assert(InVT.getVectorElementType() == MVT::i1);
11865   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11866   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11867   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11868   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11869   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11870                            MachinePointerInfo::getConstantPool(),
11871                            false, false, false, Alignment);
11872
11873   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11874   if (VT.is512BitVector())
11875     return Brcst;
11876   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11877 }
11878
11879 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11880                                SelectionDAG &DAG) {
11881   if (Subtarget->hasFp256()) {
11882     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11883     if (Res.getNode())
11884       return Res;
11885   }
11886
11887   return SDValue();
11888 }
11889
11890 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11891                                 SelectionDAG &DAG) {
11892   SDLoc DL(Op);
11893   MVT VT = Op.getSimpleValueType();
11894   SDValue In = Op.getOperand(0);
11895   MVT SVT = In.getSimpleValueType();
11896
11897   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11898     return LowerZERO_EXTEND_AVX512(Op, DAG);
11899
11900   if (Subtarget->hasFp256()) {
11901     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11902     if (Res.getNode())
11903       return Res;
11904   }
11905
11906   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11907          VT.getVectorNumElements() != SVT.getVectorNumElements());
11908   return SDValue();
11909 }
11910
11911 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11912   SDLoc DL(Op);
11913   MVT VT = Op.getSimpleValueType();
11914   SDValue In = Op.getOperand(0);
11915   MVT InVT = In.getSimpleValueType();
11916
11917   if (VT == MVT::i1) {
11918     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11919            "Invalid scalar TRUNCATE operation");
11920     if (InVT == MVT::i32)
11921       return SDValue();
11922     if (InVT.getSizeInBits() == 64)
11923       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11924     else if (InVT.getSizeInBits() < 32)
11925       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11926     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11927   }
11928   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11929          "Invalid TRUNCATE operation");
11930
11931   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11932     if (VT.getVectorElementType().getSizeInBits() >=8)
11933       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11934
11935     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11936     unsigned NumElts = InVT.getVectorNumElements();
11937     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11938     if (InVT.getSizeInBits() < 512) {
11939       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11940       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11941       InVT = ExtVT;
11942     }
11943     
11944     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11945     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11946     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11947     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11948     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11949                            MachinePointerInfo::getConstantPool(),
11950                            false, false, false, Alignment);
11951     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11952     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11953     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11954   }
11955
11956   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11957     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11958     if (Subtarget->hasInt256()) {
11959       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11960       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11961       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11962                                 ShufMask);
11963       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11964                          DAG.getIntPtrConstant(0));
11965     }
11966
11967     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11968                                DAG.getIntPtrConstant(0));
11969     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11970                                DAG.getIntPtrConstant(2));
11971     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11972     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11973     static const int ShufMask[] = {0, 2, 4, 6};
11974     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11975   }
11976
11977   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11978     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11979     if (Subtarget->hasInt256()) {
11980       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11981
11982       SmallVector<SDValue,32> pshufbMask;
11983       for (unsigned i = 0; i < 2; ++i) {
11984         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11985         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11986         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11987         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11988         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11989         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11990         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11991         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11992         for (unsigned j = 0; j < 8; ++j)
11993           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11994       }
11995       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11996       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11997       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11998
11999       static const int ShufMask[] = {0,  2,  -1,  -1};
12000       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12001                                 &ShufMask[0]);
12002       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12003                        DAG.getIntPtrConstant(0));
12004       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12005     }
12006
12007     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12008                                DAG.getIntPtrConstant(0));
12009
12010     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12011                                DAG.getIntPtrConstant(4));
12012
12013     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12014     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12015
12016     // The PSHUFB mask:
12017     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12018                                    -1, -1, -1, -1, -1, -1, -1, -1};
12019
12020     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12021     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12022     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12023
12024     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12025     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12026
12027     // The MOVLHPS Mask:
12028     static const int ShufMask2[] = {0, 1, 4, 5};
12029     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12030     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12031   }
12032
12033   // Handle truncation of V256 to V128 using shuffles.
12034   if (!VT.is128BitVector() || !InVT.is256BitVector())
12035     return SDValue();
12036
12037   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12038
12039   unsigned NumElems = VT.getVectorNumElements();
12040   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12041
12042   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12043   // Prepare truncation shuffle mask
12044   for (unsigned i = 0; i != NumElems; ++i)
12045     MaskVec[i] = i * 2;
12046   SDValue V = DAG.getVectorShuffle(NVT, DL,
12047                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12048                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12049   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12050                      DAG.getIntPtrConstant(0));
12051 }
12052
12053 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12054                                            SelectionDAG &DAG) const {
12055   assert(!Op.getSimpleValueType().isVector());
12056
12057   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12058     /*IsSigned=*/ true, /*IsReplace=*/ false);
12059   SDValue FIST = Vals.first, StackSlot = Vals.second;
12060   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12061   if (!FIST.getNode()) return Op;
12062
12063   if (StackSlot.getNode())
12064     // Load the result.
12065     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12066                        FIST, StackSlot, MachinePointerInfo(),
12067                        false, false, false, 0);
12068
12069   // The node is the result.
12070   return FIST;
12071 }
12072
12073 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12074                                            SelectionDAG &DAG) const {
12075   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12076     /*IsSigned=*/ false, /*IsReplace=*/ false);
12077   SDValue FIST = Vals.first, StackSlot = Vals.second;
12078   assert(FIST.getNode() && "Unexpected failure");
12079
12080   if (StackSlot.getNode())
12081     // Load the result.
12082     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12083                        FIST, StackSlot, MachinePointerInfo(),
12084                        false, false, false, 0);
12085
12086   // The node is the result.
12087   return FIST;
12088 }
12089
12090 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12091   SDLoc DL(Op);
12092   MVT VT = Op.getSimpleValueType();
12093   SDValue In = Op.getOperand(0);
12094   MVT SVT = In.getSimpleValueType();
12095
12096   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12097
12098   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12099                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12100                                  In, DAG.getUNDEF(SVT)));
12101 }
12102
12103 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
12104   LLVMContext *Context = DAG.getContext();
12105   SDLoc dl(Op);
12106   MVT VT = Op.getSimpleValueType();
12107   MVT EltVT = VT;
12108   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12109   if (VT.isVector()) {
12110     EltVT = VT.getVectorElementType();
12111     NumElts = VT.getVectorNumElements();
12112   }
12113   Constant *C;
12114   if (EltVT == MVT::f64)
12115     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12116                                           APInt(64, ~(1ULL << 63))));
12117   else
12118     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12119                                           APInt(32, ~(1U << 31))));
12120   C = ConstantVector::getSplat(NumElts, C);
12121   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12122   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12123   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12124   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12125                              MachinePointerInfo::getConstantPool(),
12126                              false, false, false, Alignment);
12127   if (VT.isVector()) {
12128     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12129     return DAG.getNode(ISD::BITCAST, dl, VT,
12130                        DAG.getNode(ISD::AND, dl, ANDVT,
12131                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
12132                                                Op.getOperand(0)),
12133                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
12134   }
12135   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
12136 }
12137
12138 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
12139   LLVMContext *Context = DAG.getContext();
12140   SDLoc dl(Op);
12141   MVT VT = Op.getSimpleValueType();
12142   MVT EltVT = VT;
12143   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12144   if (VT.isVector()) {
12145     EltVT = VT.getVectorElementType();
12146     NumElts = VT.getVectorNumElements();
12147   }
12148   Constant *C;
12149   if (EltVT == MVT::f64)
12150     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12151                                           APInt(64, 1ULL << 63)));
12152   else
12153     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12154                                           APInt(32, 1U << 31)));
12155   C = ConstantVector::getSplat(NumElts, C);
12156   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12157   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12158   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12159   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12160                              MachinePointerInfo::getConstantPool(),
12161                              false, false, false, Alignment);
12162   if (VT.isVector()) {
12163     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
12164     return DAG.getNode(ISD::BITCAST, dl, VT,
12165                        DAG.getNode(ISD::XOR, dl, XORVT,
12166                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
12167                                                Op.getOperand(0)),
12168                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
12169   }
12170
12171   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
12172 }
12173
12174 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12175   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12176   LLVMContext *Context = DAG.getContext();
12177   SDValue Op0 = Op.getOperand(0);
12178   SDValue Op1 = Op.getOperand(1);
12179   SDLoc dl(Op);
12180   MVT VT = Op.getSimpleValueType();
12181   MVT SrcVT = Op1.getSimpleValueType();
12182
12183   // If second operand is smaller, extend it first.
12184   if (SrcVT.bitsLT(VT)) {
12185     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12186     SrcVT = VT;
12187   }
12188   // And if it is bigger, shrink it first.
12189   if (SrcVT.bitsGT(VT)) {
12190     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12191     SrcVT = VT;
12192   }
12193
12194   // At this point the operands and the result should have the same
12195   // type, and that won't be f80 since that is not custom lowered.
12196
12197   // First get the sign bit of second operand.
12198   SmallVector<Constant*,4> CV;
12199   if (SrcVT == MVT::f64) {
12200     const fltSemantics &Sem = APFloat::IEEEdouble;
12201     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
12202     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12203   } else {
12204     const fltSemantics &Sem = APFloat::IEEEsingle;
12205     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
12206     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12207     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12208     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12209   }
12210   Constant *C = ConstantVector::get(CV);
12211   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12212   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12213                               MachinePointerInfo::getConstantPool(),
12214                               false, false, false, 16);
12215   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12216
12217   // Shift sign bit right or left if the two operands have different types.
12218   if (SrcVT.bitsGT(VT)) {
12219     // Op0 is MVT::f32, Op1 is MVT::f64.
12220     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
12221     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
12222                           DAG.getConstant(32, MVT::i32));
12223     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
12224     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
12225                           DAG.getIntPtrConstant(0));
12226   }
12227
12228   // Clear first operand sign bit.
12229   CV.clear();
12230   if (VT == MVT::f64) {
12231     const fltSemantics &Sem = APFloat::IEEEdouble;
12232     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12233                                                    APInt(64, ~(1ULL << 63)))));
12234     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12235   } else {
12236     const fltSemantics &Sem = APFloat::IEEEsingle;
12237     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12238                                                    APInt(32, ~(1U << 31)))));
12239     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12240     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12241     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12242   }
12243   C = ConstantVector::get(CV);
12244   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12245   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12246                               MachinePointerInfo::getConstantPool(),
12247                               false, false, false, 16);
12248   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
12249
12250   // Or the value with the sign bit.
12251   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12252 }
12253
12254 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12255   SDValue N0 = Op.getOperand(0);
12256   SDLoc dl(Op);
12257   MVT VT = Op.getSimpleValueType();
12258
12259   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12260   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12261                                   DAG.getConstant(1, VT));
12262   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12263 }
12264
12265 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
12266 //
12267 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12268                                       SelectionDAG &DAG) {
12269   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12270
12271   if (!Subtarget->hasSSE41())
12272     return SDValue();
12273
12274   if (!Op->hasOneUse())
12275     return SDValue();
12276
12277   SDNode *N = Op.getNode();
12278   SDLoc DL(N);
12279
12280   SmallVector<SDValue, 8> Opnds;
12281   DenseMap<SDValue, unsigned> VecInMap;
12282   SmallVector<SDValue, 8> VecIns;
12283   EVT VT = MVT::Other;
12284
12285   // Recognize a special case where a vector is casted into wide integer to
12286   // test all 0s.
12287   Opnds.push_back(N->getOperand(0));
12288   Opnds.push_back(N->getOperand(1));
12289
12290   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12291     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12292     // BFS traverse all OR'd operands.
12293     if (I->getOpcode() == ISD::OR) {
12294       Opnds.push_back(I->getOperand(0));
12295       Opnds.push_back(I->getOperand(1));
12296       // Re-evaluate the number of nodes to be traversed.
12297       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12298       continue;
12299     }
12300
12301     // Quit if a non-EXTRACT_VECTOR_ELT
12302     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12303       return SDValue();
12304
12305     // Quit if without a constant index.
12306     SDValue Idx = I->getOperand(1);
12307     if (!isa<ConstantSDNode>(Idx))
12308       return SDValue();
12309
12310     SDValue ExtractedFromVec = I->getOperand(0);
12311     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12312     if (M == VecInMap.end()) {
12313       VT = ExtractedFromVec.getValueType();
12314       // Quit if not 128/256-bit vector.
12315       if (!VT.is128BitVector() && !VT.is256BitVector())
12316         return SDValue();
12317       // Quit if not the same type.
12318       if (VecInMap.begin() != VecInMap.end() &&
12319           VT != VecInMap.begin()->first.getValueType())
12320         return SDValue();
12321       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12322       VecIns.push_back(ExtractedFromVec);
12323     }
12324     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12325   }
12326
12327   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12328          "Not extracted from 128-/256-bit vector.");
12329
12330   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12331
12332   for (DenseMap<SDValue, unsigned>::const_iterator
12333         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12334     // Quit if not all elements are used.
12335     if (I->second != FullMask)
12336       return SDValue();
12337   }
12338
12339   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12340
12341   // Cast all vectors into TestVT for PTEST.
12342   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12343     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12344
12345   // If more than one full vectors are evaluated, OR them first before PTEST.
12346   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12347     // Each iteration will OR 2 nodes and append the result until there is only
12348     // 1 node left, i.e. the final OR'd value of all vectors.
12349     SDValue LHS = VecIns[Slot];
12350     SDValue RHS = VecIns[Slot + 1];
12351     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12352   }
12353
12354   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12355                      VecIns.back(), VecIns.back());
12356 }
12357
12358 /// \brief return true if \c Op has a use that doesn't just read flags.
12359 static bool hasNonFlagsUse(SDValue Op) {
12360   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12361        ++UI) {
12362     SDNode *User = *UI;
12363     unsigned UOpNo = UI.getOperandNo();
12364     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12365       // Look pass truncate.
12366       UOpNo = User->use_begin().getOperandNo();
12367       User = *User->use_begin();
12368     }
12369
12370     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12371         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12372       return true;
12373   }
12374   return false;
12375 }
12376
12377 /// Emit nodes that will be selected as "test Op0,Op0", or something
12378 /// equivalent.
12379 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12380                                     SelectionDAG &DAG) const {
12381   if (Op.getValueType() == MVT::i1)
12382     // KORTEST instruction should be selected
12383     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12384                        DAG.getConstant(0, Op.getValueType()));
12385
12386   // CF and OF aren't always set the way we want. Determine which
12387   // of these we need.
12388   bool NeedCF = false;
12389   bool NeedOF = false;
12390   switch (X86CC) {
12391   default: break;
12392   case X86::COND_A: case X86::COND_AE:
12393   case X86::COND_B: case X86::COND_BE:
12394     NeedCF = true;
12395     break;
12396   case X86::COND_G: case X86::COND_GE:
12397   case X86::COND_L: case X86::COND_LE:
12398   case X86::COND_O: case X86::COND_NO: {
12399     // Check if we really need to set the
12400     // Overflow flag. If NoSignedWrap is present
12401     // that is not actually needed.
12402     switch (Op->getOpcode()) {
12403     case ISD::ADD:
12404     case ISD::SUB:
12405     case ISD::MUL:
12406     case ISD::SHL: {
12407       const BinaryWithFlagsSDNode *BinNode =
12408           cast<BinaryWithFlagsSDNode>(Op.getNode());
12409       if (BinNode->hasNoSignedWrap())
12410         break;
12411     }
12412     default:
12413       NeedOF = true;
12414       break;
12415     }
12416     break;
12417   }
12418   }
12419   // See if we can use the EFLAGS value from the operand instead of
12420   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12421   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12422   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12423     // Emit a CMP with 0, which is the TEST pattern.
12424     //if (Op.getValueType() == MVT::i1)
12425     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12426     //                     DAG.getConstant(0, MVT::i1));
12427     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12428                        DAG.getConstant(0, Op.getValueType()));
12429   }
12430   unsigned Opcode = 0;
12431   unsigned NumOperands = 0;
12432
12433   // Truncate operations may prevent the merge of the SETCC instruction
12434   // and the arithmetic instruction before it. Attempt to truncate the operands
12435   // of the arithmetic instruction and use a reduced bit-width instruction.
12436   bool NeedTruncation = false;
12437   SDValue ArithOp = Op;
12438   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12439     SDValue Arith = Op->getOperand(0);
12440     // Both the trunc and the arithmetic op need to have one user each.
12441     if (Arith->hasOneUse())
12442       switch (Arith.getOpcode()) {
12443         default: break;
12444         case ISD::ADD:
12445         case ISD::SUB:
12446         case ISD::AND:
12447         case ISD::OR:
12448         case ISD::XOR: {
12449           NeedTruncation = true;
12450           ArithOp = Arith;
12451         }
12452       }
12453   }
12454
12455   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12456   // which may be the result of a CAST.  We use the variable 'Op', which is the
12457   // non-casted variable when we check for possible users.
12458   switch (ArithOp.getOpcode()) {
12459   case ISD::ADD:
12460     // Due to an isel shortcoming, be conservative if this add is likely to be
12461     // selected as part of a load-modify-store instruction. When the root node
12462     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12463     // uses of other nodes in the match, such as the ADD in this case. This
12464     // leads to the ADD being left around and reselected, with the result being
12465     // two adds in the output.  Alas, even if none our users are stores, that
12466     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12467     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12468     // climbing the DAG back to the root, and it doesn't seem to be worth the
12469     // effort.
12470     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12471          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12472       if (UI->getOpcode() != ISD::CopyToReg &&
12473           UI->getOpcode() != ISD::SETCC &&
12474           UI->getOpcode() != ISD::STORE)
12475         goto default_case;
12476
12477     if (ConstantSDNode *C =
12478         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12479       // An add of one will be selected as an INC.
12480       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12481         Opcode = X86ISD::INC;
12482         NumOperands = 1;
12483         break;
12484       }
12485
12486       // An add of negative one (subtract of one) will be selected as a DEC.
12487       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12488         Opcode = X86ISD::DEC;
12489         NumOperands = 1;
12490         break;
12491       }
12492     }
12493
12494     // Otherwise use a regular EFLAGS-setting add.
12495     Opcode = X86ISD::ADD;
12496     NumOperands = 2;
12497     break;
12498   case ISD::SHL:
12499   case ISD::SRL:
12500     // If we have a constant logical shift that's only used in a comparison
12501     // against zero turn it into an equivalent AND. This allows turning it into
12502     // a TEST instruction later.
12503     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12504         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12505       EVT VT = Op.getValueType();
12506       unsigned BitWidth = VT.getSizeInBits();
12507       unsigned ShAmt = Op->getConstantOperandVal(1);
12508       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12509         break;
12510       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12511                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12512                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12513       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12514         break;
12515       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12516                                 DAG.getConstant(Mask, VT));
12517       DAG.ReplaceAllUsesWith(Op, New);
12518       Op = New;
12519     }
12520     break;
12521
12522   case ISD::AND:
12523     // If the primary and result isn't used, don't bother using X86ISD::AND,
12524     // because a TEST instruction will be better.
12525     if (!hasNonFlagsUse(Op))
12526       break;
12527     // FALL THROUGH
12528   case ISD::SUB:
12529   case ISD::OR:
12530   case ISD::XOR:
12531     // Due to the ISEL shortcoming noted above, be conservative if this op is
12532     // likely to be selected as part of a load-modify-store instruction.
12533     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12534            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12535       if (UI->getOpcode() == ISD::STORE)
12536         goto default_case;
12537
12538     // Otherwise use a regular EFLAGS-setting instruction.
12539     switch (ArithOp.getOpcode()) {
12540     default: llvm_unreachable("unexpected operator!");
12541     case ISD::SUB: Opcode = X86ISD::SUB; break;
12542     case ISD::XOR: Opcode = X86ISD::XOR; break;
12543     case ISD::AND: Opcode = X86ISD::AND; break;
12544     case ISD::OR: {
12545       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12546         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12547         if (EFLAGS.getNode())
12548           return EFLAGS;
12549       }
12550       Opcode = X86ISD::OR;
12551       break;
12552     }
12553     }
12554
12555     NumOperands = 2;
12556     break;
12557   case X86ISD::ADD:
12558   case X86ISD::SUB:
12559   case X86ISD::INC:
12560   case X86ISD::DEC:
12561   case X86ISD::OR:
12562   case X86ISD::XOR:
12563   case X86ISD::AND:
12564     return SDValue(Op.getNode(), 1);
12565   default:
12566   default_case:
12567     break;
12568   }
12569
12570   // If we found that truncation is beneficial, perform the truncation and
12571   // update 'Op'.
12572   if (NeedTruncation) {
12573     EVT VT = Op.getValueType();
12574     SDValue WideVal = Op->getOperand(0);
12575     EVT WideVT = WideVal.getValueType();
12576     unsigned ConvertedOp = 0;
12577     // Use a target machine opcode to prevent further DAGCombine
12578     // optimizations that may separate the arithmetic operations
12579     // from the setcc node.
12580     switch (WideVal.getOpcode()) {
12581       default: break;
12582       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12583       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12584       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12585       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12586       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12587     }
12588
12589     if (ConvertedOp) {
12590       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12591       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12592         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12593         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12594         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12595       }
12596     }
12597   }
12598
12599   if (Opcode == 0)
12600     // Emit a CMP with 0, which is the TEST pattern.
12601     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12602                        DAG.getConstant(0, Op.getValueType()));
12603
12604   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12605   SmallVector<SDValue, 4> Ops;
12606   for (unsigned i = 0; i != NumOperands; ++i)
12607     Ops.push_back(Op.getOperand(i));
12608
12609   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12610   DAG.ReplaceAllUsesWith(Op, New);
12611   return SDValue(New.getNode(), 1);
12612 }
12613
12614 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12615 /// equivalent.
12616 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12617                                    SDLoc dl, SelectionDAG &DAG) const {
12618   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12619     if (C->getAPIntValue() == 0)
12620       return EmitTest(Op0, X86CC, dl, DAG);
12621
12622      if (Op0.getValueType() == MVT::i1)
12623        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12624   }
12625  
12626   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12627        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12628     // Do the comparison at i32 if it's smaller, besides the Atom case. 
12629     // This avoids subregister aliasing issues. Keep the smaller reference 
12630     // if we're optimizing for size, however, as that'll allow better folding 
12631     // of memory operations.
12632     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12633         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12634              AttributeSet::FunctionIndex, Attribute::MinSize) &&
12635         !Subtarget->isAtom()) {
12636       unsigned ExtendOp =
12637           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12638       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12639       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12640     }
12641     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12642     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12643     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12644                               Op0, Op1);
12645     return SDValue(Sub.getNode(), 1);
12646   }
12647   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12648 }
12649
12650 /// Convert a comparison if required by the subtarget.
12651 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12652                                                  SelectionDAG &DAG) const {
12653   // If the subtarget does not support the FUCOMI instruction, floating-point
12654   // comparisons have to be converted.
12655   if (Subtarget->hasCMov() ||
12656       Cmp.getOpcode() != X86ISD::CMP ||
12657       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12658       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12659     return Cmp;
12660
12661   // The instruction selector will select an FUCOM instruction instead of
12662   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12663   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12664   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12665   SDLoc dl(Cmp);
12666   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12667   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12668   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12669                             DAG.getConstant(8, MVT::i8));
12670   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12671   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12672 }
12673
12674 static bool isAllOnes(SDValue V) {
12675   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12676   return C && C->isAllOnesValue();
12677 }
12678
12679 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12680 /// if it's possible.
12681 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12682                                      SDLoc dl, SelectionDAG &DAG) const {
12683   SDValue Op0 = And.getOperand(0);
12684   SDValue Op1 = And.getOperand(1);
12685   if (Op0.getOpcode() == ISD::TRUNCATE)
12686     Op0 = Op0.getOperand(0);
12687   if (Op1.getOpcode() == ISD::TRUNCATE)
12688     Op1 = Op1.getOperand(0);
12689
12690   SDValue LHS, RHS;
12691   if (Op1.getOpcode() == ISD::SHL)
12692     std::swap(Op0, Op1);
12693   if (Op0.getOpcode() == ISD::SHL) {
12694     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12695       if (And00C->getZExtValue() == 1) {
12696         // If we looked past a truncate, check that it's only truncating away
12697         // known zeros.
12698         unsigned BitWidth = Op0.getValueSizeInBits();
12699         unsigned AndBitWidth = And.getValueSizeInBits();
12700         if (BitWidth > AndBitWidth) {
12701           APInt Zeros, Ones;
12702           DAG.computeKnownBits(Op0, Zeros, Ones);
12703           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12704             return SDValue();
12705         }
12706         LHS = Op1;
12707         RHS = Op0.getOperand(1);
12708       }
12709   } else if (Op1.getOpcode() == ISD::Constant) {
12710     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12711     uint64_t AndRHSVal = AndRHS->getZExtValue();
12712     SDValue AndLHS = Op0;
12713
12714     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12715       LHS = AndLHS.getOperand(0);
12716       RHS = AndLHS.getOperand(1);
12717     }
12718
12719     // Use BT if the immediate can't be encoded in a TEST instruction.
12720     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12721       LHS = AndLHS;
12722       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12723     }
12724   }
12725
12726   if (LHS.getNode()) {
12727     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12728     // instruction.  Since the shift amount is in-range-or-undefined, we know
12729     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12730     // the encoding for the i16 version is larger than the i32 version.
12731     // Also promote i16 to i32 for performance / code size reason.
12732     if (LHS.getValueType() == MVT::i8 ||
12733         LHS.getValueType() == MVT::i16)
12734       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12735
12736     // If the operand types disagree, extend the shift amount to match.  Since
12737     // BT ignores high bits (like shifts) we can use anyextend.
12738     if (LHS.getValueType() != RHS.getValueType())
12739       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12740
12741     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12742     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12743     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12744                        DAG.getConstant(Cond, MVT::i8), BT);
12745   }
12746
12747   return SDValue();
12748 }
12749
12750 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12751 /// mask CMPs.
12752 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12753                               SDValue &Op1) {
12754   unsigned SSECC;
12755   bool Swap = false;
12756
12757   // SSE Condition code mapping:
12758   //  0 - EQ
12759   //  1 - LT
12760   //  2 - LE
12761   //  3 - UNORD
12762   //  4 - NEQ
12763   //  5 - NLT
12764   //  6 - NLE
12765   //  7 - ORD
12766   switch (SetCCOpcode) {
12767   default: llvm_unreachable("Unexpected SETCC condition");
12768   case ISD::SETOEQ:
12769   case ISD::SETEQ:  SSECC = 0; break;
12770   case ISD::SETOGT:
12771   case ISD::SETGT:  Swap = true; // Fallthrough
12772   case ISD::SETLT:
12773   case ISD::SETOLT: SSECC = 1; break;
12774   case ISD::SETOGE:
12775   case ISD::SETGE:  Swap = true; // Fallthrough
12776   case ISD::SETLE:
12777   case ISD::SETOLE: SSECC = 2; break;
12778   case ISD::SETUO:  SSECC = 3; break;
12779   case ISD::SETUNE:
12780   case ISD::SETNE:  SSECC = 4; break;
12781   case ISD::SETULE: Swap = true; // Fallthrough
12782   case ISD::SETUGE: SSECC = 5; break;
12783   case ISD::SETULT: Swap = true; // Fallthrough
12784   case ISD::SETUGT: SSECC = 6; break;
12785   case ISD::SETO:   SSECC = 7; break;
12786   case ISD::SETUEQ:
12787   case ISD::SETONE: SSECC = 8; break;
12788   }
12789   if (Swap)
12790     std::swap(Op0, Op1);
12791
12792   return SSECC;
12793 }
12794
12795 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12796 // ones, and then concatenate the result back.
12797 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12798   MVT VT = Op.getSimpleValueType();
12799
12800   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12801          "Unsupported value type for operation");
12802
12803   unsigned NumElems = VT.getVectorNumElements();
12804   SDLoc dl(Op);
12805   SDValue CC = Op.getOperand(2);
12806
12807   // Extract the LHS vectors
12808   SDValue LHS = Op.getOperand(0);
12809   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12810   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12811
12812   // Extract the RHS vectors
12813   SDValue RHS = Op.getOperand(1);
12814   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12815   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12816
12817   // Issue the operation on the smaller types and concatenate the result back
12818   MVT EltVT = VT.getVectorElementType();
12819   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12820   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12821                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12822                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12823 }
12824
12825 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12826                                      const X86Subtarget *Subtarget) {
12827   SDValue Op0 = Op.getOperand(0);
12828   SDValue Op1 = Op.getOperand(1);
12829   SDValue CC = Op.getOperand(2);
12830   MVT VT = Op.getSimpleValueType();
12831   SDLoc dl(Op);
12832
12833   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12834          Op.getValueType().getScalarType() == MVT::i1 &&
12835          "Cannot set masked compare for this operation");
12836
12837   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12838   unsigned  Opc = 0;
12839   bool Unsigned = false;
12840   bool Swap = false;
12841   unsigned SSECC;
12842   switch (SetCCOpcode) {
12843   default: llvm_unreachable("Unexpected SETCC condition");
12844   case ISD::SETNE:  SSECC = 4; break;
12845   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12846   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12847   case ISD::SETLT:  Swap = true; //fall-through
12848   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12849   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12850   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12851   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12852   case ISD::SETULE: Unsigned = true; //fall-through
12853   case ISD::SETLE:  SSECC = 2; break;
12854   }
12855
12856   if (Swap)
12857     std::swap(Op0, Op1);
12858   if (Opc)
12859     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12860   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12861   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12862                      DAG.getConstant(SSECC, MVT::i8));
12863 }
12864
12865 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12866 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12867 /// return an empty value.
12868 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12869 {
12870   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12871   if (!BV)
12872     return SDValue();
12873
12874   MVT VT = Op1.getSimpleValueType();
12875   MVT EVT = VT.getVectorElementType();
12876   unsigned n = VT.getVectorNumElements();
12877   SmallVector<SDValue, 8> ULTOp1;
12878
12879   for (unsigned i = 0; i < n; ++i) {
12880     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12881     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12882       return SDValue();
12883
12884     // Avoid underflow.
12885     APInt Val = Elt->getAPIntValue();
12886     if (Val == 0)
12887       return SDValue();
12888
12889     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12890   }
12891
12892   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12893 }
12894
12895 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12896                            SelectionDAG &DAG) {
12897   SDValue Op0 = Op.getOperand(0);
12898   SDValue Op1 = Op.getOperand(1);
12899   SDValue CC = Op.getOperand(2);
12900   MVT VT = Op.getSimpleValueType();
12901   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12902   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12903   SDLoc dl(Op);
12904
12905   if (isFP) {
12906 #ifndef NDEBUG
12907     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12908     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12909 #endif
12910
12911     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12912     unsigned Opc = X86ISD::CMPP;
12913     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12914       assert(VT.getVectorNumElements() <= 16);
12915       Opc = X86ISD::CMPM;
12916     }
12917     // In the two special cases we can't handle, emit two comparisons.
12918     if (SSECC == 8) {
12919       unsigned CC0, CC1;
12920       unsigned CombineOpc;
12921       if (SetCCOpcode == ISD::SETUEQ) {
12922         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12923       } else {
12924         assert(SetCCOpcode == ISD::SETONE);
12925         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12926       }
12927
12928       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12929                                  DAG.getConstant(CC0, MVT::i8));
12930       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12931                                  DAG.getConstant(CC1, MVT::i8));
12932       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12933     }
12934     // Handle all other FP comparisons here.
12935     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12936                        DAG.getConstant(SSECC, MVT::i8));
12937   }
12938
12939   // Break 256-bit integer vector compare into smaller ones.
12940   if (VT.is256BitVector() && !Subtarget->hasInt256())
12941     return Lower256IntVSETCC(Op, DAG);
12942
12943   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12944   EVT OpVT = Op1.getValueType();
12945   if (Subtarget->hasAVX512()) {
12946     if (Op1.getValueType().is512BitVector() ||
12947         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12948       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12949
12950     // In AVX-512 architecture setcc returns mask with i1 elements,
12951     // But there is no compare instruction for i8 and i16 elements.
12952     // We are not talking about 512-bit operands in this case, these
12953     // types are illegal.
12954     if (MaskResult &&
12955         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12956          OpVT.getVectorElementType().getSizeInBits() >= 8))
12957       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12958                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12959   }
12960
12961   // We are handling one of the integer comparisons here.  Since SSE only has
12962   // GT and EQ comparisons for integer, swapping operands and multiple
12963   // operations may be required for some comparisons.
12964   unsigned Opc;
12965   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12966   bool Subus = false;
12967
12968   switch (SetCCOpcode) {
12969   default: llvm_unreachable("Unexpected SETCC condition");
12970   case ISD::SETNE:  Invert = true;
12971   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12972   case ISD::SETLT:  Swap = true;
12973   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12974   case ISD::SETGE:  Swap = true;
12975   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12976                     Invert = true; break;
12977   case ISD::SETULT: Swap = true;
12978   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12979                     FlipSigns = true; break;
12980   case ISD::SETUGE: Swap = true;
12981   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12982                     FlipSigns = true; Invert = true; break;
12983   }
12984
12985   // Special case: Use min/max operations for SETULE/SETUGE
12986   MVT VET = VT.getVectorElementType();
12987   bool hasMinMax =
12988        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12989     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12990
12991   if (hasMinMax) {
12992     switch (SetCCOpcode) {
12993     default: break;
12994     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12995     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12996     }
12997
12998     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12999   }
13000
13001   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13002   if (!MinMax && hasSubus) {
13003     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13004     // Op0 u<= Op1:
13005     //   t = psubus Op0, Op1
13006     //   pcmpeq t, <0..0>
13007     switch (SetCCOpcode) {
13008     default: break;
13009     case ISD::SETULT: {
13010       // If the comparison is against a constant we can turn this into a
13011       // setule.  With psubus, setule does not require a swap.  This is
13012       // beneficial because the constant in the register is no longer
13013       // destructed as the destination so it can be hoisted out of a loop.
13014       // Only do this pre-AVX since vpcmp* is no longer destructive.
13015       if (Subtarget->hasAVX())
13016         break;
13017       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13018       if (ULEOp1.getNode()) {
13019         Op1 = ULEOp1;
13020         Subus = true; Invert = false; Swap = false;
13021       }
13022       break;
13023     }
13024     // Psubus is better than flip-sign because it requires no inversion.
13025     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13026     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13027     }
13028
13029     if (Subus) {
13030       Opc = X86ISD::SUBUS;
13031       FlipSigns = false;
13032     }
13033   }
13034
13035   if (Swap)
13036     std::swap(Op0, Op1);
13037
13038   // Check that the operation in question is available (most are plain SSE2,
13039   // but PCMPGTQ and PCMPEQQ have different requirements).
13040   if (VT == MVT::v2i64) {
13041     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13042       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13043
13044       // First cast everything to the right type.
13045       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13046       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13047
13048       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13049       // bits of the inputs before performing those operations. The lower
13050       // compare is always unsigned.
13051       SDValue SB;
13052       if (FlipSigns) {
13053         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13054       } else {
13055         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13056         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13057         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13058                          Sign, Zero, Sign, Zero);
13059       }
13060       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13061       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13062
13063       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13064       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13065       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13066
13067       // Create masks for only the low parts/high parts of the 64 bit integers.
13068       static const int MaskHi[] = { 1, 1, 3, 3 };
13069       static const int MaskLo[] = { 0, 0, 2, 2 };
13070       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13071       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13072       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13073
13074       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13075       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13076
13077       if (Invert)
13078         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13079
13080       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13081     }
13082
13083     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13084       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13085       // pcmpeqd + pshufd + pand.
13086       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13087
13088       // First cast everything to the right type.
13089       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13090       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13091
13092       // Do the compare.
13093       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13094
13095       // Make sure the lower and upper halves are both all-ones.
13096       static const int Mask[] = { 1, 0, 3, 2 };
13097       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13098       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13099
13100       if (Invert)
13101         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13102
13103       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13104     }
13105   }
13106
13107   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13108   // bits of the inputs before performing those operations.
13109   if (FlipSigns) {
13110     EVT EltVT = VT.getVectorElementType();
13111     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13112     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13113     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13114   }
13115
13116   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13117
13118   // If the logical-not of the result is required, perform that now.
13119   if (Invert)
13120     Result = DAG.getNOT(dl, Result, VT);
13121
13122   if (MinMax)
13123     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13124
13125   if (Subus)
13126     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13127                          getZeroVector(VT, Subtarget, DAG, dl));
13128
13129   return Result;
13130 }
13131
13132 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13133
13134   MVT VT = Op.getSimpleValueType();
13135
13136   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13137
13138   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13139          && "SetCC type must be 8-bit or 1-bit integer");
13140   SDValue Op0 = Op.getOperand(0);
13141   SDValue Op1 = Op.getOperand(1);
13142   SDLoc dl(Op);
13143   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13144
13145   // Optimize to BT if possible.
13146   // Lower (X & (1 << N)) == 0 to BT(X, N).
13147   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13148   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13149   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13150       Op1.getOpcode() == ISD::Constant &&
13151       cast<ConstantSDNode>(Op1)->isNullValue() &&
13152       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13153     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13154     if (NewSetCC.getNode())
13155       return NewSetCC;
13156   }
13157
13158   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13159   // these.
13160   if (Op1.getOpcode() == ISD::Constant &&
13161       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13162        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13163       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13164
13165     // If the input is a setcc, then reuse the input setcc or use a new one with
13166     // the inverted condition.
13167     if (Op0.getOpcode() == X86ISD::SETCC) {
13168       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13169       bool Invert = (CC == ISD::SETNE) ^
13170         cast<ConstantSDNode>(Op1)->isNullValue();
13171       if (!Invert)
13172         return Op0;
13173
13174       CCode = X86::GetOppositeBranchCondition(CCode);
13175       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13176                                   DAG.getConstant(CCode, MVT::i8),
13177                                   Op0.getOperand(1));
13178       if (VT == MVT::i1)
13179         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13180       return SetCC;
13181     }
13182   }
13183   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13184       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13185       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13186
13187     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13188     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13189   }
13190
13191   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13192   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13193   if (X86CC == X86::COND_INVALID)
13194     return SDValue();
13195
13196   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13197   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13198   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13199                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13200   if (VT == MVT::i1)
13201     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13202   return SetCC;
13203 }
13204
13205 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13206 static bool isX86LogicalCmp(SDValue Op) {
13207   unsigned Opc = Op.getNode()->getOpcode();
13208   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13209       Opc == X86ISD::SAHF)
13210     return true;
13211   if (Op.getResNo() == 1 &&
13212       (Opc == X86ISD::ADD ||
13213        Opc == X86ISD::SUB ||
13214        Opc == X86ISD::ADC ||
13215        Opc == X86ISD::SBB ||
13216        Opc == X86ISD::SMUL ||
13217        Opc == X86ISD::UMUL ||
13218        Opc == X86ISD::INC ||
13219        Opc == X86ISD::DEC ||
13220        Opc == X86ISD::OR ||
13221        Opc == X86ISD::XOR ||
13222        Opc == X86ISD::AND))
13223     return true;
13224
13225   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13226     return true;
13227
13228   return false;
13229 }
13230
13231 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13232   if (V.getOpcode() != ISD::TRUNCATE)
13233     return false;
13234
13235   SDValue VOp0 = V.getOperand(0);
13236   unsigned InBits = VOp0.getValueSizeInBits();
13237   unsigned Bits = V.getValueSizeInBits();
13238   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13239 }
13240
13241 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13242   bool addTest = true;
13243   SDValue Cond  = Op.getOperand(0);
13244   SDValue Op1 = Op.getOperand(1);
13245   SDValue Op2 = Op.getOperand(2);
13246   SDLoc DL(Op);
13247   EVT VT = Op1.getValueType();
13248   SDValue CC;
13249
13250   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13251   // are available. Otherwise fp cmovs get lowered into a less efficient branch
13252   // sequence later on.
13253   if (Cond.getOpcode() == ISD::SETCC &&
13254       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13255        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13256       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13257     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13258     int SSECC = translateX86FSETCC(
13259         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13260
13261     if (SSECC != 8) {
13262       if (Subtarget->hasAVX512()) {
13263         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13264                                   DAG.getConstant(SSECC, MVT::i8));
13265         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13266       }
13267       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13268                                 DAG.getConstant(SSECC, MVT::i8));
13269       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13270       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13271       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13272     }
13273   }
13274
13275   if (Cond.getOpcode() == ISD::SETCC) {
13276     SDValue NewCond = LowerSETCC(Cond, DAG);
13277     if (NewCond.getNode())
13278       Cond = NewCond;
13279   }
13280
13281   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13282   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13283   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13284   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13285   if (Cond.getOpcode() == X86ISD::SETCC &&
13286       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13287       isZero(Cond.getOperand(1).getOperand(1))) {
13288     SDValue Cmp = Cond.getOperand(1);
13289
13290     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13291
13292     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13293         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13294       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13295
13296       SDValue CmpOp0 = Cmp.getOperand(0);
13297       // Apply further optimizations for special cases
13298       // (select (x != 0), -1, 0) -> neg & sbb
13299       // (select (x == 0), 0, -1) -> neg & sbb
13300       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13301         if (YC->isNullValue() &&
13302             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13303           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13304           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13305                                     DAG.getConstant(0, CmpOp0.getValueType()),
13306                                     CmpOp0);
13307           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13308                                     DAG.getConstant(X86::COND_B, MVT::i8),
13309                                     SDValue(Neg.getNode(), 1));
13310           return Res;
13311         }
13312
13313       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13314                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13315       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13316
13317       SDValue Res =   // Res = 0 or -1.
13318         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13319                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13320
13321       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13322         Res = DAG.getNOT(DL, Res, Res.getValueType());
13323
13324       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13325       if (!N2C || !N2C->isNullValue())
13326         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13327       return Res;
13328     }
13329   }
13330
13331   // Look past (and (setcc_carry (cmp ...)), 1).
13332   if (Cond.getOpcode() == ISD::AND &&
13333       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13334     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13335     if (C && C->getAPIntValue() == 1)
13336       Cond = Cond.getOperand(0);
13337   }
13338
13339   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13340   // setting operand in place of the X86ISD::SETCC.
13341   unsigned CondOpcode = Cond.getOpcode();
13342   if (CondOpcode == X86ISD::SETCC ||
13343       CondOpcode == X86ISD::SETCC_CARRY) {
13344     CC = Cond.getOperand(0);
13345
13346     SDValue Cmp = Cond.getOperand(1);
13347     unsigned Opc = Cmp.getOpcode();
13348     MVT VT = Op.getSimpleValueType();
13349
13350     bool IllegalFPCMov = false;
13351     if (VT.isFloatingPoint() && !VT.isVector() &&
13352         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13353       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13354
13355     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13356         Opc == X86ISD::BT) { // FIXME
13357       Cond = Cmp;
13358       addTest = false;
13359     }
13360   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13361              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13362              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13363               Cond.getOperand(0).getValueType() != MVT::i8)) {
13364     SDValue LHS = Cond.getOperand(0);
13365     SDValue RHS = Cond.getOperand(1);
13366     unsigned X86Opcode;
13367     unsigned X86Cond;
13368     SDVTList VTs;
13369     switch (CondOpcode) {
13370     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13371     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13372     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13373     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13374     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13375     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13376     default: llvm_unreachable("unexpected overflowing operator");
13377     }
13378     if (CondOpcode == ISD::UMULO)
13379       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13380                           MVT::i32);
13381     else
13382       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13383
13384     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13385
13386     if (CondOpcode == ISD::UMULO)
13387       Cond = X86Op.getValue(2);
13388     else
13389       Cond = X86Op.getValue(1);
13390
13391     CC = DAG.getConstant(X86Cond, MVT::i8);
13392     addTest = false;
13393   }
13394
13395   if (addTest) {
13396     // Look pass the truncate if the high bits are known zero.
13397     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13398         Cond = Cond.getOperand(0);
13399
13400     // We know the result of AND is compared against zero. Try to match
13401     // it to BT.
13402     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13403       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13404       if (NewSetCC.getNode()) {
13405         CC = NewSetCC.getOperand(0);
13406         Cond = NewSetCC.getOperand(1);
13407         addTest = false;
13408       }
13409     }
13410   }
13411
13412   if (addTest) {
13413     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13414     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13415   }
13416
13417   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13418   // a <  b ?  0 : -1 -> RES = setcc_carry
13419   // a >= b ? -1 :  0 -> RES = setcc_carry
13420   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13421   if (Cond.getOpcode() == X86ISD::SUB) {
13422     Cond = ConvertCmpIfNecessary(Cond, DAG);
13423     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13424
13425     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13426         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13427       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13428                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13429       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13430         return DAG.getNOT(DL, Res, Res.getValueType());
13431       return Res;
13432     }
13433   }
13434
13435   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13436   // widen the cmov and push the truncate through. This avoids introducing a new
13437   // branch during isel and doesn't add any extensions.
13438   if (Op.getValueType() == MVT::i8 &&
13439       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13440     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13441     if (T1.getValueType() == T2.getValueType() &&
13442         // Blacklist CopyFromReg to avoid partial register stalls.
13443         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13444       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13445       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13446       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13447     }
13448   }
13449
13450   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13451   // condition is true.
13452   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13453   SDValue Ops[] = { Op2, Op1, CC, Cond };
13454   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13455 }
13456
13457 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13458   MVT VT = Op->getSimpleValueType(0);
13459   SDValue In = Op->getOperand(0);
13460   MVT InVT = In.getSimpleValueType();
13461   SDLoc dl(Op);
13462
13463   unsigned int NumElts = VT.getVectorNumElements();
13464   if (NumElts != 8 && NumElts != 16)
13465     return SDValue();
13466
13467   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13468     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13469
13470   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13471   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13472
13473   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13474   Constant *C = ConstantInt::get(*DAG.getContext(),
13475     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13476
13477   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13478   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13479   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13480                           MachinePointerInfo::getConstantPool(),
13481                           false, false, false, Alignment);
13482   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13483   if (VT.is512BitVector())
13484     return Brcst;
13485   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13486 }
13487
13488 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13489                                 SelectionDAG &DAG) {
13490   MVT VT = Op->getSimpleValueType(0);
13491   SDValue In = Op->getOperand(0);
13492   MVT InVT = In.getSimpleValueType();
13493   SDLoc dl(Op);
13494
13495   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13496     return LowerSIGN_EXTEND_AVX512(Op, DAG);
13497
13498   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13499       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13500       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13501     return SDValue();
13502
13503   if (Subtarget->hasInt256())
13504     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13505
13506   // Optimize vectors in AVX mode
13507   // Sign extend  v8i16 to v8i32 and
13508   //              v4i32 to v4i64
13509   //
13510   // Divide input vector into two parts
13511   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13512   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13513   // concat the vectors to original VT
13514
13515   unsigned NumElems = InVT.getVectorNumElements();
13516   SDValue Undef = DAG.getUNDEF(InVT);
13517
13518   SmallVector<int,8> ShufMask1(NumElems, -1);
13519   for (unsigned i = 0; i != NumElems/2; ++i)
13520     ShufMask1[i] = i;
13521
13522   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13523
13524   SmallVector<int,8> ShufMask2(NumElems, -1);
13525   for (unsigned i = 0; i != NumElems/2; ++i)
13526     ShufMask2[i] = i + NumElems/2;
13527
13528   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13529
13530   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13531                                 VT.getVectorNumElements()/2);
13532
13533   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13534   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13535
13536   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13537 }
13538
13539 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13540 // may emit an illegal shuffle but the expansion is still better than scalar
13541 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13542 // we'll emit a shuffle and a arithmetic shift.
13543 // TODO: It is possible to support ZExt by zeroing the undef values during
13544 // the shuffle phase or after the shuffle.
13545 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13546                                  SelectionDAG &DAG) {
13547   MVT RegVT = Op.getSimpleValueType();
13548   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13549   assert(RegVT.isInteger() &&
13550          "We only custom lower integer vector sext loads.");
13551
13552   // Nothing useful we can do without SSE2 shuffles.
13553   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13554
13555   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13556   SDLoc dl(Ld);
13557   EVT MemVT = Ld->getMemoryVT();
13558   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13559   unsigned RegSz = RegVT.getSizeInBits();
13560
13561   ISD::LoadExtType Ext = Ld->getExtensionType();
13562
13563   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13564          && "Only anyext and sext are currently implemented.");
13565   assert(MemVT != RegVT && "Cannot extend to the same type");
13566   assert(MemVT.isVector() && "Must load a vector from memory");
13567
13568   unsigned NumElems = RegVT.getVectorNumElements();
13569   unsigned MemSz = MemVT.getSizeInBits();
13570   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13571
13572   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13573     // The only way in which we have a legal 256-bit vector result but not the
13574     // integer 256-bit operations needed to directly lower a sextload is if we
13575     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13576     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13577     // correctly legalized. We do this late to allow the canonical form of
13578     // sextload to persist throughout the rest of the DAG combiner -- it wants
13579     // to fold together any extensions it can, and so will fuse a sign_extend
13580     // of an sextload into a sextload targeting a wider value.
13581     SDValue Load;
13582     if (MemSz == 128) {
13583       // Just switch this to a normal load.
13584       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13585                                        "it must be a legal 128-bit vector "
13586                                        "type!");
13587       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13588                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13589                   Ld->isInvariant(), Ld->getAlignment());
13590     } else {
13591       assert(MemSz < 128 &&
13592              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13593       // Do an sext load to a 128-bit vector type. We want to use the same
13594       // number of elements, but elements half as wide. This will end up being
13595       // recursively lowered by this routine, but will succeed as we definitely
13596       // have all the necessary features if we're using AVX1.
13597       EVT HalfEltVT =
13598           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13599       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13600       Load =
13601           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13602                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13603                          Ld->isNonTemporal(), Ld->isInvariant(),
13604                          Ld->getAlignment());
13605     }
13606
13607     // Replace chain users with the new chain.
13608     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13609     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13610
13611     // Finally, do a normal sign-extend to the desired register.
13612     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13613   }
13614
13615   // All sizes must be a power of two.
13616   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13617          "Non-power-of-two elements are not custom lowered!");
13618
13619   // Attempt to load the original value using scalar loads.
13620   // Find the largest scalar type that divides the total loaded size.
13621   MVT SclrLoadTy = MVT::i8;
13622   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13623        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13624     MVT Tp = (MVT::SimpleValueType)tp;
13625     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13626       SclrLoadTy = Tp;
13627     }
13628   }
13629
13630   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13631   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13632       (64 <= MemSz))
13633     SclrLoadTy = MVT::f64;
13634
13635   // Calculate the number of scalar loads that we need to perform
13636   // in order to load our vector from memory.
13637   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13638
13639   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13640          "Can only lower sext loads with a single scalar load!");
13641
13642   unsigned loadRegZize = RegSz;
13643   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13644     loadRegZize /= 2;
13645
13646   // Represent our vector as a sequence of elements which are the
13647   // largest scalar that we can load.
13648   EVT LoadUnitVecVT = EVT::getVectorVT(
13649       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13650
13651   // Represent the data using the same element type that is stored in
13652   // memory. In practice, we ''widen'' MemVT.
13653   EVT WideVecVT =
13654       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13655                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13656
13657   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13658          "Invalid vector type");
13659
13660   // We can't shuffle using an illegal type.
13661   assert(TLI.isTypeLegal(WideVecVT) &&
13662          "We only lower types that form legal widened vector types");
13663
13664   SmallVector<SDValue, 8> Chains;
13665   SDValue Ptr = Ld->getBasePtr();
13666   SDValue Increment =
13667       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13668   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13669
13670   for (unsigned i = 0; i < NumLoads; ++i) {
13671     // Perform a single load.
13672     SDValue ScalarLoad =
13673         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13674                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13675                     Ld->getAlignment());
13676     Chains.push_back(ScalarLoad.getValue(1));
13677     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13678     // another round of DAGCombining.
13679     if (i == 0)
13680       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13681     else
13682       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13683                         ScalarLoad, DAG.getIntPtrConstant(i));
13684
13685     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13686   }
13687
13688   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13689
13690   // Bitcast the loaded value to a vector of the original element type, in
13691   // the size of the target vector type.
13692   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13693   unsigned SizeRatio = RegSz / MemSz;
13694
13695   if (Ext == ISD::SEXTLOAD) {
13696     // If we have SSE4.1, we can directly emit a VSEXT node.
13697     if (Subtarget->hasSSE41()) {
13698       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13699       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13700       return Sext;
13701     }
13702
13703     // Otherwise we'll shuffle the small elements in the high bits of the
13704     // larger type and perform an arithmetic shift. If the shift is not legal
13705     // it's better to scalarize.
13706     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13707            "We can't implement a sext load without an arithmetic right shift!");
13708
13709     // Redistribute the loaded elements into the different locations.
13710     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13711     for (unsigned i = 0; i != NumElems; ++i)
13712       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13713
13714     SDValue Shuff = DAG.getVectorShuffle(
13715         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13716
13717     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13718
13719     // Build the arithmetic shift.
13720     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13721                    MemVT.getVectorElementType().getSizeInBits();
13722     Shuff =
13723         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13724
13725     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13726     return Shuff;
13727   }
13728
13729   // Redistribute the loaded elements into the different locations.
13730   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13731   for (unsigned i = 0; i != NumElems; ++i)
13732     ShuffleVec[i * SizeRatio] = i;
13733
13734   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13735                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13736
13737   // Bitcast to the requested type.
13738   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13739   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13740   return Shuff;
13741 }
13742
13743 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13744 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13745 // from the AND / OR.
13746 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13747   Opc = Op.getOpcode();
13748   if (Opc != ISD::OR && Opc != ISD::AND)
13749     return false;
13750   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13751           Op.getOperand(0).hasOneUse() &&
13752           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13753           Op.getOperand(1).hasOneUse());
13754 }
13755
13756 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13757 // 1 and that the SETCC node has a single use.
13758 static bool isXor1OfSetCC(SDValue Op) {
13759   if (Op.getOpcode() != ISD::XOR)
13760     return false;
13761   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13762   if (N1C && N1C->getAPIntValue() == 1) {
13763     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13764       Op.getOperand(0).hasOneUse();
13765   }
13766   return false;
13767 }
13768
13769 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13770   bool addTest = true;
13771   SDValue Chain = Op.getOperand(0);
13772   SDValue Cond  = Op.getOperand(1);
13773   SDValue Dest  = Op.getOperand(2);
13774   SDLoc dl(Op);
13775   SDValue CC;
13776   bool Inverted = false;
13777
13778   if (Cond.getOpcode() == ISD::SETCC) {
13779     // Check for setcc([su]{add,sub,mul}o == 0).
13780     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13781         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13782         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13783         Cond.getOperand(0).getResNo() == 1 &&
13784         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13785          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13786          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13787          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13788          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13789          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13790       Inverted = true;
13791       Cond = Cond.getOperand(0);
13792     } else {
13793       SDValue NewCond = LowerSETCC(Cond, DAG);
13794       if (NewCond.getNode())
13795         Cond = NewCond;
13796     }
13797   }
13798 #if 0
13799   // FIXME: LowerXALUO doesn't handle these!!
13800   else if (Cond.getOpcode() == X86ISD::ADD  ||
13801            Cond.getOpcode() == X86ISD::SUB  ||
13802            Cond.getOpcode() == X86ISD::SMUL ||
13803            Cond.getOpcode() == X86ISD::UMUL)
13804     Cond = LowerXALUO(Cond, DAG);
13805 #endif
13806
13807   // Look pass (and (setcc_carry (cmp ...)), 1).
13808   if (Cond.getOpcode() == ISD::AND &&
13809       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13810     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13811     if (C && C->getAPIntValue() == 1)
13812       Cond = Cond.getOperand(0);
13813   }
13814
13815   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13816   // setting operand in place of the X86ISD::SETCC.
13817   unsigned CondOpcode = Cond.getOpcode();
13818   if (CondOpcode == X86ISD::SETCC ||
13819       CondOpcode == X86ISD::SETCC_CARRY) {
13820     CC = Cond.getOperand(0);
13821
13822     SDValue Cmp = Cond.getOperand(1);
13823     unsigned Opc = Cmp.getOpcode();
13824     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13825     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13826       Cond = Cmp;
13827       addTest = false;
13828     } else {
13829       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13830       default: break;
13831       case X86::COND_O:
13832       case X86::COND_B:
13833         // These can only come from an arithmetic instruction with overflow,
13834         // e.g. SADDO, UADDO.
13835         Cond = Cond.getNode()->getOperand(1);
13836         addTest = false;
13837         break;
13838       }
13839     }
13840   }
13841   CondOpcode = Cond.getOpcode();
13842   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13843       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13844       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13845        Cond.getOperand(0).getValueType() != MVT::i8)) {
13846     SDValue LHS = Cond.getOperand(0);
13847     SDValue RHS = Cond.getOperand(1);
13848     unsigned X86Opcode;
13849     unsigned X86Cond;
13850     SDVTList VTs;
13851     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13852     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13853     // X86ISD::INC).
13854     switch (CondOpcode) {
13855     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13856     case ISD::SADDO:
13857       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13858         if (C->isOne()) {
13859           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13860           break;
13861         }
13862       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13863     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13864     case ISD::SSUBO:
13865       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13866         if (C->isOne()) {
13867           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13868           break;
13869         }
13870       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13871     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13872     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13873     default: llvm_unreachable("unexpected overflowing operator");
13874     }
13875     if (Inverted)
13876       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13877     if (CondOpcode == ISD::UMULO)
13878       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13879                           MVT::i32);
13880     else
13881       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13882
13883     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13884
13885     if (CondOpcode == ISD::UMULO)
13886       Cond = X86Op.getValue(2);
13887     else
13888       Cond = X86Op.getValue(1);
13889
13890     CC = DAG.getConstant(X86Cond, MVT::i8);
13891     addTest = false;
13892   } else {
13893     unsigned CondOpc;
13894     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13895       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13896       if (CondOpc == ISD::OR) {
13897         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13898         // two branches instead of an explicit OR instruction with a
13899         // separate test.
13900         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13901             isX86LogicalCmp(Cmp)) {
13902           CC = Cond.getOperand(0).getOperand(0);
13903           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13904                               Chain, Dest, CC, Cmp);
13905           CC = Cond.getOperand(1).getOperand(0);
13906           Cond = Cmp;
13907           addTest = false;
13908         }
13909       } else { // ISD::AND
13910         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13911         // two branches instead of an explicit AND instruction with a
13912         // separate test. However, we only do this if this block doesn't
13913         // have a fall-through edge, because this requires an explicit
13914         // jmp when the condition is false.
13915         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13916             isX86LogicalCmp(Cmp) &&
13917             Op.getNode()->hasOneUse()) {
13918           X86::CondCode CCode =
13919             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13920           CCode = X86::GetOppositeBranchCondition(CCode);
13921           CC = DAG.getConstant(CCode, MVT::i8);
13922           SDNode *User = *Op.getNode()->use_begin();
13923           // Look for an unconditional branch following this conditional branch.
13924           // We need this because we need to reverse the successors in order
13925           // to implement FCMP_OEQ.
13926           if (User->getOpcode() == ISD::BR) {
13927             SDValue FalseBB = User->getOperand(1);
13928             SDNode *NewBR =
13929               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13930             assert(NewBR == User);
13931             (void)NewBR;
13932             Dest = FalseBB;
13933
13934             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13935                                 Chain, Dest, CC, Cmp);
13936             X86::CondCode CCode =
13937               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13938             CCode = X86::GetOppositeBranchCondition(CCode);
13939             CC = DAG.getConstant(CCode, MVT::i8);
13940             Cond = Cmp;
13941             addTest = false;
13942           }
13943         }
13944       }
13945     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13946       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13947       // It should be transformed during dag combiner except when the condition
13948       // is set by a arithmetics with overflow node.
13949       X86::CondCode CCode =
13950         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13951       CCode = X86::GetOppositeBranchCondition(CCode);
13952       CC = DAG.getConstant(CCode, MVT::i8);
13953       Cond = Cond.getOperand(0).getOperand(1);
13954       addTest = false;
13955     } else if (Cond.getOpcode() == ISD::SETCC &&
13956                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13957       // For FCMP_OEQ, we can emit
13958       // two branches instead of an explicit AND instruction with a
13959       // separate test. However, we only do this if this block doesn't
13960       // have a fall-through edge, because this requires an explicit
13961       // jmp when the condition is false.
13962       if (Op.getNode()->hasOneUse()) {
13963         SDNode *User = *Op.getNode()->use_begin();
13964         // Look for an unconditional branch following this conditional branch.
13965         // We need this because we need to reverse the successors in order
13966         // to implement FCMP_OEQ.
13967         if (User->getOpcode() == ISD::BR) {
13968           SDValue FalseBB = User->getOperand(1);
13969           SDNode *NewBR =
13970             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13971           assert(NewBR == User);
13972           (void)NewBR;
13973           Dest = FalseBB;
13974
13975           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13976                                     Cond.getOperand(0), Cond.getOperand(1));
13977           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13978           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13979           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13980                               Chain, Dest, CC, Cmp);
13981           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13982           Cond = Cmp;
13983           addTest = false;
13984         }
13985       }
13986     } else if (Cond.getOpcode() == ISD::SETCC &&
13987                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13988       // For FCMP_UNE, we can emit
13989       // two branches instead of an explicit AND instruction with a
13990       // separate test. However, we only do this if this block doesn't
13991       // have a fall-through edge, because this requires an explicit
13992       // jmp when the condition is false.
13993       if (Op.getNode()->hasOneUse()) {
13994         SDNode *User = *Op.getNode()->use_begin();
13995         // Look for an unconditional branch following this conditional branch.
13996         // We need this because we need to reverse the successors in order
13997         // to implement FCMP_UNE.
13998         if (User->getOpcode() == ISD::BR) {
13999           SDValue FalseBB = User->getOperand(1);
14000           SDNode *NewBR =
14001             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14002           assert(NewBR == User);
14003           (void)NewBR;
14004
14005           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14006                                     Cond.getOperand(0), Cond.getOperand(1));
14007           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14008           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14009           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14010                               Chain, Dest, CC, Cmp);
14011           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14012           Cond = Cmp;
14013           addTest = false;
14014           Dest = FalseBB;
14015         }
14016       }
14017     }
14018   }
14019
14020   if (addTest) {
14021     // Look pass the truncate if the high bits are known zero.
14022     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14023         Cond = Cond.getOperand(0);
14024
14025     // We know the result of AND is compared against zero. Try to match
14026     // it to BT.
14027     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14028       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14029       if (NewSetCC.getNode()) {
14030         CC = NewSetCC.getOperand(0);
14031         Cond = NewSetCC.getOperand(1);
14032         addTest = false;
14033       }
14034     }
14035   }
14036
14037   if (addTest) {
14038     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14039     CC = DAG.getConstant(X86Cond, MVT::i8);
14040     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14041   }
14042   Cond = ConvertCmpIfNecessary(Cond, DAG);
14043   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14044                      Chain, Dest, CC, Cond);
14045 }
14046
14047 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14048 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14049 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14050 // that the guard pages used by the OS virtual memory manager are allocated in
14051 // correct sequence.
14052 SDValue
14053 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14054                                            SelectionDAG &DAG) const {
14055   MachineFunction &MF = DAG.getMachineFunction();
14056   bool SplitStack = MF.shouldSplitStack();
14057   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
14058                SplitStack;
14059   SDLoc dl(Op);
14060
14061   if (!Lower) {
14062     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14063     SDNode* Node = Op.getNode();
14064
14065     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14066     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14067         " not tell us which reg is the stack pointer!");
14068     EVT VT = Node->getValueType(0);
14069     SDValue Tmp1 = SDValue(Node, 0);
14070     SDValue Tmp2 = SDValue(Node, 1);
14071     SDValue Tmp3 = Node->getOperand(2);
14072     SDValue Chain = Tmp1.getOperand(0);
14073
14074     // Chain the dynamic stack allocation so that it doesn't modify the stack
14075     // pointer when other instructions are using the stack.
14076     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14077         SDLoc(Node));
14078
14079     SDValue Size = Tmp2.getOperand(1);
14080     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14081     Chain = SP.getValue(1);
14082     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14083     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
14084     unsigned StackAlign = TFI.getStackAlignment();
14085     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14086     if (Align > StackAlign)
14087       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14088           DAG.getConstant(-(uint64_t)Align, VT));
14089     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14090
14091     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14092         DAG.getIntPtrConstant(0, true), SDValue(),
14093         SDLoc(Node));
14094
14095     SDValue Ops[2] = { Tmp1, Tmp2 };
14096     return DAG.getMergeValues(Ops, dl);
14097   }
14098
14099   // Get the inputs.
14100   SDValue Chain = Op.getOperand(0);
14101   SDValue Size  = Op.getOperand(1);
14102   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14103   EVT VT = Op.getNode()->getValueType(0);
14104
14105   bool Is64Bit = Subtarget->is64Bit();
14106   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
14107
14108   if (SplitStack) {
14109     MachineRegisterInfo &MRI = MF.getRegInfo();
14110
14111     if (Is64Bit) {
14112       // The 64 bit implementation of segmented stacks needs to clobber both r10
14113       // r11. This makes it impossible to use it along with nested parameters.
14114       const Function *F = MF.getFunction();
14115
14116       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14117            I != E; ++I)
14118         if (I->hasNestAttr())
14119           report_fatal_error("Cannot use segmented stacks with functions that "
14120                              "have nested arguments.");
14121     }
14122
14123     const TargetRegisterClass *AddrRegClass =
14124       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
14125     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14126     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14127     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14128                                 DAG.getRegister(Vreg, SPTy));
14129     SDValue Ops1[2] = { Value, Chain };
14130     return DAG.getMergeValues(Ops1, dl);
14131   } else {
14132     SDValue Flag;
14133     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
14134
14135     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14136     Flag = Chain.getValue(1);
14137     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14138
14139     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14140
14141     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
14142         DAG.getSubtarget().getRegisterInfo());
14143     unsigned SPReg = RegInfo->getStackRegister();
14144     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14145     Chain = SP.getValue(1);
14146
14147     if (Align) {
14148       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14149                        DAG.getConstant(-(uint64_t)Align, VT));
14150       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14151     }
14152
14153     SDValue Ops1[2] = { SP, Chain };
14154     return DAG.getMergeValues(Ops1, dl);
14155   }
14156 }
14157
14158 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14159   MachineFunction &MF = DAG.getMachineFunction();
14160   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14161
14162   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14163   SDLoc DL(Op);
14164
14165   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14166     // vastart just stores the address of the VarArgsFrameIndex slot into the
14167     // memory location argument.
14168     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14169                                    getPointerTy());
14170     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14171                         MachinePointerInfo(SV), false, false, 0);
14172   }
14173
14174   // __va_list_tag:
14175   //   gp_offset         (0 - 6 * 8)
14176   //   fp_offset         (48 - 48 + 8 * 16)
14177   //   overflow_arg_area (point to parameters coming in memory).
14178   //   reg_save_area
14179   SmallVector<SDValue, 8> MemOps;
14180   SDValue FIN = Op.getOperand(1);
14181   // Store gp_offset
14182   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14183                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14184                                                MVT::i32),
14185                                FIN, MachinePointerInfo(SV), false, false, 0);
14186   MemOps.push_back(Store);
14187
14188   // Store fp_offset
14189   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14190                     FIN, DAG.getIntPtrConstant(4));
14191   Store = DAG.getStore(Op.getOperand(0), DL,
14192                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14193                                        MVT::i32),
14194                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14195   MemOps.push_back(Store);
14196
14197   // Store ptr to overflow_arg_area
14198   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14199                     FIN, DAG.getIntPtrConstant(4));
14200   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14201                                     getPointerTy());
14202   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14203                        MachinePointerInfo(SV, 8),
14204                        false, false, 0);
14205   MemOps.push_back(Store);
14206
14207   // Store ptr to reg_save_area.
14208   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14209                     FIN, DAG.getIntPtrConstant(8));
14210   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14211                                     getPointerTy());
14212   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14213                        MachinePointerInfo(SV, 16), false, false, 0);
14214   MemOps.push_back(Store);
14215   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14216 }
14217
14218 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14219   assert(Subtarget->is64Bit() &&
14220          "LowerVAARG only handles 64-bit va_arg!");
14221   assert((Subtarget->isTargetLinux() ||
14222           Subtarget->isTargetDarwin()) &&
14223           "Unhandled target in LowerVAARG");
14224   assert(Op.getNode()->getNumOperands() == 4);
14225   SDValue Chain = Op.getOperand(0);
14226   SDValue SrcPtr = Op.getOperand(1);
14227   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14228   unsigned Align = Op.getConstantOperandVal(3);
14229   SDLoc dl(Op);
14230
14231   EVT ArgVT = Op.getNode()->getValueType(0);
14232   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14233   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14234   uint8_t ArgMode;
14235
14236   // Decide which area this value should be read from.
14237   // TODO: Implement the AMD64 ABI in its entirety. This simple
14238   // selection mechanism works only for the basic types.
14239   if (ArgVT == MVT::f80) {
14240     llvm_unreachable("va_arg for f80 not yet implemented");
14241   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14242     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14243   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14244     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14245   } else {
14246     llvm_unreachable("Unhandled argument type in LowerVAARG");
14247   }
14248
14249   if (ArgMode == 2) {
14250     // Sanity Check: Make sure using fp_offset makes sense.
14251     assert(!DAG.getTarget().Options.UseSoftFloat &&
14252            !(DAG.getMachineFunction()
14253                 .getFunction()->getAttributes()
14254                 .hasAttribute(AttributeSet::FunctionIndex,
14255                               Attribute::NoImplicitFloat)) &&
14256            Subtarget->hasSSE1());
14257   }
14258
14259   // Insert VAARG_64 node into the DAG
14260   // VAARG_64 returns two values: Variable Argument Address, Chain
14261   SmallVector<SDValue, 11> InstOps;
14262   InstOps.push_back(Chain);
14263   InstOps.push_back(SrcPtr);
14264   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
14265   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
14266   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
14267   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14268   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14269                                           VTs, InstOps, MVT::i64,
14270                                           MachinePointerInfo(SV),
14271                                           /*Align=*/0,
14272                                           /*Volatile=*/false,
14273                                           /*ReadMem=*/true,
14274                                           /*WriteMem=*/true);
14275   Chain = VAARG.getValue(1);
14276
14277   // Load the next argument and return it
14278   return DAG.getLoad(ArgVT, dl,
14279                      Chain,
14280                      VAARG,
14281                      MachinePointerInfo(),
14282                      false, false, false, 0);
14283 }
14284
14285 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14286                            SelectionDAG &DAG) {
14287   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14288   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14289   SDValue Chain = Op.getOperand(0);
14290   SDValue DstPtr = Op.getOperand(1);
14291   SDValue SrcPtr = Op.getOperand(2);
14292   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14293   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14294   SDLoc DL(Op);
14295
14296   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14297                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14298                        false,
14299                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14300 }
14301
14302 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14303 // amount is a constant. Takes immediate version of shift as input.
14304 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14305                                           SDValue SrcOp, uint64_t ShiftAmt,
14306                                           SelectionDAG &DAG) {
14307   MVT ElementType = VT.getVectorElementType();
14308
14309   // Fold this packed shift into its first operand if ShiftAmt is 0.
14310   if (ShiftAmt == 0)
14311     return SrcOp;
14312
14313   // Check for ShiftAmt >= element width
14314   if (ShiftAmt >= ElementType.getSizeInBits()) {
14315     if (Opc == X86ISD::VSRAI)
14316       ShiftAmt = ElementType.getSizeInBits() - 1;
14317     else
14318       return DAG.getConstant(0, VT);
14319   }
14320
14321   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14322          && "Unknown target vector shift-by-constant node");
14323
14324   // Fold this packed vector shift into a build vector if SrcOp is a
14325   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14326   if (VT == SrcOp.getSimpleValueType() &&
14327       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14328     SmallVector<SDValue, 8> Elts;
14329     unsigned NumElts = SrcOp->getNumOperands();
14330     ConstantSDNode *ND;
14331
14332     switch(Opc) {
14333     default: llvm_unreachable(nullptr);
14334     case X86ISD::VSHLI:
14335       for (unsigned i=0; i!=NumElts; ++i) {
14336         SDValue CurrentOp = SrcOp->getOperand(i);
14337         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14338           Elts.push_back(CurrentOp);
14339           continue;
14340         }
14341         ND = cast<ConstantSDNode>(CurrentOp);
14342         const APInt &C = ND->getAPIntValue();
14343         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14344       }
14345       break;
14346     case X86ISD::VSRLI:
14347       for (unsigned i=0; i!=NumElts; ++i) {
14348         SDValue CurrentOp = SrcOp->getOperand(i);
14349         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14350           Elts.push_back(CurrentOp);
14351           continue;
14352         }
14353         ND = cast<ConstantSDNode>(CurrentOp);
14354         const APInt &C = ND->getAPIntValue();
14355         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14356       }
14357       break;
14358     case X86ISD::VSRAI:
14359       for (unsigned i=0; i!=NumElts; ++i) {
14360         SDValue CurrentOp = SrcOp->getOperand(i);
14361         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14362           Elts.push_back(CurrentOp);
14363           continue;
14364         }
14365         ND = cast<ConstantSDNode>(CurrentOp);
14366         const APInt &C = ND->getAPIntValue();
14367         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14368       }
14369       break;
14370     }
14371
14372     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14373   }
14374
14375   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14376 }
14377
14378 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14379 // may or may not be a constant. Takes immediate version of shift as input.
14380 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14381                                    SDValue SrcOp, SDValue ShAmt,
14382                                    SelectionDAG &DAG) {
14383   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14384
14385   // Catch shift-by-constant.
14386   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14387     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14388                                       CShAmt->getZExtValue(), DAG);
14389
14390   // Change opcode to non-immediate version
14391   switch (Opc) {
14392     default: llvm_unreachable("Unknown target vector shift node");
14393     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14394     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14395     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14396   }
14397
14398   // Need to build a vector containing shift amount
14399   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14400   SDValue ShOps[4];
14401   ShOps[0] = ShAmt;
14402   ShOps[1] = DAG.getConstant(0, MVT::i32);
14403   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14404   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14405
14406   // The return type has to be a 128-bit type with the same element
14407   // type as the input type.
14408   MVT EltVT = VT.getVectorElementType();
14409   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14410
14411   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14412   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14413 }
14414
14415 /// \brief Return (vselect \p Mask, \p Op, \p PreservedSrc) along with the
14416 /// necessary casting for \p Mask when lowering masking intrinsics.
14417 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14418                                     SDValue PreservedSrc, SelectionDAG &DAG) {
14419     EVT VT = Op.getValueType();
14420     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14421                                   MVT::i1, VT.getVectorNumElements());
14422     SDLoc dl(Op);
14423
14424     assert(MaskVT.isSimple() && "invalid mask type");
14425     return DAG.getNode(ISD::VSELECT, dl, VT,
14426                        DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask),
14427                        Op, PreservedSrc);
14428 }
14429
14430 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
14431     switch (IntNo) {
14432     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14433     case Intrinsic::x86_fma_vfmadd_ps:
14434     case Intrinsic::x86_fma_vfmadd_pd:
14435     case Intrinsic::x86_fma_vfmadd_ps_256:
14436     case Intrinsic::x86_fma_vfmadd_pd_256:
14437     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14438     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14439       return X86ISD::FMADD;
14440     case Intrinsic::x86_fma_vfmsub_ps:
14441     case Intrinsic::x86_fma_vfmsub_pd:
14442     case Intrinsic::x86_fma_vfmsub_ps_256:
14443     case Intrinsic::x86_fma_vfmsub_pd_256:
14444     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14445     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14446       return X86ISD::FMSUB;
14447     case Intrinsic::x86_fma_vfnmadd_ps:
14448     case Intrinsic::x86_fma_vfnmadd_pd:
14449     case Intrinsic::x86_fma_vfnmadd_ps_256:
14450     case Intrinsic::x86_fma_vfnmadd_pd_256:
14451     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14452     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14453       return X86ISD::FNMADD;
14454     case Intrinsic::x86_fma_vfnmsub_ps:
14455     case Intrinsic::x86_fma_vfnmsub_pd:
14456     case Intrinsic::x86_fma_vfnmsub_ps_256:
14457     case Intrinsic::x86_fma_vfnmsub_pd_256:
14458     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14459     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14460       return X86ISD::FNMSUB;
14461     case Intrinsic::x86_fma_vfmaddsub_ps:
14462     case Intrinsic::x86_fma_vfmaddsub_pd:
14463     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14464     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14465     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14466     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14467       return X86ISD::FMADDSUB;
14468     case Intrinsic::x86_fma_vfmsubadd_ps:
14469     case Intrinsic::x86_fma_vfmsubadd_pd:
14470     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14471     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14472     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14473     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
14474       return X86ISD::FMSUBADD;
14475     }
14476 }
14477
14478 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14479   SDLoc dl(Op);
14480   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14481   switch (IntNo) {
14482   default: return SDValue();    // Don't custom lower most intrinsics.
14483   // Comparison intrinsics.
14484   case Intrinsic::x86_sse_comieq_ss:
14485   case Intrinsic::x86_sse_comilt_ss:
14486   case Intrinsic::x86_sse_comile_ss:
14487   case Intrinsic::x86_sse_comigt_ss:
14488   case Intrinsic::x86_sse_comige_ss:
14489   case Intrinsic::x86_sse_comineq_ss:
14490   case Intrinsic::x86_sse_ucomieq_ss:
14491   case Intrinsic::x86_sse_ucomilt_ss:
14492   case Intrinsic::x86_sse_ucomile_ss:
14493   case Intrinsic::x86_sse_ucomigt_ss:
14494   case Intrinsic::x86_sse_ucomige_ss:
14495   case Intrinsic::x86_sse_ucomineq_ss:
14496   case Intrinsic::x86_sse2_comieq_sd:
14497   case Intrinsic::x86_sse2_comilt_sd:
14498   case Intrinsic::x86_sse2_comile_sd:
14499   case Intrinsic::x86_sse2_comigt_sd:
14500   case Intrinsic::x86_sse2_comige_sd:
14501   case Intrinsic::x86_sse2_comineq_sd:
14502   case Intrinsic::x86_sse2_ucomieq_sd:
14503   case Intrinsic::x86_sse2_ucomilt_sd:
14504   case Intrinsic::x86_sse2_ucomile_sd:
14505   case Intrinsic::x86_sse2_ucomigt_sd:
14506   case Intrinsic::x86_sse2_ucomige_sd:
14507   case Intrinsic::x86_sse2_ucomineq_sd: {
14508     unsigned Opc;
14509     ISD::CondCode CC;
14510     switch (IntNo) {
14511     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14512     case Intrinsic::x86_sse_comieq_ss:
14513     case Intrinsic::x86_sse2_comieq_sd:
14514       Opc = X86ISD::COMI;
14515       CC = ISD::SETEQ;
14516       break;
14517     case Intrinsic::x86_sse_comilt_ss:
14518     case Intrinsic::x86_sse2_comilt_sd:
14519       Opc = X86ISD::COMI;
14520       CC = ISD::SETLT;
14521       break;
14522     case Intrinsic::x86_sse_comile_ss:
14523     case Intrinsic::x86_sse2_comile_sd:
14524       Opc = X86ISD::COMI;
14525       CC = ISD::SETLE;
14526       break;
14527     case Intrinsic::x86_sse_comigt_ss:
14528     case Intrinsic::x86_sse2_comigt_sd:
14529       Opc = X86ISD::COMI;
14530       CC = ISD::SETGT;
14531       break;
14532     case Intrinsic::x86_sse_comige_ss:
14533     case Intrinsic::x86_sse2_comige_sd:
14534       Opc = X86ISD::COMI;
14535       CC = ISD::SETGE;
14536       break;
14537     case Intrinsic::x86_sse_comineq_ss:
14538     case Intrinsic::x86_sse2_comineq_sd:
14539       Opc = X86ISD::COMI;
14540       CC = ISD::SETNE;
14541       break;
14542     case Intrinsic::x86_sse_ucomieq_ss:
14543     case Intrinsic::x86_sse2_ucomieq_sd:
14544       Opc = X86ISD::UCOMI;
14545       CC = ISD::SETEQ;
14546       break;
14547     case Intrinsic::x86_sse_ucomilt_ss:
14548     case Intrinsic::x86_sse2_ucomilt_sd:
14549       Opc = X86ISD::UCOMI;
14550       CC = ISD::SETLT;
14551       break;
14552     case Intrinsic::x86_sse_ucomile_ss:
14553     case Intrinsic::x86_sse2_ucomile_sd:
14554       Opc = X86ISD::UCOMI;
14555       CC = ISD::SETLE;
14556       break;
14557     case Intrinsic::x86_sse_ucomigt_ss:
14558     case Intrinsic::x86_sse2_ucomigt_sd:
14559       Opc = X86ISD::UCOMI;
14560       CC = ISD::SETGT;
14561       break;
14562     case Intrinsic::x86_sse_ucomige_ss:
14563     case Intrinsic::x86_sse2_ucomige_sd:
14564       Opc = X86ISD::UCOMI;
14565       CC = ISD::SETGE;
14566       break;
14567     case Intrinsic::x86_sse_ucomineq_ss:
14568     case Intrinsic::x86_sse2_ucomineq_sd:
14569       Opc = X86ISD::UCOMI;
14570       CC = ISD::SETNE;
14571       break;
14572     }
14573
14574     SDValue LHS = Op.getOperand(1);
14575     SDValue RHS = Op.getOperand(2);
14576     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14577     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14578     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
14579     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14580                                 DAG.getConstant(X86CC, MVT::i8), Cond);
14581     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14582   }
14583
14584   // Arithmetic intrinsics.
14585   case Intrinsic::x86_sse2_pmulu_dq:
14586   case Intrinsic::x86_avx2_pmulu_dq:
14587     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14588                        Op.getOperand(1), Op.getOperand(2));
14589
14590   case Intrinsic::x86_sse41_pmuldq:
14591   case Intrinsic::x86_avx2_pmul_dq:
14592     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14593                        Op.getOperand(1), Op.getOperand(2));
14594
14595   case Intrinsic::x86_sse2_pmulhu_w:
14596   case Intrinsic::x86_avx2_pmulhu_w:
14597     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14598                        Op.getOperand(1), Op.getOperand(2));
14599
14600   case Intrinsic::x86_sse2_pmulh_w:
14601   case Intrinsic::x86_avx2_pmulh_w:
14602     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14603                        Op.getOperand(1), Op.getOperand(2));
14604
14605   // SSE2/AVX2 sub with unsigned saturation intrinsics
14606   case Intrinsic::x86_sse2_psubus_b:
14607   case Intrinsic::x86_sse2_psubus_w:
14608   case Intrinsic::x86_avx2_psubus_b:
14609   case Intrinsic::x86_avx2_psubus_w:
14610     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
14611                        Op.getOperand(1), Op.getOperand(2));
14612
14613   // SSE3/AVX horizontal add/sub intrinsics
14614   case Intrinsic::x86_sse3_hadd_ps:
14615   case Intrinsic::x86_sse3_hadd_pd:
14616   case Intrinsic::x86_avx_hadd_ps_256:
14617   case Intrinsic::x86_avx_hadd_pd_256:
14618   case Intrinsic::x86_sse3_hsub_ps:
14619   case Intrinsic::x86_sse3_hsub_pd:
14620   case Intrinsic::x86_avx_hsub_ps_256:
14621   case Intrinsic::x86_avx_hsub_pd_256:
14622   case Intrinsic::x86_ssse3_phadd_w_128:
14623   case Intrinsic::x86_ssse3_phadd_d_128:
14624   case Intrinsic::x86_avx2_phadd_w:
14625   case Intrinsic::x86_avx2_phadd_d:
14626   case Intrinsic::x86_ssse3_phsub_w_128:
14627   case Intrinsic::x86_ssse3_phsub_d_128:
14628   case Intrinsic::x86_avx2_phsub_w:
14629   case Intrinsic::x86_avx2_phsub_d: {
14630     unsigned Opcode;
14631     switch (IntNo) {
14632     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14633     case Intrinsic::x86_sse3_hadd_ps:
14634     case Intrinsic::x86_sse3_hadd_pd:
14635     case Intrinsic::x86_avx_hadd_ps_256:
14636     case Intrinsic::x86_avx_hadd_pd_256:
14637       Opcode = X86ISD::FHADD;
14638       break;
14639     case Intrinsic::x86_sse3_hsub_ps:
14640     case Intrinsic::x86_sse3_hsub_pd:
14641     case Intrinsic::x86_avx_hsub_ps_256:
14642     case Intrinsic::x86_avx_hsub_pd_256:
14643       Opcode = X86ISD::FHSUB;
14644       break;
14645     case Intrinsic::x86_ssse3_phadd_w_128:
14646     case Intrinsic::x86_ssse3_phadd_d_128:
14647     case Intrinsic::x86_avx2_phadd_w:
14648     case Intrinsic::x86_avx2_phadd_d:
14649       Opcode = X86ISD::HADD;
14650       break;
14651     case Intrinsic::x86_ssse3_phsub_w_128:
14652     case Intrinsic::x86_ssse3_phsub_d_128:
14653     case Intrinsic::x86_avx2_phsub_w:
14654     case Intrinsic::x86_avx2_phsub_d:
14655       Opcode = X86ISD::HSUB;
14656       break;
14657     }
14658     return DAG.getNode(Opcode, dl, Op.getValueType(),
14659                        Op.getOperand(1), Op.getOperand(2));
14660   }
14661
14662   // SSE2/SSE41/AVX2 integer max/min intrinsics.
14663   case Intrinsic::x86_sse2_pmaxu_b:
14664   case Intrinsic::x86_sse41_pmaxuw:
14665   case Intrinsic::x86_sse41_pmaxud:
14666   case Intrinsic::x86_avx2_pmaxu_b:
14667   case Intrinsic::x86_avx2_pmaxu_w:
14668   case Intrinsic::x86_avx2_pmaxu_d:
14669   case Intrinsic::x86_sse2_pminu_b:
14670   case Intrinsic::x86_sse41_pminuw:
14671   case Intrinsic::x86_sse41_pminud:
14672   case Intrinsic::x86_avx2_pminu_b:
14673   case Intrinsic::x86_avx2_pminu_w:
14674   case Intrinsic::x86_avx2_pminu_d:
14675   case Intrinsic::x86_sse41_pmaxsb:
14676   case Intrinsic::x86_sse2_pmaxs_w:
14677   case Intrinsic::x86_sse41_pmaxsd:
14678   case Intrinsic::x86_avx2_pmaxs_b:
14679   case Intrinsic::x86_avx2_pmaxs_w:
14680   case Intrinsic::x86_avx2_pmaxs_d:
14681   case Intrinsic::x86_sse41_pminsb:
14682   case Intrinsic::x86_sse2_pmins_w:
14683   case Intrinsic::x86_sse41_pminsd:
14684   case Intrinsic::x86_avx2_pmins_b:
14685   case Intrinsic::x86_avx2_pmins_w:
14686   case Intrinsic::x86_avx2_pmins_d: {
14687     unsigned Opcode;
14688     switch (IntNo) {
14689     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14690     case Intrinsic::x86_sse2_pmaxu_b:
14691     case Intrinsic::x86_sse41_pmaxuw:
14692     case Intrinsic::x86_sse41_pmaxud:
14693     case Intrinsic::x86_avx2_pmaxu_b:
14694     case Intrinsic::x86_avx2_pmaxu_w:
14695     case Intrinsic::x86_avx2_pmaxu_d:
14696       Opcode = X86ISD::UMAX;
14697       break;
14698     case Intrinsic::x86_sse2_pminu_b:
14699     case Intrinsic::x86_sse41_pminuw:
14700     case Intrinsic::x86_sse41_pminud:
14701     case Intrinsic::x86_avx2_pminu_b:
14702     case Intrinsic::x86_avx2_pminu_w:
14703     case Intrinsic::x86_avx2_pminu_d:
14704       Opcode = X86ISD::UMIN;
14705       break;
14706     case Intrinsic::x86_sse41_pmaxsb:
14707     case Intrinsic::x86_sse2_pmaxs_w:
14708     case Intrinsic::x86_sse41_pmaxsd:
14709     case Intrinsic::x86_avx2_pmaxs_b:
14710     case Intrinsic::x86_avx2_pmaxs_w:
14711     case Intrinsic::x86_avx2_pmaxs_d:
14712       Opcode = X86ISD::SMAX;
14713       break;
14714     case Intrinsic::x86_sse41_pminsb:
14715     case Intrinsic::x86_sse2_pmins_w:
14716     case Intrinsic::x86_sse41_pminsd:
14717     case Intrinsic::x86_avx2_pmins_b:
14718     case Intrinsic::x86_avx2_pmins_w:
14719     case Intrinsic::x86_avx2_pmins_d:
14720       Opcode = X86ISD::SMIN;
14721       break;
14722     }
14723     return DAG.getNode(Opcode, dl, Op.getValueType(),
14724                        Op.getOperand(1), Op.getOperand(2));
14725   }
14726
14727   // SSE/SSE2/AVX floating point max/min intrinsics.
14728   case Intrinsic::x86_sse_max_ps:
14729   case Intrinsic::x86_sse2_max_pd:
14730   case Intrinsic::x86_avx_max_ps_256:
14731   case Intrinsic::x86_avx_max_pd_256:
14732   case Intrinsic::x86_sse_min_ps:
14733   case Intrinsic::x86_sse2_min_pd:
14734   case Intrinsic::x86_avx_min_ps_256:
14735   case Intrinsic::x86_avx_min_pd_256: {
14736     unsigned Opcode;
14737     switch (IntNo) {
14738     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14739     case Intrinsic::x86_sse_max_ps:
14740     case Intrinsic::x86_sse2_max_pd:
14741     case Intrinsic::x86_avx_max_ps_256:
14742     case Intrinsic::x86_avx_max_pd_256:
14743       Opcode = X86ISD::FMAX;
14744       break;
14745     case Intrinsic::x86_sse_min_ps:
14746     case Intrinsic::x86_sse2_min_pd:
14747     case Intrinsic::x86_avx_min_ps_256:
14748     case Intrinsic::x86_avx_min_pd_256:
14749       Opcode = X86ISD::FMIN;
14750       break;
14751     }
14752     return DAG.getNode(Opcode, dl, Op.getValueType(),
14753                        Op.getOperand(1), Op.getOperand(2));
14754   }
14755
14756   // AVX2 variable shift intrinsics
14757   case Intrinsic::x86_avx2_psllv_d:
14758   case Intrinsic::x86_avx2_psllv_q:
14759   case Intrinsic::x86_avx2_psllv_d_256:
14760   case Intrinsic::x86_avx2_psllv_q_256:
14761   case Intrinsic::x86_avx2_psrlv_d:
14762   case Intrinsic::x86_avx2_psrlv_q:
14763   case Intrinsic::x86_avx2_psrlv_d_256:
14764   case Intrinsic::x86_avx2_psrlv_q_256:
14765   case Intrinsic::x86_avx2_psrav_d:
14766   case Intrinsic::x86_avx2_psrav_d_256: {
14767     unsigned Opcode;
14768     switch (IntNo) {
14769     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14770     case Intrinsic::x86_avx2_psllv_d:
14771     case Intrinsic::x86_avx2_psllv_q:
14772     case Intrinsic::x86_avx2_psllv_d_256:
14773     case Intrinsic::x86_avx2_psllv_q_256:
14774       Opcode = ISD::SHL;
14775       break;
14776     case Intrinsic::x86_avx2_psrlv_d:
14777     case Intrinsic::x86_avx2_psrlv_q:
14778     case Intrinsic::x86_avx2_psrlv_d_256:
14779     case Intrinsic::x86_avx2_psrlv_q_256:
14780       Opcode = ISD::SRL;
14781       break;
14782     case Intrinsic::x86_avx2_psrav_d:
14783     case Intrinsic::x86_avx2_psrav_d_256:
14784       Opcode = ISD::SRA;
14785       break;
14786     }
14787     return DAG.getNode(Opcode, dl, Op.getValueType(),
14788                        Op.getOperand(1), Op.getOperand(2));
14789   }
14790
14791   case Intrinsic::x86_sse2_packssdw_128:
14792   case Intrinsic::x86_sse2_packsswb_128:
14793   case Intrinsic::x86_avx2_packssdw:
14794   case Intrinsic::x86_avx2_packsswb:
14795     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14796                        Op.getOperand(1), Op.getOperand(2));
14797
14798   case Intrinsic::x86_sse2_packuswb_128:
14799   case Intrinsic::x86_sse41_packusdw:
14800   case Intrinsic::x86_avx2_packuswb:
14801   case Intrinsic::x86_avx2_packusdw:
14802     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14803                        Op.getOperand(1), Op.getOperand(2));
14804
14805   case Intrinsic::x86_ssse3_pshuf_b_128:
14806   case Intrinsic::x86_avx2_pshuf_b:
14807     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14808                        Op.getOperand(1), Op.getOperand(2));
14809
14810   case Intrinsic::x86_sse2_pshuf_d:
14811     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14812                        Op.getOperand(1), Op.getOperand(2));
14813
14814   case Intrinsic::x86_sse2_pshufl_w:
14815     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14816                        Op.getOperand(1), Op.getOperand(2));
14817
14818   case Intrinsic::x86_sse2_pshufh_w:
14819     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14820                        Op.getOperand(1), Op.getOperand(2));
14821
14822   case Intrinsic::x86_ssse3_psign_b_128:
14823   case Intrinsic::x86_ssse3_psign_w_128:
14824   case Intrinsic::x86_ssse3_psign_d_128:
14825   case Intrinsic::x86_avx2_psign_b:
14826   case Intrinsic::x86_avx2_psign_w:
14827   case Intrinsic::x86_avx2_psign_d:
14828     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14829                        Op.getOperand(1), Op.getOperand(2));
14830
14831   case Intrinsic::x86_sse41_insertps:
14832     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14833                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14834
14835   case Intrinsic::x86_avx_vperm2f128_ps_256:
14836   case Intrinsic::x86_avx_vperm2f128_pd_256:
14837   case Intrinsic::x86_avx_vperm2f128_si_256:
14838   case Intrinsic::x86_avx2_vperm2i128:
14839     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14840                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14841
14842   case Intrinsic::x86_avx2_permd:
14843   case Intrinsic::x86_avx2_permps:
14844     // Operands intentionally swapped. Mask is last operand to intrinsic,
14845     // but second operand for node/instruction.
14846     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14847                        Op.getOperand(2), Op.getOperand(1));
14848
14849   case Intrinsic::x86_sse_sqrt_ps:
14850   case Intrinsic::x86_sse2_sqrt_pd:
14851   case Intrinsic::x86_avx_sqrt_ps_256:
14852   case Intrinsic::x86_avx_sqrt_pd_256:
14853     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14854
14855   case Intrinsic::x86_avx512_mask_valign_q_512:
14856   case Intrinsic::x86_avx512_mask_valign_d_512:
14857     // Vector source operands are swapped.
14858     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14859                                             Op.getValueType(), Op.getOperand(2),
14860                                             Op.getOperand(1),
14861                                             Op.getOperand(3)),
14862                                 Op.getOperand(5), Op.getOperand(4), DAG);
14863
14864   // ptest and testp intrinsics. The intrinsic these come from are designed to
14865   // return an integer value, not just an instruction so lower it to the ptest
14866   // or testp pattern and a setcc for the result.
14867   case Intrinsic::x86_sse41_ptestz:
14868   case Intrinsic::x86_sse41_ptestc:
14869   case Intrinsic::x86_sse41_ptestnzc:
14870   case Intrinsic::x86_avx_ptestz_256:
14871   case Intrinsic::x86_avx_ptestc_256:
14872   case Intrinsic::x86_avx_ptestnzc_256:
14873   case Intrinsic::x86_avx_vtestz_ps:
14874   case Intrinsic::x86_avx_vtestc_ps:
14875   case Intrinsic::x86_avx_vtestnzc_ps:
14876   case Intrinsic::x86_avx_vtestz_pd:
14877   case Intrinsic::x86_avx_vtestc_pd:
14878   case Intrinsic::x86_avx_vtestnzc_pd:
14879   case Intrinsic::x86_avx_vtestz_ps_256:
14880   case Intrinsic::x86_avx_vtestc_ps_256:
14881   case Intrinsic::x86_avx_vtestnzc_ps_256:
14882   case Intrinsic::x86_avx_vtestz_pd_256:
14883   case Intrinsic::x86_avx_vtestc_pd_256:
14884   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14885     bool IsTestPacked = false;
14886     unsigned X86CC;
14887     switch (IntNo) {
14888     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14889     case Intrinsic::x86_avx_vtestz_ps:
14890     case Intrinsic::x86_avx_vtestz_pd:
14891     case Intrinsic::x86_avx_vtestz_ps_256:
14892     case Intrinsic::x86_avx_vtestz_pd_256:
14893       IsTestPacked = true; // Fallthrough
14894     case Intrinsic::x86_sse41_ptestz:
14895     case Intrinsic::x86_avx_ptestz_256:
14896       // ZF = 1
14897       X86CC = X86::COND_E;
14898       break;
14899     case Intrinsic::x86_avx_vtestc_ps:
14900     case Intrinsic::x86_avx_vtestc_pd:
14901     case Intrinsic::x86_avx_vtestc_ps_256:
14902     case Intrinsic::x86_avx_vtestc_pd_256:
14903       IsTestPacked = true; // Fallthrough
14904     case Intrinsic::x86_sse41_ptestc:
14905     case Intrinsic::x86_avx_ptestc_256:
14906       // CF = 1
14907       X86CC = X86::COND_B;
14908       break;
14909     case Intrinsic::x86_avx_vtestnzc_ps:
14910     case Intrinsic::x86_avx_vtestnzc_pd:
14911     case Intrinsic::x86_avx_vtestnzc_ps_256:
14912     case Intrinsic::x86_avx_vtestnzc_pd_256:
14913       IsTestPacked = true; // Fallthrough
14914     case Intrinsic::x86_sse41_ptestnzc:
14915     case Intrinsic::x86_avx_ptestnzc_256:
14916       // ZF and CF = 0
14917       X86CC = X86::COND_A;
14918       break;
14919     }
14920
14921     SDValue LHS = Op.getOperand(1);
14922     SDValue RHS = Op.getOperand(2);
14923     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14924     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14925     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14926     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14927     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14928   }
14929   case Intrinsic::x86_avx512_kortestz_w:
14930   case Intrinsic::x86_avx512_kortestc_w: {
14931     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14932     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14933     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14934     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14935     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14936     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14937     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14938   }
14939
14940   // SSE/AVX shift intrinsics
14941   case Intrinsic::x86_sse2_psll_w:
14942   case Intrinsic::x86_sse2_psll_d:
14943   case Intrinsic::x86_sse2_psll_q:
14944   case Intrinsic::x86_avx2_psll_w:
14945   case Intrinsic::x86_avx2_psll_d:
14946   case Intrinsic::x86_avx2_psll_q:
14947   case Intrinsic::x86_sse2_psrl_w:
14948   case Intrinsic::x86_sse2_psrl_d:
14949   case Intrinsic::x86_sse2_psrl_q:
14950   case Intrinsic::x86_avx2_psrl_w:
14951   case Intrinsic::x86_avx2_psrl_d:
14952   case Intrinsic::x86_avx2_psrl_q:
14953   case Intrinsic::x86_sse2_psra_w:
14954   case Intrinsic::x86_sse2_psra_d:
14955   case Intrinsic::x86_avx2_psra_w:
14956   case Intrinsic::x86_avx2_psra_d: {
14957     unsigned Opcode;
14958     switch (IntNo) {
14959     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14960     case Intrinsic::x86_sse2_psll_w:
14961     case Intrinsic::x86_sse2_psll_d:
14962     case Intrinsic::x86_sse2_psll_q:
14963     case Intrinsic::x86_avx2_psll_w:
14964     case Intrinsic::x86_avx2_psll_d:
14965     case Intrinsic::x86_avx2_psll_q:
14966       Opcode = X86ISD::VSHL;
14967       break;
14968     case Intrinsic::x86_sse2_psrl_w:
14969     case Intrinsic::x86_sse2_psrl_d:
14970     case Intrinsic::x86_sse2_psrl_q:
14971     case Intrinsic::x86_avx2_psrl_w:
14972     case Intrinsic::x86_avx2_psrl_d:
14973     case Intrinsic::x86_avx2_psrl_q:
14974       Opcode = X86ISD::VSRL;
14975       break;
14976     case Intrinsic::x86_sse2_psra_w:
14977     case Intrinsic::x86_sse2_psra_d:
14978     case Intrinsic::x86_avx2_psra_w:
14979     case Intrinsic::x86_avx2_psra_d:
14980       Opcode = X86ISD::VSRA;
14981       break;
14982     }
14983     return DAG.getNode(Opcode, dl, Op.getValueType(),
14984                        Op.getOperand(1), Op.getOperand(2));
14985   }
14986
14987   // SSE/AVX immediate shift intrinsics
14988   case Intrinsic::x86_sse2_pslli_w:
14989   case Intrinsic::x86_sse2_pslli_d:
14990   case Intrinsic::x86_sse2_pslli_q:
14991   case Intrinsic::x86_avx2_pslli_w:
14992   case Intrinsic::x86_avx2_pslli_d:
14993   case Intrinsic::x86_avx2_pslli_q:
14994   case Intrinsic::x86_sse2_psrli_w:
14995   case Intrinsic::x86_sse2_psrli_d:
14996   case Intrinsic::x86_sse2_psrli_q:
14997   case Intrinsic::x86_avx2_psrli_w:
14998   case Intrinsic::x86_avx2_psrli_d:
14999   case Intrinsic::x86_avx2_psrli_q:
15000   case Intrinsic::x86_sse2_psrai_w:
15001   case Intrinsic::x86_sse2_psrai_d:
15002   case Intrinsic::x86_avx2_psrai_w:
15003   case Intrinsic::x86_avx2_psrai_d: {
15004     unsigned Opcode;
15005     switch (IntNo) {
15006     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15007     case Intrinsic::x86_sse2_pslli_w:
15008     case Intrinsic::x86_sse2_pslli_d:
15009     case Intrinsic::x86_sse2_pslli_q:
15010     case Intrinsic::x86_avx2_pslli_w:
15011     case Intrinsic::x86_avx2_pslli_d:
15012     case Intrinsic::x86_avx2_pslli_q:
15013       Opcode = X86ISD::VSHLI;
15014       break;
15015     case Intrinsic::x86_sse2_psrli_w:
15016     case Intrinsic::x86_sse2_psrli_d:
15017     case Intrinsic::x86_sse2_psrli_q:
15018     case Intrinsic::x86_avx2_psrli_w:
15019     case Intrinsic::x86_avx2_psrli_d:
15020     case Intrinsic::x86_avx2_psrli_q:
15021       Opcode = X86ISD::VSRLI;
15022       break;
15023     case Intrinsic::x86_sse2_psrai_w:
15024     case Intrinsic::x86_sse2_psrai_d:
15025     case Intrinsic::x86_avx2_psrai_w:
15026     case Intrinsic::x86_avx2_psrai_d:
15027       Opcode = X86ISD::VSRAI;
15028       break;
15029     }
15030     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
15031                                Op.getOperand(1), Op.getOperand(2), DAG);
15032   }
15033
15034   case Intrinsic::x86_sse42_pcmpistria128:
15035   case Intrinsic::x86_sse42_pcmpestria128:
15036   case Intrinsic::x86_sse42_pcmpistric128:
15037   case Intrinsic::x86_sse42_pcmpestric128:
15038   case Intrinsic::x86_sse42_pcmpistrio128:
15039   case Intrinsic::x86_sse42_pcmpestrio128:
15040   case Intrinsic::x86_sse42_pcmpistris128:
15041   case Intrinsic::x86_sse42_pcmpestris128:
15042   case Intrinsic::x86_sse42_pcmpistriz128:
15043   case Intrinsic::x86_sse42_pcmpestriz128: {
15044     unsigned Opcode;
15045     unsigned X86CC;
15046     switch (IntNo) {
15047     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15048     case Intrinsic::x86_sse42_pcmpistria128:
15049       Opcode = X86ISD::PCMPISTRI;
15050       X86CC = X86::COND_A;
15051       break;
15052     case Intrinsic::x86_sse42_pcmpestria128:
15053       Opcode = X86ISD::PCMPESTRI;
15054       X86CC = X86::COND_A;
15055       break;
15056     case Intrinsic::x86_sse42_pcmpistric128:
15057       Opcode = X86ISD::PCMPISTRI;
15058       X86CC = X86::COND_B;
15059       break;
15060     case Intrinsic::x86_sse42_pcmpestric128:
15061       Opcode = X86ISD::PCMPESTRI;
15062       X86CC = X86::COND_B;
15063       break;
15064     case Intrinsic::x86_sse42_pcmpistrio128:
15065       Opcode = X86ISD::PCMPISTRI;
15066       X86CC = X86::COND_O;
15067       break;
15068     case Intrinsic::x86_sse42_pcmpestrio128:
15069       Opcode = X86ISD::PCMPESTRI;
15070       X86CC = X86::COND_O;
15071       break;
15072     case Intrinsic::x86_sse42_pcmpistris128:
15073       Opcode = X86ISD::PCMPISTRI;
15074       X86CC = X86::COND_S;
15075       break;
15076     case Intrinsic::x86_sse42_pcmpestris128:
15077       Opcode = X86ISD::PCMPESTRI;
15078       X86CC = X86::COND_S;
15079       break;
15080     case Intrinsic::x86_sse42_pcmpistriz128:
15081       Opcode = X86ISD::PCMPISTRI;
15082       X86CC = X86::COND_E;
15083       break;
15084     case Intrinsic::x86_sse42_pcmpestriz128:
15085       Opcode = X86ISD::PCMPESTRI;
15086       X86CC = X86::COND_E;
15087       break;
15088     }
15089     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15090     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15091     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15092     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15093                                 DAG.getConstant(X86CC, MVT::i8),
15094                                 SDValue(PCMP.getNode(), 1));
15095     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15096   }
15097
15098   case Intrinsic::x86_sse42_pcmpistri128:
15099   case Intrinsic::x86_sse42_pcmpestri128: {
15100     unsigned Opcode;
15101     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15102       Opcode = X86ISD::PCMPISTRI;
15103     else
15104       Opcode = X86ISD::PCMPESTRI;
15105
15106     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15107     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15108     return DAG.getNode(Opcode, dl, VTs, NewOps);
15109   }
15110
15111   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
15112   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
15113   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
15114   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
15115   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
15116   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
15117   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
15118   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
15119   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
15120   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
15121   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
15122   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
15123     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
15124     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
15125       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
15126                                               dl, Op.getValueType(),
15127                                               Op.getOperand(1),
15128                                               Op.getOperand(2),
15129                                               Op.getOperand(3)),
15130                                   Op.getOperand(4), Op.getOperand(1), DAG);
15131     else
15132       return SDValue();
15133   }
15134
15135   case Intrinsic::x86_fma_vfmadd_ps:
15136   case Intrinsic::x86_fma_vfmadd_pd:
15137   case Intrinsic::x86_fma_vfmsub_ps:
15138   case Intrinsic::x86_fma_vfmsub_pd:
15139   case Intrinsic::x86_fma_vfnmadd_ps:
15140   case Intrinsic::x86_fma_vfnmadd_pd:
15141   case Intrinsic::x86_fma_vfnmsub_ps:
15142   case Intrinsic::x86_fma_vfnmsub_pd:
15143   case Intrinsic::x86_fma_vfmaddsub_ps:
15144   case Intrinsic::x86_fma_vfmaddsub_pd:
15145   case Intrinsic::x86_fma_vfmsubadd_ps:
15146   case Intrinsic::x86_fma_vfmsubadd_pd:
15147   case Intrinsic::x86_fma_vfmadd_ps_256:
15148   case Intrinsic::x86_fma_vfmadd_pd_256:
15149   case Intrinsic::x86_fma_vfmsub_ps_256:
15150   case Intrinsic::x86_fma_vfmsub_pd_256:
15151   case Intrinsic::x86_fma_vfnmadd_ps_256:
15152   case Intrinsic::x86_fma_vfnmadd_pd_256:
15153   case Intrinsic::x86_fma_vfnmsub_ps_256:
15154   case Intrinsic::x86_fma_vfnmsub_pd_256:
15155   case Intrinsic::x86_fma_vfmaddsub_ps_256:
15156   case Intrinsic::x86_fma_vfmaddsub_pd_256:
15157   case Intrinsic::x86_fma_vfmsubadd_ps_256:
15158   case Intrinsic::x86_fma_vfmsubadd_pd_256:
15159     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
15160                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
15161   }
15162 }
15163
15164 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15165                               SDValue Src, SDValue Mask, SDValue Base,
15166                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15167                               const X86Subtarget * Subtarget) {
15168   SDLoc dl(Op);
15169   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15170   assert(C && "Invalid scale type");
15171   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15172   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15173                              Index.getSimpleValueType().getVectorNumElements());
15174   SDValue MaskInReg;
15175   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15176   if (MaskC)
15177     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15178   else
15179     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15180   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15181   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15182   SDValue Segment = DAG.getRegister(0, MVT::i32);
15183   if (Src.getOpcode() == ISD::UNDEF)
15184     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15185   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15186   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15187   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15188   return DAG.getMergeValues(RetOps, dl);
15189 }
15190
15191 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15192                                SDValue Src, SDValue Mask, SDValue Base,
15193                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15194   SDLoc dl(Op);
15195   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15196   assert(C && "Invalid scale type");
15197   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15198   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15199   SDValue Segment = DAG.getRegister(0, MVT::i32);
15200   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15201                              Index.getSimpleValueType().getVectorNumElements());
15202   SDValue MaskInReg;
15203   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15204   if (MaskC)
15205     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15206   else
15207     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15208   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15209   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15210   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15211   return SDValue(Res, 1);
15212 }
15213
15214 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15215                                SDValue Mask, SDValue Base, SDValue Index,
15216                                SDValue ScaleOp, SDValue Chain) {
15217   SDLoc dl(Op);
15218   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15219   assert(C && "Invalid scale type");
15220   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15221   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15222   SDValue Segment = DAG.getRegister(0, MVT::i32);
15223   EVT MaskVT =
15224     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15225   SDValue MaskInReg;
15226   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15227   if (MaskC)
15228     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15229   else
15230     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15231   //SDVTList VTs = DAG.getVTList(MVT::Other);
15232   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15233   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15234   return SDValue(Res, 0);
15235 }
15236
15237 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15238 // read performance monitor counters (x86_rdpmc).
15239 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15240                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15241                               SmallVectorImpl<SDValue> &Results) {
15242   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15243   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15244   SDValue LO, HI;
15245
15246   // The ECX register is used to select the index of the performance counter
15247   // to read.
15248   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15249                                    N->getOperand(2));
15250   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15251
15252   // Reads the content of a 64-bit performance counter and returns it in the
15253   // registers EDX:EAX.
15254   if (Subtarget->is64Bit()) {
15255     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15256     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15257                             LO.getValue(2));
15258   } else {
15259     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15260     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15261                             LO.getValue(2));
15262   }
15263   Chain = HI.getValue(1);
15264
15265   if (Subtarget->is64Bit()) {
15266     // The EAX register is loaded with the low-order 32 bits. The EDX register
15267     // is loaded with the supported high-order bits of the counter.
15268     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15269                               DAG.getConstant(32, MVT::i8));
15270     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15271     Results.push_back(Chain);
15272     return;
15273   }
15274
15275   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15276   SDValue Ops[] = { LO, HI };
15277   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15278   Results.push_back(Pair);
15279   Results.push_back(Chain);
15280 }
15281
15282 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15283 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15284 // also used to custom lower READCYCLECOUNTER nodes.
15285 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15286                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15287                               SmallVectorImpl<SDValue> &Results) {
15288   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15289   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15290   SDValue LO, HI;
15291
15292   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15293   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15294   // and the EAX register is loaded with the low-order 32 bits.
15295   if (Subtarget->is64Bit()) {
15296     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15297     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15298                             LO.getValue(2));
15299   } else {
15300     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15301     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15302                             LO.getValue(2));
15303   }
15304   SDValue Chain = HI.getValue(1);
15305
15306   if (Opcode == X86ISD::RDTSCP_DAG) {
15307     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15308
15309     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15310     // the ECX register. Add 'ecx' explicitly to the chain.
15311     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15312                                      HI.getValue(2));
15313     // Explicitly store the content of ECX at the location passed in input
15314     // to the 'rdtscp' intrinsic.
15315     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15316                          MachinePointerInfo(), false, false, 0);
15317   }
15318
15319   if (Subtarget->is64Bit()) {
15320     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15321     // the EAX register is loaded with the low-order 32 bits.
15322     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15323                               DAG.getConstant(32, MVT::i8));
15324     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15325     Results.push_back(Chain);
15326     return;
15327   }
15328
15329   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15330   SDValue Ops[] = { LO, HI };
15331   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15332   Results.push_back(Pair);
15333   Results.push_back(Chain);
15334 }
15335
15336 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15337                                      SelectionDAG &DAG) {
15338   SmallVector<SDValue, 2> Results;
15339   SDLoc DL(Op);
15340   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15341                           Results);
15342   return DAG.getMergeValues(Results, DL);
15343 }
15344
15345 enum IntrinsicType {
15346   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
15347 };
15348
15349 struct IntrinsicData {
15350   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
15351     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
15352   IntrinsicType Type;
15353   unsigned      Opc0;
15354   unsigned      Opc1;
15355 };
15356
15357 std::map < unsigned, IntrinsicData> IntrMap;
15358 static void InitIntinsicsMap() {
15359   static bool Initialized = false;
15360   if (Initialized) 
15361     return;
15362   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
15363                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
15364   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
15365                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
15366   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
15367                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
15368   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
15369                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
15370   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
15371                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
15372   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
15373                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
15374   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
15375                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
15376   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
15377                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
15378   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
15379                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
15380
15381   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
15382                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
15383   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
15384                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
15385   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
15386                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
15387   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
15388                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
15389   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
15390                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
15391   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
15392                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
15393   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
15394                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
15395   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
15396                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
15397    
15398   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
15399                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
15400                                                         X86::VGATHERPF1QPSm)));
15401   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
15402                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
15403                                                         X86::VGATHERPF1QPDm)));
15404   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
15405                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
15406                                                         X86::VGATHERPF1DPDm)));
15407   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
15408                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
15409                                                         X86::VGATHERPF1DPSm)));
15410   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
15411                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
15412                                                         X86::VSCATTERPF1QPSm)));
15413   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
15414                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
15415                                                         X86::VSCATTERPF1QPDm)));
15416   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
15417                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
15418                                                         X86::VSCATTERPF1DPDm)));
15419   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
15420                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
15421                                                         X86::VSCATTERPF1DPSm)));
15422   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
15423                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15424   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
15425                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15426   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
15427                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15428   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
15429                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15430   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
15431                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15432   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
15433                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15434   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
15435                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
15436   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
15437                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
15438   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
15439                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
15440   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
15441                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
15442   Initialized = true;
15443 }
15444
15445 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15446                                       SelectionDAG &DAG) {
15447   InitIntinsicsMap();
15448   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15449   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
15450   if (itr == IntrMap.end())
15451     return SDValue();
15452
15453   SDLoc dl(Op);
15454   IntrinsicData Intr = itr->second;
15455   switch(Intr.Type) {
15456   case RDSEED:
15457   case RDRAND: {
15458     // Emit the node with the right value type.
15459     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15460     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
15461
15462     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15463     // Otherwise return the value from Rand, which is always 0, casted to i32.
15464     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15465                       DAG.getConstant(1, Op->getValueType(1)),
15466                       DAG.getConstant(X86::COND_B, MVT::i32),
15467                       SDValue(Result.getNode(), 1) };
15468     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15469                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15470                                   Ops);
15471
15472     // Return { result, isValid, chain }.
15473     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15474                        SDValue(Result.getNode(), 2));
15475   }
15476   case GATHER: {
15477   //gather(v1, mask, index, base, scale);
15478     SDValue Chain = Op.getOperand(0);
15479     SDValue Src   = Op.getOperand(2);
15480     SDValue Base  = Op.getOperand(3);
15481     SDValue Index = Op.getOperand(4);
15482     SDValue Mask  = Op.getOperand(5);
15483     SDValue Scale = Op.getOperand(6);
15484     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15485                           Subtarget);
15486   }
15487   case SCATTER: {
15488   //scatter(base, mask, index, v1, scale);
15489     SDValue Chain = Op.getOperand(0);
15490     SDValue Base  = Op.getOperand(2);
15491     SDValue Mask  = Op.getOperand(3);
15492     SDValue Index = Op.getOperand(4);
15493     SDValue Src   = Op.getOperand(5);
15494     SDValue Scale = Op.getOperand(6);
15495     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15496   }
15497   case PREFETCH: {
15498     SDValue Hint = Op.getOperand(6);
15499     unsigned HintVal;
15500     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15501         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15502       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15503     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
15504     SDValue Chain = Op.getOperand(0);
15505     SDValue Mask  = Op.getOperand(2);
15506     SDValue Index = Op.getOperand(3);
15507     SDValue Base  = Op.getOperand(4);
15508     SDValue Scale = Op.getOperand(5);
15509     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15510   }
15511   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15512   case RDTSC: {
15513     SmallVector<SDValue, 2> Results;
15514     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
15515     return DAG.getMergeValues(Results, dl);
15516   }
15517   // Read Performance Monitoring Counters.
15518   case RDPMC: {
15519     SmallVector<SDValue, 2> Results;
15520     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15521     return DAG.getMergeValues(Results, dl);
15522   }
15523   // XTEST intrinsics.
15524   case XTEST: {
15525     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15526     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
15527     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15528                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15529                                 InTrans);
15530     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15531     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15532                        Ret, SDValue(InTrans.getNode(), 1));
15533   }
15534   }
15535   llvm_unreachable("Unknown Intrinsic Type");
15536 }
15537
15538 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15539                                            SelectionDAG &DAG) const {
15540   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15541   MFI->setReturnAddressIsTaken(true);
15542
15543   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15544     return SDValue();
15545
15546   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15547   SDLoc dl(Op);
15548   EVT PtrVT = getPointerTy();
15549
15550   if (Depth > 0) {
15551     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15552     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15553         DAG.getSubtarget().getRegisterInfo());
15554     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15555     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15556                        DAG.getNode(ISD::ADD, dl, PtrVT,
15557                                    FrameAddr, Offset),
15558                        MachinePointerInfo(), false, false, false, 0);
15559   }
15560
15561   // Just load the return address.
15562   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15563   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15564                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15565 }
15566
15567 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15568   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15569   MFI->setFrameAddressIsTaken(true);
15570
15571   EVT VT = Op.getValueType();
15572   SDLoc dl(Op);  // FIXME probably not meaningful
15573   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15574   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15575       DAG.getSubtarget().getRegisterInfo());
15576   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15577   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15578           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15579          "Invalid Frame Register!");
15580   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15581   while (Depth--)
15582     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15583                             MachinePointerInfo(),
15584                             false, false, false, 0);
15585   return FrameAddr;
15586 }
15587
15588 // FIXME? Maybe this could be a TableGen attribute on some registers and
15589 // this table could be generated automatically from RegInfo.
15590 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15591                                               EVT VT) const {
15592   unsigned Reg = StringSwitch<unsigned>(RegName)
15593                        .Case("esp", X86::ESP)
15594                        .Case("rsp", X86::RSP)
15595                        .Default(0);
15596   if (Reg)
15597     return Reg;
15598   report_fatal_error("Invalid register name global variable");
15599 }
15600
15601 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15602                                                      SelectionDAG &DAG) const {
15603   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15604       DAG.getSubtarget().getRegisterInfo());
15605   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15606 }
15607
15608 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15609   SDValue Chain     = Op.getOperand(0);
15610   SDValue Offset    = Op.getOperand(1);
15611   SDValue Handler   = Op.getOperand(2);
15612   SDLoc dl      (Op);
15613
15614   EVT PtrVT = getPointerTy();
15615   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15616       DAG.getSubtarget().getRegisterInfo());
15617   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15618   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15619           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15620          "Invalid Frame Register!");
15621   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15622   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15623
15624   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15625                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15626   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15627   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15628                        false, false, 0);
15629   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15630
15631   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15632                      DAG.getRegister(StoreAddrReg, PtrVT));
15633 }
15634
15635 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15636                                                SelectionDAG &DAG) const {
15637   SDLoc DL(Op);
15638   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15639                      DAG.getVTList(MVT::i32, MVT::Other),
15640                      Op.getOperand(0), Op.getOperand(1));
15641 }
15642
15643 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15644                                                 SelectionDAG &DAG) const {
15645   SDLoc DL(Op);
15646   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15647                      Op.getOperand(0), Op.getOperand(1));
15648 }
15649
15650 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15651   return Op.getOperand(0);
15652 }
15653
15654 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15655                                                 SelectionDAG &DAG) const {
15656   SDValue Root = Op.getOperand(0);
15657   SDValue Trmp = Op.getOperand(1); // trampoline
15658   SDValue FPtr = Op.getOperand(2); // nested function
15659   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15660   SDLoc dl (Op);
15661
15662   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15663   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15664
15665   if (Subtarget->is64Bit()) {
15666     SDValue OutChains[6];
15667
15668     // Large code-model.
15669     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15670     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15671
15672     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15673     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15674
15675     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15676
15677     // Load the pointer to the nested function into R11.
15678     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15679     SDValue Addr = Trmp;
15680     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15681                                 Addr, MachinePointerInfo(TrmpAddr),
15682                                 false, false, 0);
15683
15684     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15685                        DAG.getConstant(2, MVT::i64));
15686     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15687                                 MachinePointerInfo(TrmpAddr, 2),
15688                                 false, false, 2);
15689
15690     // Load the 'nest' parameter value into R10.
15691     // R10 is specified in X86CallingConv.td
15692     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15693     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15694                        DAG.getConstant(10, MVT::i64));
15695     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15696                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15697                                 false, false, 0);
15698
15699     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15700                        DAG.getConstant(12, MVT::i64));
15701     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15702                                 MachinePointerInfo(TrmpAddr, 12),
15703                                 false, false, 2);
15704
15705     // Jump to the nested function.
15706     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15707     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15708                        DAG.getConstant(20, MVT::i64));
15709     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15710                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15711                                 false, false, 0);
15712
15713     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15714     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15715                        DAG.getConstant(22, MVT::i64));
15716     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15717                                 MachinePointerInfo(TrmpAddr, 22),
15718                                 false, false, 0);
15719
15720     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15721   } else {
15722     const Function *Func =
15723       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15724     CallingConv::ID CC = Func->getCallingConv();
15725     unsigned NestReg;
15726
15727     switch (CC) {
15728     default:
15729       llvm_unreachable("Unsupported calling convention");
15730     case CallingConv::C:
15731     case CallingConv::X86_StdCall: {
15732       // Pass 'nest' parameter in ECX.
15733       // Must be kept in sync with X86CallingConv.td
15734       NestReg = X86::ECX;
15735
15736       // Check that ECX wasn't needed by an 'inreg' parameter.
15737       FunctionType *FTy = Func->getFunctionType();
15738       const AttributeSet &Attrs = Func->getAttributes();
15739
15740       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15741         unsigned InRegCount = 0;
15742         unsigned Idx = 1;
15743
15744         for (FunctionType::param_iterator I = FTy->param_begin(),
15745              E = FTy->param_end(); I != E; ++I, ++Idx)
15746           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15747             // FIXME: should only count parameters that are lowered to integers.
15748             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15749
15750         if (InRegCount > 2) {
15751           report_fatal_error("Nest register in use - reduce number of inreg"
15752                              " parameters!");
15753         }
15754       }
15755       break;
15756     }
15757     case CallingConv::X86_FastCall:
15758     case CallingConv::X86_ThisCall:
15759     case CallingConv::Fast:
15760       // Pass 'nest' parameter in EAX.
15761       // Must be kept in sync with X86CallingConv.td
15762       NestReg = X86::EAX;
15763       break;
15764     }
15765
15766     SDValue OutChains[4];
15767     SDValue Addr, Disp;
15768
15769     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15770                        DAG.getConstant(10, MVT::i32));
15771     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15772
15773     // This is storing the opcode for MOV32ri.
15774     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15775     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15776     OutChains[0] = DAG.getStore(Root, dl,
15777                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15778                                 Trmp, MachinePointerInfo(TrmpAddr),
15779                                 false, false, 0);
15780
15781     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15782                        DAG.getConstant(1, MVT::i32));
15783     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15784                                 MachinePointerInfo(TrmpAddr, 1),
15785                                 false, false, 1);
15786
15787     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15788     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15789                        DAG.getConstant(5, MVT::i32));
15790     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15791                                 MachinePointerInfo(TrmpAddr, 5),
15792                                 false, false, 1);
15793
15794     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15795                        DAG.getConstant(6, MVT::i32));
15796     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15797                                 MachinePointerInfo(TrmpAddr, 6),
15798                                 false, false, 1);
15799
15800     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15801   }
15802 }
15803
15804 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15805                                             SelectionDAG &DAG) const {
15806   /*
15807    The rounding mode is in bits 11:10 of FPSR, and has the following
15808    settings:
15809      00 Round to nearest
15810      01 Round to -inf
15811      10 Round to +inf
15812      11 Round to 0
15813
15814   FLT_ROUNDS, on the other hand, expects the following:
15815     -1 Undefined
15816      0 Round to 0
15817      1 Round to nearest
15818      2 Round to +inf
15819      3 Round to -inf
15820
15821   To perform the conversion, we do:
15822     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15823   */
15824
15825   MachineFunction &MF = DAG.getMachineFunction();
15826   const TargetMachine &TM = MF.getTarget();
15827   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15828   unsigned StackAlignment = TFI.getStackAlignment();
15829   MVT VT = Op.getSimpleValueType();
15830   SDLoc DL(Op);
15831
15832   // Save FP Control Word to stack slot
15833   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15834   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15835
15836   MachineMemOperand *MMO =
15837    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15838                            MachineMemOperand::MOStore, 2, 2);
15839
15840   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15841   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15842                                           DAG.getVTList(MVT::Other),
15843                                           Ops, MVT::i16, MMO);
15844
15845   // Load FP Control Word from stack slot
15846   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15847                             MachinePointerInfo(), false, false, false, 0);
15848
15849   // Transform as necessary
15850   SDValue CWD1 =
15851     DAG.getNode(ISD::SRL, DL, MVT::i16,
15852                 DAG.getNode(ISD::AND, DL, MVT::i16,
15853                             CWD, DAG.getConstant(0x800, MVT::i16)),
15854                 DAG.getConstant(11, MVT::i8));
15855   SDValue CWD2 =
15856     DAG.getNode(ISD::SRL, DL, MVT::i16,
15857                 DAG.getNode(ISD::AND, DL, MVT::i16,
15858                             CWD, DAG.getConstant(0x400, MVT::i16)),
15859                 DAG.getConstant(9, MVT::i8));
15860
15861   SDValue RetVal =
15862     DAG.getNode(ISD::AND, DL, MVT::i16,
15863                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15864                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15865                             DAG.getConstant(1, MVT::i16)),
15866                 DAG.getConstant(3, MVT::i16));
15867
15868   return DAG.getNode((VT.getSizeInBits() < 16 ?
15869                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15870 }
15871
15872 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15873   MVT VT = Op.getSimpleValueType();
15874   EVT OpVT = VT;
15875   unsigned NumBits = VT.getSizeInBits();
15876   SDLoc dl(Op);
15877
15878   Op = Op.getOperand(0);
15879   if (VT == MVT::i8) {
15880     // Zero extend to i32 since there is not an i8 bsr.
15881     OpVT = MVT::i32;
15882     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15883   }
15884
15885   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15886   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15887   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15888
15889   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15890   SDValue Ops[] = {
15891     Op,
15892     DAG.getConstant(NumBits+NumBits-1, OpVT),
15893     DAG.getConstant(X86::COND_E, MVT::i8),
15894     Op.getValue(1)
15895   };
15896   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15897
15898   // Finally xor with NumBits-1.
15899   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15900
15901   if (VT == MVT::i8)
15902     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15903   return Op;
15904 }
15905
15906 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15907   MVT VT = Op.getSimpleValueType();
15908   EVT OpVT = VT;
15909   unsigned NumBits = VT.getSizeInBits();
15910   SDLoc dl(Op);
15911
15912   Op = Op.getOperand(0);
15913   if (VT == MVT::i8) {
15914     // Zero extend to i32 since there is not an i8 bsr.
15915     OpVT = MVT::i32;
15916     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15917   }
15918
15919   // Issue a bsr (scan bits in reverse).
15920   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15921   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15922
15923   // And xor with NumBits-1.
15924   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15925
15926   if (VT == MVT::i8)
15927     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15928   return Op;
15929 }
15930
15931 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15932   MVT VT = Op.getSimpleValueType();
15933   unsigned NumBits = VT.getSizeInBits();
15934   SDLoc dl(Op);
15935   Op = Op.getOperand(0);
15936
15937   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15938   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15939   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15940
15941   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15942   SDValue Ops[] = {
15943     Op,
15944     DAG.getConstant(NumBits, VT),
15945     DAG.getConstant(X86::COND_E, MVT::i8),
15946     Op.getValue(1)
15947   };
15948   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15949 }
15950
15951 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15952 // ones, and then concatenate the result back.
15953 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15954   MVT VT = Op.getSimpleValueType();
15955
15956   assert(VT.is256BitVector() && VT.isInteger() &&
15957          "Unsupported value type for operation");
15958
15959   unsigned NumElems = VT.getVectorNumElements();
15960   SDLoc dl(Op);
15961
15962   // Extract the LHS vectors
15963   SDValue LHS = Op.getOperand(0);
15964   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15965   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15966
15967   // Extract the RHS vectors
15968   SDValue RHS = Op.getOperand(1);
15969   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15970   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15971
15972   MVT EltVT = VT.getVectorElementType();
15973   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15974
15975   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15976                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15977                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15978 }
15979
15980 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15981   assert(Op.getSimpleValueType().is256BitVector() &&
15982          Op.getSimpleValueType().isInteger() &&
15983          "Only handle AVX 256-bit vector integer operation");
15984   return Lower256IntArith(Op, DAG);
15985 }
15986
15987 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15988   assert(Op.getSimpleValueType().is256BitVector() &&
15989          Op.getSimpleValueType().isInteger() &&
15990          "Only handle AVX 256-bit vector integer operation");
15991   return Lower256IntArith(Op, DAG);
15992 }
15993
15994 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15995                         SelectionDAG &DAG) {
15996   SDLoc dl(Op);
15997   MVT VT = Op.getSimpleValueType();
15998
15999   // Decompose 256-bit ops into smaller 128-bit ops.
16000   if (VT.is256BitVector() && !Subtarget->hasInt256())
16001     return Lower256IntArith(Op, DAG);
16002
16003   SDValue A = Op.getOperand(0);
16004   SDValue B = Op.getOperand(1);
16005
16006   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16007   if (VT == MVT::v4i32) {
16008     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16009            "Should not custom lower when pmuldq is available!");
16010
16011     // Extract the odd parts.
16012     static const int UnpackMask[] = { 1, -1, 3, -1 };
16013     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16014     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16015
16016     // Multiply the even parts.
16017     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16018     // Now multiply odd parts.
16019     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16020
16021     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16022     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16023
16024     // Merge the two vectors back together with a shuffle. This expands into 2
16025     // shuffles.
16026     static const int ShufMask[] = { 0, 4, 2, 6 };
16027     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16028   }
16029
16030   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16031          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16032
16033   //  Ahi = psrlqi(a, 32);
16034   //  Bhi = psrlqi(b, 32);
16035   //
16036   //  AloBlo = pmuludq(a, b);
16037   //  AloBhi = pmuludq(a, Bhi);
16038   //  AhiBlo = pmuludq(Ahi, b);
16039
16040   //  AloBhi = psllqi(AloBhi, 32);
16041   //  AhiBlo = psllqi(AhiBlo, 32);
16042   //  return AloBlo + AloBhi + AhiBlo;
16043
16044   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16045   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16046
16047   // Bit cast to 32-bit vectors for MULUDQ
16048   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16049                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16050   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16051   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16052   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16053   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16054
16055   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16056   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16057   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16058
16059   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16060   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16061
16062   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16063   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16064 }
16065
16066 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16067   assert(Subtarget->isTargetWin64() && "Unexpected target");
16068   EVT VT = Op.getValueType();
16069   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16070          "Unexpected return type for lowering");
16071
16072   RTLIB::Libcall LC;
16073   bool isSigned;
16074   switch (Op->getOpcode()) {
16075   default: llvm_unreachable("Unexpected request for libcall!");
16076   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16077   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16078   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16079   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16080   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16081   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16082   }
16083
16084   SDLoc dl(Op);
16085   SDValue InChain = DAG.getEntryNode();
16086
16087   TargetLowering::ArgListTy Args;
16088   TargetLowering::ArgListEntry Entry;
16089   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16090     EVT ArgVT = Op->getOperand(i).getValueType();
16091     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16092            "Unexpected argument type for lowering");
16093     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16094     Entry.Node = StackPtr;
16095     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16096                            false, false, 16);
16097     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16098     Entry.Ty = PointerType::get(ArgTy,0);
16099     Entry.isSExt = false;
16100     Entry.isZExt = false;
16101     Args.push_back(Entry);
16102   }
16103
16104   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16105                                          getPointerTy());
16106
16107   TargetLowering::CallLoweringInfo CLI(DAG);
16108   CLI.setDebugLoc(dl).setChain(InChain)
16109     .setCallee(getLibcallCallingConv(LC),
16110                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16111                Callee, std::move(Args), 0)
16112     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16113
16114   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16115   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16116 }
16117
16118 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16119                              SelectionDAG &DAG) {
16120   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16121   EVT VT = Op0.getValueType();
16122   SDLoc dl(Op);
16123
16124   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16125          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16126
16127   // PMULxD operations multiply each even value (starting at 0) of LHS with
16128   // the related value of RHS and produce a widen result.
16129   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16130   // => <2 x i64> <ae|cg>
16131   //
16132   // In other word, to have all the results, we need to perform two PMULxD:
16133   // 1. one with the even values.
16134   // 2. one with the odd values.
16135   // To achieve #2, with need to place the odd values at an even position.
16136   //
16137   // Place the odd value at an even position (basically, shift all values 1
16138   // step to the left):
16139   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16140   // <a|b|c|d> => <b|undef|d|undef>
16141   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16142   // <e|f|g|h> => <f|undef|h|undef>
16143   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16144
16145   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16146   // ints.
16147   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16148   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16149   unsigned Opcode =
16150       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16151   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16152   // => <2 x i64> <ae|cg>
16153   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16154                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16155   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16156   // => <2 x i64> <bf|dh>
16157   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16158                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16159
16160   // Shuffle it back into the right order.
16161   SDValue Highs, Lows;
16162   if (VT == MVT::v8i32) {
16163     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16164     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16165     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16166     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16167   } else {
16168     const int HighMask[] = {1, 5, 3, 7};
16169     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16170     const int LowMask[] = {0, 4, 2, 6};
16171     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16172   }
16173
16174   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16175   // unsigned multiply.
16176   if (IsSigned && !Subtarget->hasSSE41()) {
16177     SDValue ShAmt =
16178         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16179     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16180                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16181     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16182                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16183
16184     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16185     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16186   }
16187
16188   // The first result of MUL_LOHI is actually the low value, followed by the
16189   // high value.
16190   SDValue Ops[] = {Lows, Highs};
16191   return DAG.getMergeValues(Ops, dl);
16192 }
16193
16194 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16195                                          const X86Subtarget *Subtarget) {
16196   MVT VT = Op.getSimpleValueType();
16197   SDLoc dl(Op);
16198   SDValue R = Op.getOperand(0);
16199   SDValue Amt = Op.getOperand(1);
16200
16201   // Optimize shl/srl/sra with constant shift amount.
16202   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16203     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16204       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16205
16206       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16207           (Subtarget->hasInt256() &&
16208            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16209           (Subtarget->hasAVX512() &&
16210            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16211         if (Op.getOpcode() == ISD::SHL)
16212           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16213                                             DAG);
16214         if (Op.getOpcode() == ISD::SRL)
16215           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16216                                             DAG);
16217         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16218           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16219                                             DAG);
16220       }
16221
16222       if (VT == MVT::v16i8) {
16223         if (Op.getOpcode() == ISD::SHL) {
16224           // Make a large shift.
16225           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16226                                                    MVT::v8i16, R, ShiftAmt,
16227                                                    DAG);
16228           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16229           // Zero out the rightmost bits.
16230           SmallVector<SDValue, 16> V(16,
16231                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
16232                                                      MVT::i8));
16233           return DAG.getNode(ISD::AND, dl, VT, SHL,
16234                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16235         }
16236         if (Op.getOpcode() == ISD::SRL) {
16237           // Make a large shift.
16238           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16239                                                    MVT::v8i16, R, ShiftAmt,
16240                                                    DAG);
16241           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16242           // Zero out the leftmost bits.
16243           SmallVector<SDValue, 16> V(16,
16244                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16245                                                      MVT::i8));
16246           return DAG.getNode(ISD::AND, dl, VT, SRL,
16247                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16248         }
16249         if (Op.getOpcode() == ISD::SRA) {
16250           if (ShiftAmt == 7) {
16251             // R s>> 7  ===  R s< 0
16252             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16253             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16254           }
16255
16256           // R s>> a === ((R u>> a) ^ m) - m
16257           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16258           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
16259                                                          MVT::i8));
16260           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16261           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16262           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16263           return Res;
16264         }
16265         llvm_unreachable("Unknown shift opcode.");
16266       }
16267
16268       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
16269         if (Op.getOpcode() == ISD::SHL) {
16270           // Make a large shift.
16271           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16272                                                    MVT::v16i16, R, ShiftAmt,
16273                                                    DAG);
16274           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16275           // Zero out the rightmost bits.
16276           SmallVector<SDValue, 32> V(32,
16277                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
16278                                                      MVT::i8));
16279           return DAG.getNode(ISD::AND, dl, VT, SHL,
16280                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16281         }
16282         if (Op.getOpcode() == ISD::SRL) {
16283           // Make a large shift.
16284           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16285                                                    MVT::v16i16, R, ShiftAmt,
16286                                                    DAG);
16287           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16288           // Zero out the leftmost bits.
16289           SmallVector<SDValue, 32> V(32,
16290                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16291                                                      MVT::i8));
16292           return DAG.getNode(ISD::AND, dl, VT, SRL,
16293                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16294         }
16295         if (Op.getOpcode() == ISD::SRA) {
16296           if (ShiftAmt == 7) {
16297             // R s>> 7  ===  R s< 0
16298             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16299             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16300           }
16301
16302           // R s>> a === ((R u>> a) ^ m) - m
16303           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16304           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
16305                                                          MVT::i8));
16306           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16307           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16308           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16309           return Res;
16310         }
16311         llvm_unreachable("Unknown shift opcode.");
16312       }
16313     }
16314   }
16315
16316   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16317   if (!Subtarget->is64Bit() &&
16318       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16319       Amt.getOpcode() == ISD::BITCAST &&
16320       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16321     Amt = Amt.getOperand(0);
16322     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16323                      VT.getVectorNumElements();
16324     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16325     uint64_t ShiftAmt = 0;
16326     for (unsigned i = 0; i != Ratio; ++i) {
16327       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16328       if (!C)
16329         return SDValue();
16330       // 6 == Log2(64)
16331       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16332     }
16333     // Check remaining shift amounts.
16334     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16335       uint64_t ShAmt = 0;
16336       for (unsigned j = 0; j != Ratio; ++j) {
16337         ConstantSDNode *C =
16338           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16339         if (!C)
16340           return SDValue();
16341         // 6 == Log2(64)
16342         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16343       }
16344       if (ShAmt != ShiftAmt)
16345         return SDValue();
16346     }
16347     switch (Op.getOpcode()) {
16348     default:
16349       llvm_unreachable("Unknown shift opcode!");
16350     case ISD::SHL:
16351       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16352                                         DAG);
16353     case ISD::SRL:
16354       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16355                                         DAG);
16356     case ISD::SRA:
16357       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16358                                         DAG);
16359     }
16360   }
16361
16362   return SDValue();
16363 }
16364
16365 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16366                                         const X86Subtarget* Subtarget) {
16367   MVT VT = Op.getSimpleValueType();
16368   SDLoc dl(Op);
16369   SDValue R = Op.getOperand(0);
16370   SDValue Amt = Op.getOperand(1);
16371
16372   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16373       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16374       (Subtarget->hasInt256() &&
16375        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16376         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16377        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16378     SDValue BaseShAmt;
16379     EVT EltVT = VT.getVectorElementType();
16380
16381     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16382       unsigned NumElts = VT.getVectorNumElements();
16383       unsigned i, j;
16384       for (i = 0; i != NumElts; ++i) {
16385         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
16386           continue;
16387         break;
16388       }
16389       for (j = i; j != NumElts; ++j) {
16390         SDValue Arg = Amt.getOperand(j);
16391         if (Arg.getOpcode() == ISD::UNDEF) continue;
16392         if (Arg != Amt.getOperand(i))
16393           break;
16394       }
16395       if (i != NumElts && j == NumElts)
16396         BaseShAmt = Amt.getOperand(i);
16397     } else {
16398       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16399         Amt = Amt.getOperand(0);
16400       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
16401                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
16402         SDValue InVec = Amt.getOperand(0);
16403         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16404           unsigned NumElts = InVec.getValueType().getVectorNumElements();
16405           unsigned i = 0;
16406           for (; i != NumElts; ++i) {
16407             SDValue Arg = InVec.getOperand(i);
16408             if (Arg.getOpcode() == ISD::UNDEF) continue;
16409             BaseShAmt = Arg;
16410             break;
16411           }
16412         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16413            if (ConstantSDNode *C =
16414                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16415              unsigned SplatIdx =
16416                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16417              if (C->getZExtValue() == SplatIdx)
16418                BaseShAmt = InVec.getOperand(1);
16419            }
16420         }
16421         if (!BaseShAmt.getNode())
16422           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16423                                   DAG.getIntPtrConstant(0));
16424       }
16425     }
16426
16427     if (BaseShAmt.getNode()) {
16428       if (EltVT.bitsGT(MVT::i32))
16429         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16430       else if (EltVT.bitsLT(MVT::i32))
16431         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16432
16433       switch (Op.getOpcode()) {
16434       default:
16435         llvm_unreachable("Unknown shift opcode!");
16436       case ISD::SHL:
16437         switch (VT.SimpleTy) {
16438         default: return SDValue();
16439         case MVT::v2i64:
16440         case MVT::v4i32:
16441         case MVT::v8i16:
16442         case MVT::v4i64:
16443         case MVT::v8i32:
16444         case MVT::v16i16:
16445         case MVT::v16i32:
16446         case MVT::v8i64:
16447           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16448         }
16449       case ISD::SRA:
16450         switch (VT.SimpleTy) {
16451         default: return SDValue();
16452         case MVT::v4i32:
16453         case MVT::v8i16:
16454         case MVT::v8i32:
16455         case MVT::v16i16:
16456         case MVT::v16i32:
16457         case MVT::v8i64:
16458           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16459         }
16460       case ISD::SRL:
16461         switch (VT.SimpleTy) {
16462         default: return SDValue();
16463         case MVT::v2i64:
16464         case MVT::v4i32:
16465         case MVT::v8i16:
16466         case MVT::v4i64:
16467         case MVT::v8i32:
16468         case MVT::v16i16:
16469         case MVT::v16i32:
16470         case MVT::v8i64:
16471           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16472         }
16473       }
16474     }
16475   }
16476
16477   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16478   if (!Subtarget->is64Bit() &&
16479       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16480       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16481       Amt.getOpcode() == ISD::BITCAST &&
16482       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16483     Amt = Amt.getOperand(0);
16484     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16485                      VT.getVectorNumElements();
16486     std::vector<SDValue> Vals(Ratio);
16487     for (unsigned i = 0; i != Ratio; ++i)
16488       Vals[i] = Amt.getOperand(i);
16489     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16490       for (unsigned j = 0; j != Ratio; ++j)
16491         if (Vals[j] != Amt.getOperand(i + j))
16492           return SDValue();
16493     }
16494     switch (Op.getOpcode()) {
16495     default:
16496       llvm_unreachable("Unknown shift opcode!");
16497     case ISD::SHL:
16498       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16499     case ISD::SRL:
16500       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16501     case ISD::SRA:
16502       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16503     }
16504   }
16505
16506   return SDValue();
16507 }
16508
16509 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16510                           SelectionDAG &DAG) {
16511   MVT VT = Op.getSimpleValueType();
16512   SDLoc dl(Op);
16513   SDValue R = Op.getOperand(0);
16514   SDValue Amt = Op.getOperand(1);
16515   SDValue V;
16516
16517   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16518   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16519
16520   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16521   if (V.getNode())
16522     return V;
16523
16524   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16525   if (V.getNode())
16526       return V;
16527
16528   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16529     return Op;
16530   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16531   if (Subtarget->hasInt256()) {
16532     if (Op.getOpcode() == ISD::SRL &&
16533         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16534          VT == MVT::v4i64 || VT == MVT::v8i32))
16535       return Op;
16536     if (Op.getOpcode() == ISD::SHL &&
16537         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16538          VT == MVT::v4i64 || VT == MVT::v8i32))
16539       return Op;
16540     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16541       return Op;
16542   }
16543
16544   // If possible, lower this packed shift into a vector multiply instead of
16545   // expanding it into a sequence of scalar shifts.
16546   // Do this only if the vector shift count is a constant build_vector.
16547   if (Op.getOpcode() == ISD::SHL && 
16548       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16549        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16550       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16551     SmallVector<SDValue, 8> Elts;
16552     EVT SVT = VT.getScalarType();
16553     unsigned SVTBits = SVT.getSizeInBits();
16554     const APInt &One = APInt(SVTBits, 1);
16555     unsigned NumElems = VT.getVectorNumElements();
16556
16557     for (unsigned i=0; i !=NumElems; ++i) {
16558       SDValue Op = Amt->getOperand(i);
16559       if (Op->getOpcode() == ISD::UNDEF) {
16560         Elts.push_back(Op);
16561         continue;
16562       }
16563
16564       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16565       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16566       uint64_t ShAmt = C.getZExtValue();
16567       if (ShAmt >= SVTBits) {
16568         Elts.push_back(DAG.getUNDEF(SVT));
16569         continue;
16570       }
16571       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16572     }
16573     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16574     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16575   }
16576
16577   // Lower SHL with variable shift amount.
16578   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16579     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16580
16581     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16582     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16583     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16584     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16585   }
16586
16587   // If possible, lower this shift as a sequence of two shifts by
16588   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16589   // Example:
16590   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16591   //
16592   // Could be rewritten as:
16593   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16594   //
16595   // The advantage is that the two shifts from the example would be
16596   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16597   // the vector shift into four scalar shifts plus four pairs of vector
16598   // insert/extract.
16599   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16600       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16601     unsigned TargetOpcode = X86ISD::MOVSS;
16602     bool CanBeSimplified;
16603     // The splat value for the first packed shift (the 'X' from the example).
16604     SDValue Amt1 = Amt->getOperand(0);
16605     // The splat value for the second packed shift (the 'Y' from the example).
16606     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16607                                         Amt->getOperand(2);
16608
16609     // See if it is possible to replace this node with a sequence of
16610     // two shifts followed by a MOVSS/MOVSD
16611     if (VT == MVT::v4i32) {
16612       // Check if it is legal to use a MOVSS.
16613       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16614                         Amt2 == Amt->getOperand(3);
16615       if (!CanBeSimplified) {
16616         // Otherwise, check if we can still simplify this node using a MOVSD.
16617         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16618                           Amt->getOperand(2) == Amt->getOperand(3);
16619         TargetOpcode = X86ISD::MOVSD;
16620         Amt2 = Amt->getOperand(2);
16621       }
16622     } else {
16623       // Do similar checks for the case where the machine value type
16624       // is MVT::v8i16.
16625       CanBeSimplified = Amt1 == Amt->getOperand(1);
16626       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16627         CanBeSimplified = Amt2 == Amt->getOperand(i);
16628
16629       if (!CanBeSimplified) {
16630         TargetOpcode = X86ISD::MOVSD;
16631         CanBeSimplified = true;
16632         Amt2 = Amt->getOperand(4);
16633         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16634           CanBeSimplified = Amt1 == Amt->getOperand(i);
16635         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16636           CanBeSimplified = Amt2 == Amt->getOperand(j);
16637       }
16638     }
16639     
16640     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16641         isa<ConstantSDNode>(Amt2)) {
16642       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16643       EVT CastVT = MVT::v4i32;
16644       SDValue Splat1 = 
16645         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16646       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16647       SDValue Splat2 = 
16648         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16649       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16650       if (TargetOpcode == X86ISD::MOVSD)
16651         CastVT = MVT::v2i64;
16652       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16653       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16654       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16655                                             BitCast1, DAG);
16656       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16657     }
16658   }
16659
16660   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16661     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16662
16663     // a = a << 5;
16664     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16665     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16666
16667     // Turn 'a' into a mask suitable for VSELECT
16668     SDValue VSelM = DAG.getConstant(0x80, VT);
16669     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16670     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16671
16672     SDValue CM1 = DAG.getConstant(0x0f, VT);
16673     SDValue CM2 = DAG.getConstant(0x3f, VT);
16674
16675     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16676     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16677     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16678     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16679     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16680
16681     // a += a
16682     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16683     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16684     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16685
16686     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16687     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16688     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16689     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16690     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16691
16692     // a += a
16693     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16694     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16695     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16696
16697     // return VSELECT(r, r+r, a);
16698     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16699                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16700     return R;
16701   }
16702
16703   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16704   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16705   // solution better.
16706   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16707     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16708     unsigned ExtOpc =
16709         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16710     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16711     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16712     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16713                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16714     }
16715
16716   // Decompose 256-bit shifts into smaller 128-bit shifts.
16717   if (VT.is256BitVector()) {
16718     unsigned NumElems = VT.getVectorNumElements();
16719     MVT EltVT = VT.getVectorElementType();
16720     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16721
16722     // Extract the two vectors
16723     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16724     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16725
16726     // Recreate the shift amount vectors
16727     SDValue Amt1, Amt2;
16728     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16729       // Constant shift amount
16730       SmallVector<SDValue, 4> Amt1Csts;
16731       SmallVector<SDValue, 4> Amt2Csts;
16732       for (unsigned i = 0; i != NumElems/2; ++i)
16733         Amt1Csts.push_back(Amt->getOperand(i));
16734       for (unsigned i = NumElems/2; i != NumElems; ++i)
16735         Amt2Csts.push_back(Amt->getOperand(i));
16736
16737       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16738       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16739     } else {
16740       // Variable shift amount
16741       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16742       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16743     }
16744
16745     // Issue new vector shifts for the smaller types
16746     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16747     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16748
16749     // Concatenate the result back
16750     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16751   }
16752
16753   return SDValue();
16754 }
16755
16756 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16757   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16758   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16759   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16760   // has only one use.
16761   SDNode *N = Op.getNode();
16762   SDValue LHS = N->getOperand(0);
16763   SDValue RHS = N->getOperand(1);
16764   unsigned BaseOp = 0;
16765   unsigned Cond = 0;
16766   SDLoc DL(Op);
16767   switch (Op.getOpcode()) {
16768   default: llvm_unreachable("Unknown ovf instruction!");
16769   case ISD::SADDO:
16770     // A subtract of one will be selected as a INC. Note that INC doesn't
16771     // set CF, so we can't do this for UADDO.
16772     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16773       if (C->isOne()) {
16774         BaseOp = X86ISD::INC;
16775         Cond = X86::COND_O;
16776         break;
16777       }
16778     BaseOp = X86ISD::ADD;
16779     Cond = X86::COND_O;
16780     break;
16781   case ISD::UADDO:
16782     BaseOp = X86ISD::ADD;
16783     Cond = X86::COND_B;
16784     break;
16785   case ISD::SSUBO:
16786     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16787     // set CF, so we can't do this for USUBO.
16788     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16789       if (C->isOne()) {
16790         BaseOp = X86ISD::DEC;
16791         Cond = X86::COND_O;
16792         break;
16793       }
16794     BaseOp = X86ISD::SUB;
16795     Cond = X86::COND_O;
16796     break;
16797   case ISD::USUBO:
16798     BaseOp = X86ISD::SUB;
16799     Cond = X86::COND_B;
16800     break;
16801   case ISD::SMULO:
16802     BaseOp = X86ISD::SMUL;
16803     Cond = X86::COND_O;
16804     break;
16805   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16806     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16807                                  MVT::i32);
16808     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16809
16810     SDValue SetCC =
16811       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16812                   DAG.getConstant(X86::COND_O, MVT::i32),
16813                   SDValue(Sum.getNode(), 2));
16814
16815     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16816   }
16817   }
16818
16819   // Also sets EFLAGS.
16820   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16821   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16822
16823   SDValue SetCC =
16824     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16825                 DAG.getConstant(Cond, MVT::i32),
16826                 SDValue(Sum.getNode(), 1));
16827
16828   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16829 }
16830
16831 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16832                                                   SelectionDAG &DAG) const {
16833   SDLoc dl(Op);
16834   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16835   MVT VT = Op.getSimpleValueType();
16836
16837   if (!Subtarget->hasSSE2() || !VT.isVector())
16838     return SDValue();
16839
16840   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16841                       ExtraVT.getScalarType().getSizeInBits();
16842
16843   switch (VT.SimpleTy) {
16844     default: return SDValue();
16845     case MVT::v8i32:
16846     case MVT::v16i16:
16847       if (!Subtarget->hasFp256())
16848         return SDValue();
16849       if (!Subtarget->hasInt256()) {
16850         // needs to be split
16851         unsigned NumElems = VT.getVectorNumElements();
16852
16853         // Extract the LHS vectors
16854         SDValue LHS = Op.getOperand(0);
16855         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16856         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16857
16858         MVT EltVT = VT.getVectorElementType();
16859         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16860
16861         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16862         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16863         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16864                                    ExtraNumElems/2);
16865         SDValue Extra = DAG.getValueType(ExtraVT);
16866
16867         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16868         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16869
16870         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16871       }
16872       // fall through
16873     case MVT::v4i32:
16874     case MVT::v8i16: {
16875       SDValue Op0 = Op.getOperand(0);
16876       SDValue Op00 = Op0.getOperand(0);
16877       SDValue Tmp1;
16878       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16879       if (Op0.getOpcode() == ISD::BITCAST &&
16880           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16881         // (sext (vzext x)) -> (vsext x)
16882         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16883         if (Tmp1.getNode()) {
16884           EVT ExtraEltVT = ExtraVT.getVectorElementType();
16885           // This folding is only valid when the in-reg type is a vector of i8,
16886           // i16, or i32.
16887           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16888               ExtraEltVT == MVT::i32) {
16889             SDValue Tmp1Op0 = Tmp1.getOperand(0);
16890             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16891                    "This optimization is invalid without a VZEXT.");
16892             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16893           }
16894           Op0 = Tmp1;
16895         }
16896       }
16897
16898       // If the above didn't work, then just use Shift-Left + Shift-Right.
16899       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16900                                         DAG);
16901       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16902                                         DAG);
16903     }
16904   }
16905 }
16906
16907 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16908                                  SelectionDAG &DAG) {
16909   SDLoc dl(Op);
16910   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16911     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16912   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16913     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16914
16915   // The only fence that needs an instruction is a sequentially-consistent
16916   // cross-thread fence.
16917   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16918     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16919     // no-sse2). There isn't any reason to disable it if the target processor
16920     // supports it.
16921     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16922       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16923
16924     SDValue Chain = Op.getOperand(0);
16925     SDValue Zero = DAG.getConstant(0, MVT::i32);
16926     SDValue Ops[] = {
16927       DAG.getRegister(X86::ESP, MVT::i32), // Base
16928       DAG.getTargetConstant(1, MVT::i8),   // Scale
16929       DAG.getRegister(0, MVT::i32),        // Index
16930       DAG.getTargetConstant(0, MVT::i32),  // Disp
16931       DAG.getRegister(0, MVT::i32),        // Segment.
16932       Zero,
16933       Chain
16934     };
16935     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16936     return SDValue(Res, 0);
16937   }
16938
16939   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16940   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16941 }
16942
16943 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16944                              SelectionDAG &DAG) {
16945   MVT T = Op.getSimpleValueType();
16946   SDLoc DL(Op);
16947   unsigned Reg = 0;
16948   unsigned size = 0;
16949   switch(T.SimpleTy) {
16950   default: llvm_unreachable("Invalid value type!");
16951   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16952   case MVT::i16: Reg = X86::AX;  size = 2; break;
16953   case MVT::i32: Reg = X86::EAX; size = 4; break;
16954   case MVT::i64:
16955     assert(Subtarget->is64Bit() && "Node not type legal!");
16956     Reg = X86::RAX; size = 8;
16957     break;
16958   }
16959   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16960                                   Op.getOperand(2), SDValue());
16961   SDValue Ops[] = { cpIn.getValue(0),
16962                     Op.getOperand(1),
16963                     Op.getOperand(3),
16964                     DAG.getTargetConstant(size, MVT::i8),
16965                     cpIn.getValue(1) };
16966   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16967   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16968   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16969                                            Ops, T, MMO);
16970
16971   SDValue cpOut =
16972     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16973   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16974                                       MVT::i32, cpOut.getValue(2));
16975   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16976                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16977
16978   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16979   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16980   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16981   return SDValue();
16982 }
16983
16984 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16985                             SelectionDAG &DAG) {
16986   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16987   MVT DstVT = Op.getSimpleValueType();
16988
16989   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16990     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16991     if (DstVT != MVT::f64)
16992       // This conversion needs to be expanded.
16993       return SDValue();
16994
16995     SDValue InVec = Op->getOperand(0);
16996     SDLoc dl(Op);
16997     unsigned NumElts = SrcVT.getVectorNumElements();
16998     EVT SVT = SrcVT.getVectorElementType();
16999
17000     // Widen the vector in input in the case of MVT::v2i32.
17001     // Example: from MVT::v2i32 to MVT::v4i32.
17002     SmallVector<SDValue, 16> Elts;
17003     for (unsigned i = 0, e = NumElts; i != e; ++i)
17004       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17005                                  DAG.getIntPtrConstant(i)));
17006
17007     // Explicitly mark the extra elements as Undef.
17008     SDValue Undef = DAG.getUNDEF(SVT);
17009     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
17010       Elts.push_back(Undef);
17011
17012     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17013     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17014     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17015     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17016                        DAG.getIntPtrConstant(0));
17017   }
17018
17019   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17020          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17021   assert((DstVT == MVT::i64 ||
17022           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17023          "Unexpected custom BITCAST");
17024   // i64 <=> MMX conversions are Legal.
17025   if (SrcVT==MVT::i64 && DstVT.isVector())
17026     return Op;
17027   if (DstVT==MVT::i64 && SrcVT.isVector())
17028     return Op;
17029   // MMX <=> MMX conversions are Legal.
17030   if (SrcVT.isVector() && DstVT.isVector())
17031     return Op;
17032   // All other conversions need to be expanded.
17033   return SDValue();
17034 }
17035
17036 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17037   SDNode *Node = Op.getNode();
17038   SDLoc dl(Node);
17039   EVT T = Node->getValueType(0);
17040   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17041                               DAG.getConstant(0, T), Node->getOperand(2));
17042   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17043                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17044                        Node->getOperand(0),
17045                        Node->getOperand(1), negOp,
17046                        cast<AtomicSDNode>(Node)->getMemOperand(),
17047                        cast<AtomicSDNode>(Node)->getOrdering(),
17048                        cast<AtomicSDNode>(Node)->getSynchScope());
17049 }
17050
17051 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17052   SDNode *Node = Op.getNode();
17053   SDLoc dl(Node);
17054   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17055
17056   // Convert seq_cst store -> xchg
17057   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17058   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17059   //        (The only way to get a 16-byte store is cmpxchg16b)
17060   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17061   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17062       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17063     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17064                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17065                                  Node->getOperand(0),
17066                                  Node->getOperand(1), Node->getOperand(2),
17067                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17068                                  cast<AtomicSDNode>(Node)->getOrdering(),
17069                                  cast<AtomicSDNode>(Node)->getSynchScope());
17070     return Swap.getValue(1);
17071   }
17072   // Other atomic stores have a simple pattern.
17073   return Op;
17074 }
17075
17076 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17077   EVT VT = Op.getNode()->getSimpleValueType(0);
17078
17079   // Let legalize expand this if it isn't a legal type yet.
17080   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17081     return SDValue();
17082
17083   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17084
17085   unsigned Opc;
17086   bool ExtraOp = false;
17087   switch (Op.getOpcode()) {
17088   default: llvm_unreachable("Invalid code");
17089   case ISD::ADDC: Opc = X86ISD::ADD; break;
17090   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17091   case ISD::SUBC: Opc = X86ISD::SUB; break;
17092   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17093   }
17094
17095   if (!ExtraOp)
17096     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17097                        Op.getOperand(1));
17098   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17099                      Op.getOperand(1), Op.getOperand(2));
17100 }
17101
17102 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17103                             SelectionDAG &DAG) {
17104   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17105
17106   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17107   // which returns the values as { float, float } (in XMM0) or
17108   // { double, double } (which is returned in XMM0, XMM1).
17109   SDLoc dl(Op);
17110   SDValue Arg = Op.getOperand(0);
17111   EVT ArgVT = Arg.getValueType();
17112   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17113
17114   TargetLowering::ArgListTy Args;
17115   TargetLowering::ArgListEntry Entry;
17116
17117   Entry.Node = Arg;
17118   Entry.Ty = ArgTy;
17119   Entry.isSExt = false;
17120   Entry.isZExt = false;
17121   Args.push_back(Entry);
17122
17123   bool isF64 = ArgVT == MVT::f64;
17124   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17125   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17126   // the results are returned via SRet in memory.
17127   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17128   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17129   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17130
17131   Type *RetTy = isF64
17132     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
17133     : (Type*)VectorType::get(ArgTy, 4);
17134
17135   TargetLowering::CallLoweringInfo CLI(DAG);
17136   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17137     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17138
17139   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17140
17141   if (isF64)
17142     // Returned in xmm0 and xmm1.
17143     return CallResult.first;
17144
17145   // Returned in bits 0:31 and 32:64 xmm0.
17146   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17147                                CallResult.first, DAG.getIntPtrConstant(0));
17148   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17149                                CallResult.first, DAG.getIntPtrConstant(1));
17150   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17151   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17152 }
17153
17154 /// LowerOperation - Provide custom lowering hooks for some operations.
17155 ///
17156 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17157   switch (Op.getOpcode()) {
17158   default: llvm_unreachable("Should not custom lower this!");
17159   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
17160   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17161   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17162     return LowerCMP_SWAP(Op, Subtarget, DAG);
17163   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17164   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17165   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17166   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
17167   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
17168   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17169   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17170   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17171   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17172   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17173   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17174   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17175   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17176   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17177   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17178   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17179   case ISD::SHL_PARTS:
17180   case ISD::SRA_PARTS:
17181   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17182   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17183   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17184   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17185   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17186   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17187   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17188   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17189   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17190   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17191   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17192   case ISD::FABS:               return LowerFABS(Op, DAG);
17193   case ISD::FNEG:               return LowerFNEG(Op, DAG);
17194   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17195   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17196   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17197   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17198   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17199   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17200   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17201   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17202   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17203   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
17204   case ISD::INTRINSIC_VOID:
17205   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17206   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17207   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17208   case ISD::FRAME_TO_ARGS_OFFSET:
17209                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17210   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17211   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17212   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17213   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17214   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17215   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17216   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17217   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17218   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17219   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17220   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17221   case ISD::UMUL_LOHI:
17222   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17223   case ISD::SRA:
17224   case ISD::SRL:
17225   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17226   case ISD::SADDO:
17227   case ISD::UADDO:
17228   case ISD::SSUBO:
17229   case ISD::USUBO:
17230   case ISD::SMULO:
17231   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17232   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17233   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17234   case ISD::ADDC:
17235   case ISD::ADDE:
17236   case ISD::SUBC:
17237   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17238   case ISD::ADD:                return LowerADD(Op, DAG);
17239   case ISD::SUB:                return LowerSUB(Op, DAG);
17240   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17241   }
17242 }
17243
17244 static void ReplaceATOMIC_LOAD(SDNode *Node,
17245                                SmallVectorImpl<SDValue> &Results,
17246                                SelectionDAG &DAG) {
17247   SDLoc dl(Node);
17248   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17249
17250   // Convert wide load -> cmpxchg8b/cmpxchg16b
17251   // FIXME: On 32-bit, load -> fild or movq would be more efficient
17252   //        (The only way to get a 16-byte load is cmpxchg16b)
17253   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
17254   SDValue Zero = DAG.getConstant(0, VT);
17255   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
17256   SDValue Swap =
17257       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
17258                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
17259                            cast<AtomicSDNode>(Node)->getMemOperand(),
17260                            cast<AtomicSDNode>(Node)->getOrdering(),
17261                            cast<AtomicSDNode>(Node)->getOrdering(),
17262                            cast<AtomicSDNode>(Node)->getSynchScope());
17263   Results.push_back(Swap.getValue(0));
17264   Results.push_back(Swap.getValue(2));
17265 }
17266
17267 /// ReplaceNodeResults - Replace a node with an illegal result type
17268 /// with a new node built out of custom code.
17269 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17270                                            SmallVectorImpl<SDValue>&Results,
17271                                            SelectionDAG &DAG) const {
17272   SDLoc dl(N);
17273   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17274   switch (N->getOpcode()) {
17275   default:
17276     llvm_unreachable("Do not know how to custom type legalize this operation!");
17277   case ISD::SIGN_EXTEND_INREG:
17278   case ISD::ADDC:
17279   case ISD::ADDE:
17280   case ISD::SUBC:
17281   case ISD::SUBE:
17282     // We don't want to expand or promote these.
17283     return;
17284   case ISD::SDIV:
17285   case ISD::UDIV:
17286   case ISD::SREM:
17287   case ISD::UREM:
17288   case ISD::SDIVREM:
17289   case ISD::UDIVREM: {
17290     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17291     Results.push_back(V);
17292     return;
17293   }
17294   case ISD::FP_TO_SINT:
17295   case ISD::FP_TO_UINT: {
17296     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17297
17298     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17299       return;
17300
17301     std::pair<SDValue,SDValue> Vals =
17302         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17303     SDValue FIST = Vals.first, StackSlot = Vals.second;
17304     if (FIST.getNode()) {
17305       EVT VT = N->getValueType(0);
17306       // Return a load from the stack slot.
17307       if (StackSlot.getNode())
17308         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17309                                       MachinePointerInfo(),
17310                                       false, false, false, 0));
17311       else
17312         Results.push_back(FIST);
17313     }
17314     return;
17315   }
17316   case ISD::UINT_TO_FP: {
17317     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17318     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17319         N->getValueType(0) != MVT::v2f32)
17320       return;
17321     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17322                                  N->getOperand(0));
17323     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17324                                      MVT::f64);
17325     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17326     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17327                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17328     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17329     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17330     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17331     return;
17332   }
17333   case ISD::FP_ROUND: {
17334     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17335         return;
17336     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17337     Results.push_back(V);
17338     return;
17339   }
17340   case ISD::INTRINSIC_W_CHAIN: {
17341     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17342     switch (IntNo) {
17343     default : llvm_unreachable("Do not know how to custom type "
17344                                "legalize this intrinsic operation!");
17345     case Intrinsic::x86_rdtsc:
17346       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17347                                      Results);
17348     case Intrinsic::x86_rdtscp:
17349       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17350                                      Results);
17351     case Intrinsic::x86_rdpmc:
17352       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17353     }
17354   }
17355   case ISD::READCYCLECOUNTER: {
17356     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17357                                    Results);
17358   }
17359   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17360     EVT T = N->getValueType(0);
17361     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17362     bool Regs64bit = T == MVT::i128;
17363     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17364     SDValue cpInL, cpInH;
17365     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17366                         DAG.getConstant(0, HalfT));
17367     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17368                         DAG.getConstant(1, HalfT));
17369     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17370                              Regs64bit ? X86::RAX : X86::EAX,
17371                              cpInL, SDValue());
17372     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17373                              Regs64bit ? X86::RDX : X86::EDX,
17374                              cpInH, cpInL.getValue(1));
17375     SDValue swapInL, swapInH;
17376     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17377                           DAG.getConstant(0, HalfT));
17378     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17379                           DAG.getConstant(1, HalfT));
17380     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17381                                Regs64bit ? X86::RBX : X86::EBX,
17382                                swapInL, cpInH.getValue(1));
17383     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17384                                Regs64bit ? X86::RCX : X86::ECX,
17385                                swapInH, swapInL.getValue(1));
17386     SDValue Ops[] = { swapInH.getValue(0),
17387                       N->getOperand(1),
17388                       swapInH.getValue(1) };
17389     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17390     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17391     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17392                                   X86ISD::LCMPXCHG8_DAG;
17393     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17394     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17395                                         Regs64bit ? X86::RAX : X86::EAX,
17396                                         HalfT, Result.getValue(1));
17397     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17398                                         Regs64bit ? X86::RDX : X86::EDX,
17399                                         HalfT, cpOutL.getValue(2));
17400     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17401
17402     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17403                                         MVT::i32, cpOutH.getValue(2));
17404     SDValue Success =
17405         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17406                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17407     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17408
17409     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17410     Results.push_back(Success);
17411     Results.push_back(EFLAGS.getValue(1));
17412     return;
17413   }
17414   case ISD::ATOMIC_SWAP:
17415   case ISD::ATOMIC_LOAD_ADD:
17416   case ISD::ATOMIC_LOAD_SUB:
17417   case ISD::ATOMIC_LOAD_AND:
17418   case ISD::ATOMIC_LOAD_OR:
17419   case ISD::ATOMIC_LOAD_XOR:
17420   case ISD::ATOMIC_LOAD_NAND:
17421   case ISD::ATOMIC_LOAD_MIN:
17422   case ISD::ATOMIC_LOAD_MAX:
17423   case ISD::ATOMIC_LOAD_UMIN:
17424   case ISD::ATOMIC_LOAD_UMAX:
17425     // Delegate to generic TypeLegalization. Situations we can really handle
17426     // should have already been dealt with by X86AtomicExpandPass.cpp.
17427     break;
17428   case ISD::ATOMIC_LOAD: {
17429     ReplaceATOMIC_LOAD(N, Results, DAG);
17430     return;
17431   }
17432   case ISD::BITCAST: {
17433     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17434     EVT DstVT = N->getValueType(0);
17435     EVT SrcVT = N->getOperand(0)->getValueType(0);
17436
17437     if (SrcVT != MVT::f64 ||
17438         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17439       return;
17440
17441     unsigned NumElts = DstVT.getVectorNumElements();
17442     EVT SVT = DstVT.getVectorElementType();
17443     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17444     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17445                                    MVT::v2f64, N->getOperand(0));
17446     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17447
17448     if (ExperimentalVectorWideningLegalization) {
17449       // If we are legalizing vectors by widening, we already have the desired
17450       // legal vector type, just return it.
17451       Results.push_back(ToVecInt);
17452       return;
17453     }
17454
17455     SmallVector<SDValue, 8> Elts;
17456     for (unsigned i = 0, e = NumElts; i != e; ++i)
17457       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17458                                    ToVecInt, DAG.getIntPtrConstant(i)));
17459
17460     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17461   }
17462   }
17463 }
17464
17465 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17466   switch (Opcode) {
17467   default: return nullptr;
17468   case X86ISD::BSF:                return "X86ISD::BSF";
17469   case X86ISD::BSR:                return "X86ISD::BSR";
17470   case X86ISD::SHLD:               return "X86ISD::SHLD";
17471   case X86ISD::SHRD:               return "X86ISD::SHRD";
17472   case X86ISD::FAND:               return "X86ISD::FAND";
17473   case X86ISD::FANDN:              return "X86ISD::FANDN";
17474   case X86ISD::FOR:                return "X86ISD::FOR";
17475   case X86ISD::FXOR:               return "X86ISD::FXOR";
17476   case X86ISD::FSRL:               return "X86ISD::FSRL";
17477   case X86ISD::FILD:               return "X86ISD::FILD";
17478   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17479   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17480   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17481   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17482   case X86ISD::FLD:                return "X86ISD::FLD";
17483   case X86ISD::FST:                return "X86ISD::FST";
17484   case X86ISD::CALL:               return "X86ISD::CALL";
17485   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17486   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17487   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17488   case X86ISD::BT:                 return "X86ISD::BT";
17489   case X86ISD::CMP:                return "X86ISD::CMP";
17490   case X86ISD::COMI:               return "X86ISD::COMI";
17491   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17492   case X86ISD::CMPM:               return "X86ISD::CMPM";
17493   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17494   case X86ISD::SETCC:              return "X86ISD::SETCC";
17495   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17496   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17497   case X86ISD::CMOV:               return "X86ISD::CMOV";
17498   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17499   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17500   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17501   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17502   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17503   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17504   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17505   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17506   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17507   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17508   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17509   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17510   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17511   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17512   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17513   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
17514   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17515   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17516   case X86ISD::HADD:               return "X86ISD::HADD";
17517   case X86ISD::HSUB:               return "X86ISD::HSUB";
17518   case X86ISD::FHADD:              return "X86ISD::FHADD";
17519   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17520   case X86ISD::UMAX:               return "X86ISD::UMAX";
17521   case X86ISD::UMIN:               return "X86ISD::UMIN";
17522   case X86ISD::SMAX:               return "X86ISD::SMAX";
17523   case X86ISD::SMIN:               return "X86ISD::SMIN";
17524   case X86ISD::FMAX:               return "X86ISD::FMAX";
17525   case X86ISD::FMIN:               return "X86ISD::FMIN";
17526   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17527   case X86ISD::FMINC:              return "X86ISD::FMINC";
17528   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17529   case X86ISD::FRCP:               return "X86ISD::FRCP";
17530   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17531   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17532   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17533   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17534   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17535   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17536   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17537   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17538   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17539   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17540   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17541   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17542   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17543   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17544   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17545   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17546   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17547   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17548   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17549   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17550   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17551   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17552   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17553   case X86ISD::VSHL:               return "X86ISD::VSHL";
17554   case X86ISD::VSRL:               return "X86ISD::VSRL";
17555   case X86ISD::VSRA:               return "X86ISD::VSRA";
17556   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17557   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17558   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17559   case X86ISD::CMPP:               return "X86ISD::CMPP";
17560   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17561   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17562   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17563   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17564   case X86ISD::ADD:                return "X86ISD::ADD";
17565   case X86ISD::SUB:                return "X86ISD::SUB";
17566   case X86ISD::ADC:                return "X86ISD::ADC";
17567   case X86ISD::SBB:                return "X86ISD::SBB";
17568   case X86ISD::SMUL:               return "X86ISD::SMUL";
17569   case X86ISD::UMUL:               return "X86ISD::UMUL";
17570   case X86ISD::INC:                return "X86ISD::INC";
17571   case X86ISD::DEC:                return "X86ISD::DEC";
17572   case X86ISD::OR:                 return "X86ISD::OR";
17573   case X86ISD::XOR:                return "X86ISD::XOR";
17574   case X86ISD::AND:                return "X86ISD::AND";
17575   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17576   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17577   case X86ISD::PTEST:              return "X86ISD::PTEST";
17578   case X86ISD::TESTP:              return "X86ISD::TESTP";
17579   case X86ISD::TESTM:              return "X86ISD::TESTM";
17580   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17581   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17582   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17583   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17584   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17585   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17586   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17587   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17588   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17589   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17590   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17591   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17592   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17593   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17594   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17595   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17596   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17597   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17598   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17599   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17600   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17601   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17602   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17603   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17604   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17605   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
17606   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17607   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17608   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17609   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17610   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17611   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17612   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17613   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17614   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17615   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17616   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17617   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17618   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17619   case X86ISD::SAHF:               return "X86ISD::SAHF";
17620   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17621   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17622   case X86ISD::FMADD:              return "X86ISD::FMADD";
17623   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17624   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17625   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17626   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17627   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17628   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17629   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17630   case X86ISD::XTEST:              return "X86ISD::XTEST";
17631   }
17632 }
17633
17634 // isLegalAddressingMode - Return true if the addressing mode represented
17635 // by AM is legal for this target, for a load/store of the specified type.
17636 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17637                                               Type *Ty) const {
17638   // X86 supports extremely general addressing modes.
17639   CodeModel::Model M = getTargetMachine().getCodeModel();
17640   Reloc::Model R = getTargetMachine().getRelocationModel();
17641
17642   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17643   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17644     return false;
17645
17646   if (AM.BaseGV) {
17647     unsigned GVFlags =
17648       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17649
17650     // If a reference to this global requires an extra load, we can't fold it.
17651     if (isGlobalStubReference(GVFlags))
17652       return false;
17653
17654     // If BaseGV requires a register for the PIC base, we cannot also have a
17655     // BaseReg specified.
17656     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17657       return false;
17658
17659     // If lower 4G is not available, then we must use rip-relative addressing.
17660     if ((M != CodeModel::Small || R != Reloc::Static) &&
17661         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17662       return false;
17663   }
17664
17665   switch (AM.Scale) {
17666   case 0:
17667   case 1:
17668   case 2:
17669   case 4:
17670   case 8:
17671     // These scales always work.
17672     break;
17673   case 3:
17674   case 5:
17675   case 9:
17676     // These scales are formed with basereg+scalereg.  Only accept if there is
17677     // no basereg yet.
17678     if (AM.HasBaseReg)
17679       return false;
17680     break;
17681   default:  // Other stuff never works.
17682     return false;
17683   }
17684
17685   return true;
17686 }
17687
17688 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17689   unsigned Bits = Ty->getScalarSizeInBits();
17690
17691   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17692   // particularly cheaper than those without.
17693   if (Bits == 8)
17694     return false;
17695
17696   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17697   // variable shifts just as cheap as scalar ones.
17698   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17699     return false;
17700
17701   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17702   // fully general vector.
17703   return true;
17704 }
17705
17706 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17707   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17708     return false;
17709   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17710   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17711   return NumBits1 > NumBits2;
17712 }
17713
17714 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17715   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17716     return false;
17717
17718   if (!isTypeLegal(EVT::getEVT(Ty1)))
17719     return false;
17720
17721   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17722
17723   // Assuming the caller doesn't have a zeroext or signext return parameter,
17724   // truncation all the way down to i1 is valid.
17725   return true;
17726 }
17727
17728 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17729   return isInt<32>(Imm);
17730 }
17731
17732 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17733   // Can also use sub to handle negated immediates.
17734   return isInt<32>(Imm);
17735 }
17736
17737 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17738   if (!VT1.isInteger() || !VT2.isInteger())
17739     return false;
17740   unsigned NumBits1 = VT1.getSizeInBits();
17741   unsigned NumBits2 = VT2.getSizeInBits();
17742   return NumBits1 > NumBits2;
17743 }
17744
17745 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17746   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17747   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17748 }
17749
17750 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17751   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17752   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17753 }
17754
17755 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17756   EVT VT1 = Val.getValueType();
17757   if (isZExtFree(VT1, VT2))
17758     return true;
17759
17760   if (Val.getOpcode() != ISD::LOAD)
17761     return false;
17762
17763   if (!VT1.isSimple() || !VT1.isInteger() ||
17764       !VT2.isSimple() || !VT2.isInteger())
17765     return false;
17766
17767   switch (VT1.getSimpleVT().SimpleTy) {
17768   default: break;
17769   case MVT::i8:
17770   case MVT::i16:
17771   case MVT::i32:
17772     // X86 has 8, 16, and 32-bit zero-extending loads.
17773     return true;
17774   }
17775
17776   return false;
17777 }
17778
17779 bool
17780 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17781   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17782     return false;
17783
17784   VT = VT.getScalarType();
17785
17786   if (!VT.isSimple())
17787     return false;
17788
17789   switch (VT.getSimpleVT().SimpleTy) {
17790   case MVT::f32:
17791   case MVT::f64:
17792     return true;
17793   default:
17794     break;
17795   }
17796
17797   return false;
17798 }
17799
17800 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17801   // i16 instructions are longer (0x66 prefix) and potentially slower.
17802   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17803 }
17804
17805 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17806 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17807 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17808 /// are assumed to be legal.
17809 bool
17810 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17811                                       EVT VT) const {
17812   if (!VT.isSimple())
17813     return false;
17814
17815   MVT SVT = VT.getSimpleVT();
17816
17817   // Very little shuffling can be done for 64-bit vectors right now.
17818   if (VT.getSizeInBits() == 64)
17819     return false;
17820
17821   // If this is a single-input shuffle with no 128 bit lane crossings we can
17822   // lower it into pshufb.
17823   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17824       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17825     bool isLegal = true;
17826     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17827       if (M[I] >= (int)SVT.getVectorNumElements() ||
17828           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17829         isLegal = false;
17830         break;
17831       }
17832     }
17833     if (isLegal)
17834       return true;
17835   }
17836
17837   // FIXME: blends, shifts.
17838   return (SVT.getVectorNumElements() == 2 ||
17839           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17840           isMOVLMask(M, SVT) ||
17841           isMOVHLPSMask(M, SVT) ||
17842           isSHUFPMask(M, SVT) ||
17843           isPSHUFDMask(M, SVT) ||
17844           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17845           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17846           isPALIGNRMask(M, SVT, Subtarget) ||
17847           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17848           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17849           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17850           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17851           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17852 }
17853
17854 bool
17855 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17856                                           EVT VT) const {
17857   if (!VT.isSimple())
17858     return false;
17859
17860   MVT SVT = VT.getSimpleVT();
17861   unsigned NumElts = SVT.getVectorNumElements();
17862   // FIXME: This collection of masks seems suspect.
17863   if (NumElts == 2)
17864     return true;
17865   if (NumElts == 4 && SVT.is128BitVector()) {
17866     return (isMOVLMask(Mask, SVT)  ||
17867             isCommutedMOVLMask(Mask, SVT, true) ||
17868             isSHUFPMask(Mask, SVT) ||
17869             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17870   }
17871   return false;
17872 }
17873
17874 //===----------------------------------------------------------------------===//
17875 //                           X86 Scheduler Hooks
17876 //===----------------------------------------------------------------------===//
17877
17878 /// Utility function to emit xbegin specifying the start of an RTM region.
17879 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17880                                      const TargetInstrInfo *TII) {
17881   DebugLoc DL = MI->getDebugLoc();
17882
17883   const BasicBlock *BB = MBB->getBasicBlock();
17884   MachineFunction::iterator I = MBB;
17885   ++I;
17886
17887   // For the v = xbegin(), we generate
17888   //
17889   // thisMBB:
17890   //  xbegin sinkMBB
17891   //
17892   // mainMBB:
17893   //  eax = -1
17894   //
17895   // sinkMBB:
17896   //  v = eax
17897
17898   MachineBasicBlock *thisMBB = MBB;
17899   MachineFunction *MF = MBB->getParent();
17900   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17901   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17902   MF->insert(I, mainMBB);
17903   MF->insert(I, sinkMBB);
17904
17905   // Transfer the remainder of BB and its successor edges to sinkMBB.
17906   sinkMBB->splice(sinkMBB->begin(), MBB,
17907                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17908   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17909
17910   // thisMBB:
17911   //  xbegin sinkMBB
17912   //  # fallthrough to mainMBB
17913   //  # abortion to sinkMBB
17914   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17915   thisMBB->addSuccessor(mainMBB);
17916   thisMBB->addSuccessor(sinkMBB);
17917
17918   // mainMBB:
17919   //  EAX = -1
17920   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17921   mainMBB->addSuccessor(sinkMBB);
17922
17923   // sinkMBB:
17924   // EAX is live into the sinkMBB
17925   sinkMBB->addLiveIn(X86::EAX);
17926   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17927           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17928     .addReg(X86::EAX);
17929
17930   MI->eraseFromParent();
17931   return sinkMBB;
17932 }
17933
17934 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17935 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17936 // in the .td file.
17937 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17938                                        const TargetInstrInfo *TII) {
17939   unsigned Opc;
17940   switch (MI->getOpcode()) {
17941   default: llvm_unreachable("illegal opcode!");
17942   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17943   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17944   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17945   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17946   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17947   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17948   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17949   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17950   }
17951
17952   DebugLoc dl = MI->getDebugLoc();
17953   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17954
17955   unsigned NumArgs = MI->getNumOperands();
17956   for (unsigned i = 1; i < NumArgs; ++i) {
17957     MachineOperand &Op = MI->getOperand(i);
17958     if (!(Op.isReg() && Op.isImplicit()))
17959       MIB.addOperand(Op);
17960   }
17961   if (MI->hasOneMemOperand())
17962     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17963
17964   BuildMI(*BB, MI, dl,
17965     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17966     .addReg(X86::XMM0);
17967
17968   MI->eraseFromParent();
17969   return BB;
17970 }
17971
17972 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17973 // defs in an instruction pattern
17974 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17975                                        const TargetInstrInfo *TII) {
17976   unsigned Opc;
17977   switch (MI->getOpcode()) {
17978   default: llvm_unreachable("illegal opcode!");
17979   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17980   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17981   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17982   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17983   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17984   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17985   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17986   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17987   }
17988
17989   DebugLoc dl = MI->getDebugLoc();
17990   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17991
17992   unsigned NumArgs = MI->getNumOperands(); // remove the results
17993   for (unsigned i = 1; i < NumArgs; ++i) {
17994     MachineOperand &Op = MI->getOperand(i);
17995     if (!(Op.isReg() && Op.isImplicit()))
17996       MIB.addOperand(Op);
17997   }
17998   if (MI->hasOneMemOperand())
17999     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18000
18001   BuildMI(*BB, MI, dl,
18002     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18003     .addReg(X86::ECX);
18004
18005   MI->eraseFromParent();
18006   return BB;
18007 }
18008
18009 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18010                                        const TargetInstrInfo *TII,
18011                                        const X86Subtarget* Subtarget) {
18012   DebugLoc dl = MI->getDebugLoc();
18013
18014   // Address into RAX/EAX, other two args into ECX, EDX.
18015   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18016   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18017   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18018   for (int i = 0; i < X86::AddrNumOperands; ++i)
18019     MIB.addOperand(MI->getOperand(i));
18020
18021   unsigned ValOps = X86::AddrNumOperands;
18022   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18023     .addReg(MI->getOperand(ValOps).getReg());
18024   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18025     .addReg(MI->getOperand(ValOps+1).getReg());
18026
18027   // The instruction doesn't actually take any operands though.
18028   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18029
18030   MI->eraseFromParent(); // The pseudo is gone now.
18031   return BB;
18032 }
18033
18034 MachineBasicBlock *
18035 X86TargetLowering::EmitVAARG64WithCustomInserter(
18036                    MachineInstr *MI,
18037                    MachineBasicBlock *MBB) const {
18038   // Emit va_arg instruction on X86-64.
18039
18040   // Operands to this pseudo-instruction:
18041   // 0  ) Output        : destination address (reg)
18042   // 1-5) Input         : va_list address (addr, i64mem)
18043   // 6  ) ArgSize       : Size (in bytes) of vararg type
18044   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18045   // 8  ) Align         : Alignment of type
18046   // 9  ) EFLAGS (implicit-def)
18047
18048   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18049   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
18050
18051   unsigned DestReg = MI->getOperand(0).getReg();
18052   MachineOperand &Base = MI->getOperand(1);
18053   MachineOperand &Scale = MI->getOperand(2);
18054   MachineOperand &Index = MI->getOperand(3);
18055   MachineOperand &Disp = MI->getOperand(4);
18056   MachineOperand &Segment = MI->getOperand(5);
18057   unsigned ArgSize = MI->getOperand(6).getImm();
18058   unsigned ArgMode = MI->getOperand(7).getImm();
18059   unsigned Align = MI->getOperand(8).getImm();
18060
18061   // Memory Reference
18062   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18063   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18064   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18065
18066   // Machine Information
18067   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18068   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18069   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18070   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18071   DebugLoc DL = MI->getDebugLoc();
18072
18073   // struct va_list {
18074   //   i32   gp_offset
18075   //   i32   fp_offset
18076   //   i64   overflow_area (address)
18077   //   i64   reg_save_area (address)
18078   // }
18079   // sizeof(va_list) = 24
18080   // alignment(va_list) = 8
18081
18082   unsigned TotalNumIntRegs = 6;
18083   unsigned TotalNumXMMRegs = 8;
18084   bool UseGPOffset = (ArgMode == 1);
18085   bool UseFPOffset = (ArgMode == 2);
18086   unsigned MaxOffset = TotalNumIntRegs * 8 +
18087                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18088
18089   /* Align ArgSize to a multiple of 8 */
18090   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18091   bool NeedsAlign = (Align > 8);
18092
18093   MachineBasicBlock *thisMBB = MBB;
18094   MachineBasicBlock *overflowMBB;
18095   MachineBasicBlock *offsetMBB;
18096   MachineBasicBlock *endMBB;
18097
18098   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18099   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18100   unsigned OffsetReg = 0;
18101
18102   if (!UseGPOffset && !UseFPOffset) {
18103     // If we only pull from the overflow region, we don't create a branch.
18104     // We don't need to alter control flow.
18105     OffsetDestReg = 0; // unused
18106     OverflowDestReg = DestReg;
18107
18108     offsetMBB = nullptr;
18109     overflowMBB = thisMBB;
18110     endMBB = thisMBB;
18111   } else {
18112     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18113     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18114     // If not, pull from overflow_area. (branch to overflowMBB)
18115     //
18116     //       thisMBB
18117     //         |     .
18118     //         |        .
18119     //     offsetMBB   overflowMBB
18120     //         |        .
18121     //         |     .
18122     //        endMBB
18123
18124     // Registers for the PHI in endMBB
18125     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18126     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18127
18128     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18129     MachineFunction *MF = MBB->getParent();
18130     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18131     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18132     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18133
18134     MachineFunction::iterator MBBIter = MBB;
18135     ++MBBIter;
18136
18137     // Insert the new basic blocks
18138     MF->insert(MBBIter, offsetMBB);
18139     MF->insert(MBBIter, overflowMBB);
18140     MF->insert(MBBIter, endMBB);
18141
18142     // Transfer the remainder of MBB and its successor edges to endMBB.
18143     endMBB->splice(endMBB->begin(), thisMBB,
18144                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18145     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18146
18147     // Make offsetMBB and overflowMBB successors of thisMBB
18148     thisMBB->addSuccessor(offsetMBB);
18149     thisMBB->addSuccessor(overflowMBB);
18150
18151     // endMBB is a successor of both offsetMBB and overflowMBB
18152     offsetMBB->addSuccessor(endMBB);
18153     overflowMBB->addSuccessor(endMBB);
18154
18155     // Load the offset value into a register
18156     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18157     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18158       .addOperand(Base)
18159       .addOperand(Scale)
18160       .addOperand(Index)
18161       .addDisp(Disp, UseFPOffset ? 4 : 0)
18162       .addOperand(Segment)
18163       .setMemRefs(MMOBegin, MMOEnd);
18164
18165     // Check if there is enough room left to pull this argument.
18166     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18167       .addReg(OffsetReg)
18168       .addImm(MaxOffset + 8 - ArgSizeA8);
18169
18170     // Branch to "overflowMBB" if offset >= max
18171     // Fall through to "offsetMBB" otherwise
18172     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18173       .addMBB(overflowMBB);
18174   }
18175
18176   // In offsetMBB, emit code to use the reg_save_area.
18177   if (offsetMBB) {
18178     assert(OffsetReg != 0);
18179
18180     // Read the reg_save_area address.
18181     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18182     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18183       .addOperand(Base)
18184       .addOperand(Scale)
18185       .addOperand(Index)
18186       .addDisp(Disp, 16)
18187       .addOperand(Segment)
18188       .setMemRefs(MMOBegin, MMOEnd);
18189
18190     // Zero-extend the offset
18191     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18192       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18193         .addImm(0)
18194         .addReg(OffsetReg)
18195         .addImm(X86::sub_32bit);
18196
18197     // Add the offset to the reg_save_area to get the final address.
18198     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18199       .addReg(OffsetReg64)
18200       .addReg(RegSaveReg);
18201
18202     // Compute the offset for the next argument
18203     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18204     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18205       .addReg(OffsetReg)
18206       .addImm(UseFPOffset ? 16 : 8);
18207
18208     // Store it back into the va_list.
18209     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18210       .addOperand(Base)
18211       .addOperand(Scale)
18212       .addOperand(Index)
18213       .addDisp(Disp, UseFPOffset ? 4 : 0)
18214       .addOperand(Segment)
18215       .addReg(NextOffsetReg)
18216       .setMemRefs(MMOBegin, MMOEnd);
18217
18218     // Jump to endMBB
18219     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
18220       .addMBB(endMBB);
18221   }
18222
18223   //
18224   // Emit code to use overflow area
18225   //
18226
18227   // Load the overflow_area address into a register.
18228   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18229   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18230     .addOperand(Base)
18231     .addOperand(Scale)
18232     .addOperand(Index)
18233     .addDisp(Disp, 8)
18234     .addOperand(Segment)
18235     .setMemRefs(MMOBegin, MMOEnd);
18236
18237   // If we need to align it, do so. Otherwise, just copy the address
18238   // to OverflowDestReg.
18239   if (NeedsAlign) {
18240     // Align the overflow address
18241     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18242     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18243
18244     // aligned_addr = (addr + (align-1)) & ~(align-1)
18245     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18246       .addReg(OverflowAddrReg)
18247       .addImm(Align-1);
18248
18249     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18250       .addReg(TmpReg)
18251       .addImm(~(uint64_t)(Align-1));
18252   } else {
18253     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18254       .addReg(OverflowAddrReg);
18255   }
18256
18257   // Compute the next overflow address after this argument.
18258   // (the overflow address should be kept 8-byte aligned)
18259   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18260   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18261     .addReg(OverflowDestReg)
18262     .addImm(ArgSizeA8);
18263
18264   // Store the new overflow address.
18265   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18266     .addOperand(Base)
18267     .addOperand(Scale)
18268     .addOperand(Index)
18269     .addDisp(Disp, 8)
18270     .addOperand(Segment)
18271     .addReg(NextAddrReg)
18272     .setMemRefs(MMOBegin, MMOEnd);
18273
18274   // If we branched, emit the PHI to the front of endMBB.
18275   if (offsetMBB) {
18276     BuildMI(*endMBB, endMBB->begin(), DL,
18277             TII->get(X86::PHI), DestReg)
18278       .addReg(OffsetDestReg).addMBB(offsetMBB)
18279       .addReg(OverflowDestReg).addMBB(overflowMBB);
18280   }
18281
18282   // Erase the pseudo instruction
18283   MI->eraseFromParent();
18284
18285   return endMBB;
18286 }
18287
18288 MachineBasicBlock *
18289 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18290                                                  MachineInstr *MI,
18291                                                  MachineBasicBlock *MBB) const {
18292   // Emit code to save XMM registers to the stack. The ABI says that the
18293   // number of registers to save is given in %al, so it's theoretically
18294   // possible to do an indirect jump trick to avoid saving all of them,
18295   // however this code takes a simpler approach and just executes all
18296   // of the stores if %al is non-zero. It's less code, and it's probably
18297   // easier on the hardware branch predictor, and stores aren't all that
18298   // expensive anyway.
18299
18300   // Create the new basic blocks. One block contains all the XMM stores,
18301   // and one block is the final destination regardless of whether any
18302   // stores were performed.
18303   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18304   MachineFunction *F = MBB->getParent();
18305   MachineFunction::iterator MBBIter = MBB;
18306   ++MBBIter;
18307   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18308   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18309   F->insert(MBBIter, XMMSaveMBB);
18310   F->insert(MBBIter, EndMBB);
18311
18312   // Transfer the remainder of MBB and its successor edges to EndMBB.
18313   EndMBB->splice(EndMBB->begin(), MBB,
18314                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18315   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18316
18317   // The original block will now fall through to the XMM save block.
18318   MBB->addSuccessor(XMMSaveMBB);
18319   // The XMMSaveMBB will fall through to the end block.
18320   XMMSaveMBB->addSuccessor(EndMBB);
18321
18322   // Now add the instructions.
18323   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18324   DebugLoc DL = MI->getDebugLoc();
18325
18326   unsigned CountReg = MI->getOperand(0).getReg();
18327   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18328   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18329
18330   if (!Subtarget->isTargetWin64()) {
18331     // If %al is 0, branch around the XMM save block.
18332     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18333     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
18334     MBB->addSuccessor(EndMBB);
18335   }
18336
18337   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18338   // that was just emitted, but clearly shouldn't be "saved".
18339   assert((MI->getNumOperands() <= 3 ||
18340           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18341           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18342          && "Expected last argument to be EFLAGS");
18343   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18344   // In the XMM save block, save all the XMM argument registers.
18345   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18346     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18347     MachineMemOperand *MMO =
18348       F->getMachineMemOperand(
18349           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18350         MachineMemOperand::MOStore,
18351         /*Size=*/16, /*Align=*/16);
18352     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18353       .addFrameIndex(RegSaveFrameIndex)
18354       .addImm(/*Scale=*/1)
18355       .addReg(/*IndexReg=*/0)
18356       .addImm(/*Disp=*/Offset)
18357       .addReg(/*Segment=*/0)
18358       .addReg(MI->getOperand(i).getReg())
18359       .addMemOperand(MMO);
18360   }
18361
18362   MI->eraseFromParent();   // The pseudo instruction is gone now.
18363
18364   return EndMBB;
18365 }
18366
18367 // The EFLAGS operand of SelectItr might be missing a kill marker
18368 // because there were multiple uses of EFLAGS, and ISel didn't know
18369 // which to mark. Figure out whether SelectItr should have had a
18370 // kill marker, and set it if it should. Returns the correct kill
18371 // marker value.
18372 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18373                                      MachineBasicBlock* BB,
18374                                      const TargetRegisterInfo* TRI) {
18375   // Scan forward through BB for a use/def of EFLAGS.
18376   MachineBasicBlock::iterator miI(std::next(SelectItr));
18377   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18378     const MachineInstr& mi = *miI;
18379     if (mi.readsRegister(X86::EFLAGS))
18380       return false;
18381     if (mi.definesRegister(X86::EFLAGS))
18382       break; // Should have kill-flag - update below.
18383   }
18384
18385   // If we hit the end of the block, check whether EFLAGS is live into a
18386   // successor.
18387   if (miI == BB->end()) {
18388     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18389                                           sEnd = BB->succ_end();
18390          sItr != sEnd; ++sItr) {
18391       MachineBasicBlock* succ = *sItr;
18392       if (succ->isLiveIn(X86::EFLAGS))
18393         return false;
18394     }
18395   }
18396
18397   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18398   // out. SelectMI should have a kill flag on EFLAGS.
18399   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18400   return true;
18401 }
18402
18403 MachineBasicBlock *
18404 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18405                                      MachineBasicBlock *BB) const {
18406   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18407   DebugLoc DL = MI->getDebugLoc();
18408
18409   // To "insert" a SELECT_CC instruction, we actually have to insert the
18410   // diamond control-flow pattern.  The incoming instruction knows the
18411   // destination vreg to set, the condition code register to branch on, the
18412   // true/false values to select between, and a branch opcode to use.
18413   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18414   MachineFunction::iterator It = BB;
18415   ++It;
18416
18417   //  thisMBB:
18418   //  ...
18419   //   TrueVal = ...
18420   //   cmpTY ccX, r1, r2
18421   //   bCC copy1MBB
18422   //   fallthrough --> copy0MBB
18423   MachineBasicBlock *thisMBB = BB;
18424   MachineFunction *F = BB->getParent();
18425   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18426   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18427   F->insert(It, copy0MBB);
18428   F->insert(It, sinkMBB);
18429
18430   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18431   // live into the sink and copy blocks.
18432   const TargetRegisterInfo *TRI =
18433       BB->getParent()->getSubtarget().getRegisterInfo();
18434   if (!MI->killsRegister(X86::EFLAGS) &&
18435       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18436     copy0MBB->addLiveIn(X86::EFLAGS);
18437     sinkMBB->addLiveIn(X86::EFLAGS);
18438   }
18439
18440   // Transfer the remainder of BB and its successor edges to sinkMBB.
18441   sinkMBB->splice(sinkMBB->begin(), BB,
18442                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18443   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18444
18445   // Add the true and fallthrough blocks as its successors.
18446   BB->addSuccessor(copy0MBB);
18447   BB->addSuccessor(sinkMBB);
18448
18449   // Create the conditional branch instruction.
18450   unsigned Opc =
18451     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18452   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18453
18454   //  copy0MBB:
18455   //   %FalseValue = ...
18456   //   # fallthrough to sinkMBB
18457   copy0MBB->addSuccessor(sinkMBB);
18458
18459   //  sinkMBB:
18460   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18461   //  ...
18462   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18463           TII->get(X86::PHI), MI->getOperand(0).getReg())
18464     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18465     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18466
18467   MI->eraseFromParent();   // The pseudo instruction is gone now.
18468   return sinkMBB;
18469 }
18470
18471 MachineBasicBlock *
18472 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18473                                         bool Is64Bit) const {
18474   MachineFunction *MF = BB->getParent();
18475   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18476   DebugLoc DL = MI->getDebugLoc();
18477   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18478
18479   assert(MF->shouldSplitStack());
18480
18481   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18482   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18483
18484   // BB:
18485   //  ... [Till the alloca]
18486   // If stacklet is not large enough, jump to mallocMBB
18487   //
18488   // bumpMBB:
18489   //  Allocate by subtracting from RSP
18490   //  Jump to continueMBB
18491   //
18492   // mallocMBB:
18493   //  Allocate by call to runtime
18494   //
18495   // continueMBB:
18496   //  ...
18497   //  [rest of original BB]
18498   //
18499
18500   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18501   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18502   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18503
18504   MachineRegisterInfo &MRI = MF->getRegInfo();
18505   const TargetRegisterClass *AddrRegClass =
18506     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18507
18508   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18509     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18510     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18511     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18512     sizeVReg = MI->getOperand(1).getReg(),
18513     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18514
18515   MachineFunction::iterator MBBIter = BB;
18516   ++MBBIter;
18517
18518   MF->insert(MBBIter, bumpMBB);
18519   MF->insert(MBBIter, mallocMBB);
18520   MF->insert(MBBIter, continueMBB);
18521
18522   continueMBB->splice(continueMBB->begin(), BB,
18523                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18524   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18525
18526   // Add code to the main basic block to check if the stack limit has been hit,
18527   // and if so, jump to mallocMBB otherwise to bumpMBB.
18528   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18529   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18530     .addReg(tmpSPVReg).addReg(sizeVReg);
18531   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18532     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18533     .addReg(SPLimitVReg);
18534   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18535
18536   // bumpMBB simply decreases the stack pointer, since we know the current
18537   // stacklet has enough space.
18538   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18539     .addReg(SPLimitVReg);
18540   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18541     .addReg(SPLimitVReg);
18542   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18543
18544   // Calls into a routine in libgcc to allocate more space from the heap.
18545   const uint32_t *RegMask = MF->getTarget()
18546                                 .getSubtargetImpl()
18547                                 ->getRegisterInfo()
18548                                 ->getCallPreservedMask(CallingConv::C);
18549   if (Is64Bit) {
18550     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18551       .addReg(sizeVReg);
18552     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18553       .addExternalSymbol("__morestack_allocate_stack_space")
18554       .addRegMask(RegMask)
18555       .addReg(X86::RDI, RegState::Implicit)
18556       .addReg(X86::RAX, RegState::ImplicitDefine);
18557   } else {
18558     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18559       .addImm(12);
18560     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18561     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18562       .addExternalSymbol("__morestack_allocate_stack_space")
18563       .addRegMask(RegMask)
18564       .addReg(X86::EAX, RegState::ImplicitDefine);
18565   }
18566
18567   if (!Is64Bit)
18568     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18569       .addImm(16);
18570
18571   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18572     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18573   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18574
18575   // Set up the CFG correctly.
18576   BB->addSuccessor(bumpMBB);
18577   BB->addSuccessor(mallocMBB);
18578   mallocMBB->addSuccessor(continueMBB);
18579   bumpMBB->addSuccessor(continueMBB);
18580
18581   // Take care of the PHI nodes.
18582   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18583           MI->getOperand(0).getReg())
18584     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18585     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18586
18587   // Delete the original pseudo instruction.
18588   MI->eraseFromParent();
18589
18590   // And we're done.
18591   return continueMBB;
18592 }
18593
18594 MachineBasicBlock *
18595 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18596                                         MachineBasicBlock *BB) const {
18597   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18598   DebugLoc DL = MI->getDebugLoc();
18599
18600   assert(!Subtarget->isTargetMacho());
18601
18602   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18603   // non-trivial part is impdef of ESP.
18604
18605   if (Subtarget->isTargetWin64()) {
18606     if (Subtarget->isTargetCygMing()) {
18607       // ___chkstk(Mingw64):
18608       // Clobbers R10, R11, RAX and EFLAGS.
18609       // Updates RSP.
18610       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18611         .addExternalSymbol("___chkstk")
18612         .addReg(X86::RAX, RegState::Implicit)
18613         .addReg(X86::RSP, RegState::Implicit)
18614         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18615         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18616         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18617     } else {
18618       // __chkstk(MSVCRT): does not update stack pointer.
18619       // Clobbers R10, R11 and EFLAGS.
18620       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18621         .addExternalSymbol("__chkstk")
18622         .addReg(X86::RAX, RegState::Implicit)
18623         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18624       // RAX has the offset to be subtracted from RSP.
18625       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18626         .addReg(X86::RSP)
18627         .addReg(X86::RAX);
18628     }
18629   } else {
18630     const char *StackProbeSymbol =
18631       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18632
18633     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18634       .addExternalSymbol(StackProbeSymbol)
18635       .addReg(X86::EAX, RegState::Implicit)
18636       .addReg(X86::ESP, RegState::Implicit)
18637       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18638       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18639       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18640   }
18641
18642   MI->eraseFromParent();   // The pseudo instruction is gone now.
18643   return BB;
18644 }
18645
18646 MachineBasicBlock *
18647 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18648                                       MachineBasicBlock *BB) const {
18649   // This is pretty easy.  We're taking the value that we received from
18650   // our load from the relocation, sticking it in either RDI (x86-64)
18651   // or EAX and doing an indirect call.  The return value will then
18652   // be in the normal return register.
18653   MachineFunction *F = BB->getParent();
18654   const X86InstrInfo *TII =
18655       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18656   DebugLoc DL = MI->getDebugLoc();
18657
18658   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18659   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18660
18661   // Get a register mask for the lowered call.
18662   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18663   // proper register mask.
18664   const uint32_t *RegMask = F->getTarget()
18665                                 .getSubtargetImpl()
18666                                 ->getRegisterInfo()
18667                                 ->getCallPreservedMask(CallingConv::C);
18668   if (Subtarget->is64Bit()) {
18669     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18670                                       TII->get(X86::MOV64rm), X86::RDI)
18671     .addReg(X86::RIP)
18672     .addImm(0).addReg(0)
18673     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18674                       MI->getOperand(3).getTargetFlags())
18675     .addReg(0);
18676     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18677     addDirectMem(MIB, X86::RDI);
18678     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18679   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18680     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18681                                       TII->get(X86::MOV32rm), X86::EAX)
18682     .addReg(0)
18683     .addImm(0).addReg(0)
18684     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18685                       MI->getOperand(3).getTargetFlags())
18686     .addReg(0);
18687     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18688     addDirectMem(MIB, X86::EAX);
18689     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18690   } else {
18691     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18692                                       TII->get(X86::MOV32rm), X86::EAX)
18693     .addReg(TII->getGlobalBaseReg(F))
18694     .addImm(0).addReg(0)
18695     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18696                       MI->getOperand(3).getTargetFlags())
18697     .addReg(0);
18698     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18699     addDirectMem(MIB, X86::EAX);
18700     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18701   }
18702
18703   MI->eraseFromParent(); // The pseudo instruction is gone now.
18704   return BB;
18705 }
18706
18707 MachineBasicBlock *
18708 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18709                                     MachineBasicBlock *MBB) const {
18710   DebugLoc DL = MI->getDebugLoc();
18711   MachineFunction *MF = MBB->getParent();
18712   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18713   MachineRegisterInfo &MRI = MF->getRegInfo();
18714
18715   const BasicBlock *BB = MBB->getBasicBlock();
18716   MachineFunction::iterator I = MBB;
18717   ++I;
18718
18719   // Memory Reference
18720   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18721   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18722
18723   unsigned DstReg;
18724   unsigned MemOpndSlot = 0;
18725
18726   unsigned CurOp = 0;
18727
18728   DstReg = MI->getOperand(CurOp++).getReg();
18729   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18730   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18731   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18732   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18733
18734   MemOpndSlot = CurOp;
18735
18736   MVT PVT = getPointerTy();
18737   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18738          "Invalid Pointer Size!");
18739
18740   // For v = setjmp(buf), we generate
18741   //
18742   // thisMBB:
18743   //  buf[LabelOffset] = restoreMBB
18744   //  SjLjSetup restoreMBB
18745   //
18746   // mainMBB:
18747   //  v_main = 0
18748   //
18749   // sinkMBB:
18750   //  v = phi(main, restore)
18751   //
18752   // restoreMBB:
18753   //  v_restore = 1
18754
18755   MachineBasicBlock *thisMBB = MBB;
18756   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18757   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18758   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18759   MF->insert(I, mainMBB);
18760   MF->insert(I, sinkMBB);
18761   MF->push_back(restoreMBB);
18762
18763   MachineInstrBuilder MIB;
18764
18765   // Transfer the remainder of BB and its successor edges to sinkMBB.
18766   sinkMBB->splice(sinkMBB->begin(), MBB,
18767                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18768   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18769
18770   // thisMBB:
18771   unsigned PtrStoreOpc = 0;
18772   unsigned LabelReg = 0;
18773   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18774   Reloc::Model RM = MF->getTarget().getRelocationModel();
18775   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18776                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18777
18778   // Prepare IP either in reg or imm.
18779   if (!UseImmLabel) {
18780     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18781     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18782     LabelReg = MRI.createVirtualRegister(PtrRC);
18783     if (Subtarget->is64Bit()) {
18784       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18785               .addReg(X86::RIP)
18786               .addImm(0)
18787               .addReg(0)
18788               .addMBB(restoreMBB)
18789               .addReg(0);
18790     } else {
18791       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18792       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18793               .addReg(XII->getGlobalBaseReg(MF))
18794               .addImm(0)
18795               .addReg(0)
18796               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18797               .addReg(0);
18798     }
18799   } else
18800     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18801   // Store IP
18802   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18803   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18804     if (i == X86::AddrDisp)
18805       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18806     else
18807       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18808   }
18809   if (!UseImmLabel)
18810     MIB.addReg(LabelReg);
18811   else
18812     MIB.addMBB(restoreMBB);
18813   MIB.setMemRefs(MMOBegin, MMOEnd);
18814   // Setup
18815   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18816           .addMBB(restoreMBB);
18817
18818   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18819       MF->getSubtarget().getRegisterInfo());
18820   MIB.addRegMask(RegInfo->getNoPreservedMask());
18821   thisMBB->addSuccessor(mainMBB);
18822   thisMBB->addSuccessor(restoreMBB);
18823
18824   // mainMBB:
18825   //  EAX = 0
18826   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18827   mainMBB->addSuccessor(sinkMBB);
18828
18829   // sinkMBB:
18830   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18831           TII->get(X86::PHI), DstReg)
18832     .addReg(mainDstReg).addMBB(mainMBB)
18833     .addReg(restoreDstReg).addMBB(restoreMBB);
18834
18835   // restoreMBB:
18836   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18837   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18838   restoreMBB->addSuccessor(sinkMBB);
18839
18840   MI->eraseFromParent();
18841   return sinkMBB;
18842 }
18843
18844 MachineBasicBlock *
18845 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18846                                      MachineBasicBlock *MBB) const {
18847   DebugLoc DL = MI->getDebugLoc();
18848   MachineFunction *MF = MBB->getParent();
18849   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18850   MachineRegisterInfo &MRI = MF->getRegInfo();
18851
18852   // Memory Reference
18853   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18854   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18855
18856   MVT PVT = getPointerTy();
18857   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18858          "Invalid Pointer Size!");
18859
18860   const TargetRegisterClass *RC =
18861     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18862   unsigned Tmp = MRI.createVirtualRegister(RC);
18863   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18864   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18865       MF->getSubtarget().getRegisterInfo());
18866   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18867   unsigned SP = RegInfo->getStackRegister();
18868
18869   MachineInstrBuilder MIB;
18870
18871   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18872   const int64_t SPOffset = 2 * PVT.getStoreSize();
18873
18874   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18875   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18876
18877   // Reload FP
18878   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18879   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18880     MIB.addOperand(MI->getOperand(i));
18881   MIB.setMemRefs(MMOBegin, MMOEnd);
18882   // Reload IP
18883   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18884   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18885     if (i == X86::AddrDisp)
18886       MIB.addDisp(MI->getOperand(i), LabelOffset);
18887     else
18888       MIB.addOperand(MI->getOperand(i));
18889   }
18890   MIB.setMemRefs(MMOBegin, MMOEnd);
18891   // Reload SP
18892   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18893   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18894     if (i == X86::AddrDisp)
18895       MIB.addDisp(MI->getOperand(i), SPOffset);
18896     else
18897       MIB.addOperand(MI->getOperand(i));
18898   }
18899   MIB.setMemRefs(MMOBegin, MMOEnd);
18900   // Jump
18901   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18902
18903   MI->eraseFromParent();
18904   return MBB;
18905 }
18906
18907 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18908 // accumulator loops. Writing back to the accumulator allows the coalescer
18909 // to remove extra copies in the loop.   
18910 MachineBasicBlock *
18911 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18912                                  MachineBasicBlock *MBB) const {
18913   MachineOperand &AddendOp = MI->getOperand(3);
18914
18915   // Bail out early if the addend isn't a register - we can't switch these.
18916   if (!AddendOp.isReg())
18917     return MBB;
18918
18919   MachineFunction &MF = *MBB->getParent();
18920   MachineRegisterInfo &MRI = MF.getRegInfo();
18921
18922   // Check whether the addend is defined by a PHI:
18923   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18924   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18925   if (!AddendDef.isPHI())
18926     return MBB;
18927
18928   // Look for the following pattern:
18929   // loop:
18930   //   %addend = phi [%entry, 0], [%loop, %result]
18931   //   ...
18932   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18933
18934   // Replace with:
18935   //   loop:
18936   //   %addend = phi [%entry, 0], [%loop, %result]
18937   //   ...
18938   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18939
18940   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18941     assert(AddendDef.getOperand(i).isReg());
18942     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18943     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18944     if (&PHISrcInst == MI) {
18945       // Found a matching instruction.
18946       unsigned NewFMAOpc = 0;
18947       switch (MI->getOpcode()) {
18948         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18949         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18950         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18951         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18952         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18953         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18954         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18955         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18956         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18957         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18958         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18959         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18960         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18961         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18962         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18963         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18964         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18965         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18966         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18967         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18968         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18969         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18970         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18971         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18972         default: llvm_unreachable("Unrecognized FMA variant.");
18973       }
18974
18975       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18976       MachineInstrBuilder MIB =
18977         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18978         .addOperand(MI->getOperand(0))
18979         .addOperand(MI->getOperand(3))
18980         .addOperand(MI->getOperand(2))
18981         .addOperand(MI->getOperand(1));
18982       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18983       MI->eraseFromParent();
18984     }
18985   }
18986
18987   return MBB;
18988 }
18989
18990 MachineBasicBlock *
18991 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18992                                                MachineBasicBlock *BB) const {
18993   switch (MI->getOpcode()) {
18994   default: llvm_unreachable("Unexpected instr type to insert");
18995   case X86::TAILJMPd64:
18996   case X86::TAILJMPr64:
18997   case X86::TAILJMPm64:
18998     llvm_unreachable("TAILJMP64 would not be touched here.");
18999   case X86::TCRETURNdi64:
19000   case X86::TCRETURNri64:
19001   case X86::TCRETURNmi64:
19002     return BB;
19003   case X86::WIN_ALLOCA:
19004     return EmitLoweredWinAlloca(MI, BB);
19005   case X86::SEG_ALLOCA_32:
19006     return EmitLoweredSegAlloca(MI, BB, false);
19007   case X86::SEG_ALLOCA_64:
19008     return EmitLoweredSegAlloca(MI, BB, true);
19009   case X86::TLSCall_32:
19010   case X86::TLSCall_64:
19011     return EmitLoweredTLSCall(MI, BB);
19012   case X86::CMOV_GR8:
19013   case X86::CMOV_FR32:
19014   case X86::CMOV_FR64:
19015   case X86::CMOV_V4F32:
19016   case X86::CMOV_V2F64:
19017   case X86::CMOV_V2I64:
19018   case X86::CMOV_V8F32:
19019   case X86::CMOV_V4F64:
19020   case X86::CMOV_V4I64:
19021   case X86::CMOV_V16F32:
19022   case X86::CMOV_V8F64:
19023   case X86::CMOV_V8I64:
19024   case X86::CMOV_GR16:
19025   case X86::CMOV_GR32:
19026   case X86::CMOV_RFP32:
19027   case X86::CMOV_RFP64:
19028   case X86::CMOV_RFP80:
19029     return EmitLoweredSelect(MI, BB);
19030
19031   case X86::FP32_TO_INT16_IN_MEM:
19032   case X86::FP32_TO_INT32_IN_MEM:
19033   case X86::FP32_TO_INT64_IN_MEM:
19034   case X86::FP64_TO_INT16_IN_MEM:
19035   case X86::FP64_TO_INT32_IN_MEM:
19036   case X86::FP64_TO_INT64_IN_MEM:
19037   case X86::FP80_TO_INT16_IN_MEM:
19038   case X86::FP80_TO_INT32_IN_MEM:
19039   case X86::FP80_TO_INT64_IN_MEM: {
19040     MachineFunction *F = BB->getParent();
19041     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
19042     DebugLoc DL = MI->getDebugLoc();
19043
19044     // Change the floating point control register to use "round towards zero"
19045     // mode when truncating to an integer value.
19046     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19047     addFrameReference(BuildMI(*BB, MI, DL,
19048                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19049
19050     // Load the old value of the high byte of the control word...
19051     unsigned OldCW =
19052       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19053     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19054                       CWFrameIdx);
19055
19056     // Set the high part to be round to zero...
19057     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19058       .addImm(0xC7F);
19059
19060     // Reload the modified control word now...
19061     addFrameReference(BuildMI(*BB, MI, DL,
19062                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19063
19064     // Restore the memory image of control word to original value
19065     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19066       .addReg(OldCW);
19067
19068     // Get the X86 opcode to use.
19069     unsigned Opc;
19070     switch (MI->getOpcode()) {
19071     default: llvm_unreachable("illegal opcode!");
19072     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19073     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19074     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19075     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19076     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19077     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19078     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19079     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19080     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19081     }
19082
19083     X86AddressMode AM;
19084     MachineOperand &Op = MI->getOperand(0);
19085     if (Op.isReg()) {
19086       AM.BaseType = X86AddressMode::RegBase;
19087       AM.Base.Reg = Op.getReg();
19088     } else {
19089       AM.BaseType = X86AddressMode::FrameIndexBase;
19090       AM.Base.FrameIndex = Op.getIndex();
19091     }
19092     Op = MI->getOperand(1);
19093     if (Op.isImm())
19094       AM.Scale = Op.getImm();
19095     Op = MI->getOperand(2);
19096     if (Op.isImm())
19097       AM.IndexReg = Op.getImm();
19098     Op = MI->getOperand(3);
19099     if (Op.isGlobal()) {
19100       AM.GV = Op.getGlobal();
19101     } else {
19102       AM.Disp = Op.getImm();
19103     }
19104     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19105                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19106
19107     // Reload the original control word now.
19108     addFrameReference(BuildMI(*BB, MI, DL,
19109                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19110
19111     MI->eraseFromParent();   // The pseudo instruction is gone now.
19112     return BB;
19113   }
19114     // String/text processing lowering.
19115   case X86::PCMPISTRM128REG:
19116   case X86::VPCMPISTRM128REG:
19117   case X86::PCMPISTRM128MEM:
19118   case X86::VPCMPISTRM128MEM:
19119   case X86::PCMPESTRM128REG:
19120   case X86::VPCMPESTRM128REG:
19121   case X86::PCMPESTRM128MEM:
19122   case X86::VPCMPESTRM128MEM:
19123     assert(Subtarget->hasSSE42() &&
19124            "Target must have SSE4.2 or AVX features enabled");
19125     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19126
19127   // String/text processing lowering.
19128   case X86::PCMPISTRIREG:
19129   case X86::VPCMPISTRIREG:
19130   case X86::PCMPISTRIMEM:
19131   case X86::VPCMPISTRIMEM:
19132   case X86::PCMPESTRIREG:
19133   case X86::VPCMPESTRIREG:
19134   case X86::PCMPESTRIMEM:
19135   case X86::VPCMPESTRIMEM:
19136     assert(Subtarget->hasSSE42() &&
19137            "Target must have SSE4.2 or AVX features enabled");
19138     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19139
19140   // Thread synchronization.
19141   case X86::MONITOR:
19142     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
19143                        Subtarget);
19144
19145   // xbegin
19146   case X86::XBEGIN:
19147     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19148
19149   case X86::VASTART_SAVE_XMM_REGS:
19150     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19151
19152   case X86::VAARG_64:
19153     return EmitVAARG64WithCustomInserter(MI, BB);
19154
19155   case X86::EH_SjLj_SetJmp32:
19156   case X86::EH_SjLj_SetJmp64:
19157     return emitEHSjLjSetJmp(MI, BB);
19158
19159   case X86::EH_SjLj_LongJmp32:
19160   case X86::EH_SjLj_LongJmp64:
19161     return emitEHSjLjLongJmp(MI, BB);
19162
19163   case TargetOpcode::STACKMAP:
19164   case TargetOpcode::PATCHPOINT:
19165     return emitPatchPoint(MI, BB);
19166
19167   case X86::VFMADDPDr213r:
19168   case X86::VFMADDPSr213r:
19169   case X86::VFMADDSDr213r:
19170   case X86::VFMADDSSr213r:
19171   case X86::VFMSUBPDr213r:
19172   case X86::VFMSUBPSr213r:
19173   case X86::VFMSUBSDr213r:
19174   case X86::VFMSUBSSr213r:
19175   case X86::VFNMADDPDr213r:
19176   case X86::VFNMADDPSr213r:
19177   case X86::VFNMADDSDr213r:
19178   case X86::VFNMADDSSr213r:
19179   case X86::VFNMSUBPDr213r:
19180   case X86::VFNMSUBPSr213r:
19181   case X86::VFNMSUBSDr213r:
19182   case X86::VFNMSUBSSr213r:
19183   case X86::VFMADDPDr213rY:
19184   case X86::VFMADDPSr213rY:
19185   case X86::VFMSUBPDr213rY:
19186   case X86::VFMSUBPSr213rY:
19187   case X86::VFNMADDPDr213rY:
19188   case X86::VFNMADDPSr213rY:
19189   case X86::VFNMSUBPDr213rY:
19190   case X86::VFNMSUBPSr213rY:
19191     return emitFMA3Instr(MI, BB);
19192   }
19193 }
19194
19195 //===----------------------------------------------------------------------===//
19196 //                           X86 Optimization Hooks
19197 //===----------------------------------------------------------------------===//
19198
19199 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19200                                                       APInt &KnownZero,
19201                                                       APInt &KnownOne,
19202                                                       const SelectionDAG &DAG,
19203                                                       unsigned Depth) const {
19204   unsigned BitWidth = KnownZero.getBitWidth();
19205   unsigned Opc = Op.getOpcode();
19206   assert((Opc >= ISD::BUILTIN_OP_END ||
19207           Opc == ISD::INTRINSIC_WO_CHAIN ||
19208           Opc == ISD::INTRINSIC_W_CHAIN ||
19209           Opc == ISD::INTRINSIC_VOID) &&
19210          "Should use MaskedValueIsZero if you don't know whether Op"
19211          " is a target node!");
19212
19213   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19214   switch (Opc) {
19215   default: break;
19216   case X86ISD::ADD:
19217   case X86ISD::SUB:
19218   case X86ISD::ADC:
19219   case X86ISD::SBB:
19220   case X86ISD::SMUL:
19221   case X86ISD::UMUL:
19222   case X86ISD::INC:
19223   case X86ISD::DEC:
19224   case X86ISD::OR:
19225   case X86ISD::XOR:
19226   case X86ISD::AND:
19227     // These nodes' second result is a boolean.
19228     if (Op.getResNo() == 0)
19229       break;
19230     // Fallthrough
19231   case X86ISD::SETCC:
19232     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19233     break;
19234   case ISD::INTRINSIC_WO_CHAIN: {
19235     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19236     unsigned NumLoBits = 0;
19237     switch (IntId) {
19238     default: break;
19239     case Intrinsic::x86_sse_movmsk_ps:
19240     case Intrinsic::x86_avx_movmsk_ps_256:
19241     case Intrinsic::x86_sse2_movmsk_pd:
19242     case Intrinsic::x86_avx_movmsk_pd_256:
19243     case Intrinsic::x86_mmx_pmovmskb:
19244     case Intrinsic::x86_sse2_pmovmskb_128:
19245     case Intrinsic::x86_avx2_pmovmskb: {
19246       // High bits of movmskp{s|d}, pmovmskb are known zero.
19247       switch (IntId) {
19248         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19249         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19250         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19251         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19252         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19253         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19254         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19255         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19256       }
19257       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19258       break;
19259     }
19260     }
19261     break;
19262   }
19263   }
19264 }
19265
19266 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19267   SDValue Op,
19268   const SelectionDAG &,
19269   unsigned Depth) const {
19270   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19271   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19272     return Op.getValueType().getScalarType().getSizeInBits();
19273
19274   // Fallback case.
19275   return 1;
19276 }
19277
19278 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19279 /// node is a GlobalAddress + offset.
19280 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19281                                        const GlobalValue* &GA,
19282                                        int64_t &Offset) const {
19283   if (N->getOpcode() == X86ISD::Wrapper) {
19284     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19285       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19286       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19287       return true;
19288     }
19289   }
19290   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19291 }
19292
19293 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19294 /// same as extracting the high 128-bit part of 256-bit vector and then
19295 /// inserting the result into the low part of a new 256-bit vector
19296 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19297   EVT VT = SVOp->getValueType(0);
19298   unsigned NumElems = VT.getVectorNumElements();
19299
19300   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19301   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19302     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19303         SVOp->getMaskElt(j) >= 0)
19304       return false;
19305
19306   return true;
19307 }
19308
19309 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19310 /// same as extracting the low 128-bit part of 256-bit vector and then
19311 /// inserting the result into the high part of a new 256-bit vector
19312 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19313   EVT VT = SVOp->getValueType(0);
19314   unsigned NumElems = VT.getVectorNumElements();
19315
19316   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19317   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19318     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19319         SVOp->getMaskElt(j) >= 0)
19320       return false;
19321
19322   return true;
19323 }
19324
19325 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19326 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19327                                         TargetLowering::DAGCombinerInfo &DCI,
19328                                         const X86Subtarget* Subtarget) {
19329   SDLoc dl(N);
19330   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19331   SDValue V1 = SVOp->getOperand(0);
19332   SDValue V2 = SVOp->getOperand(1);
19333   EVT VT = SVOp->getValueType(0);
19334   unsigned NumElems = VT.getVectorNumElements();
19335
19336   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19337       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19338     //
19339     //                   0,0,0,...
19340     //                      |
19341     //    V      UNDEF    BUILD_VECTOR    UNDEF
19342     //     \      /           \           /
19343     //  CONCAT_VECTOR         CONCAT_VECTOR
19344     //         \                  /
19345     //          \                /
19346     //          RESULT: V + zero extended
19347     //
19348     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19349         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19350         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19351       return SDValue();
19352
19353     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19354       return SDValue();
19355
19356     // To match the shuffle mask, the first half of the mask should
19357     // be exactly the first vector, and all the rest a splat with the
19358     // first element of the second one.
19359     for (unsigned i = 0; i != NumElems/2; ++i)
19360       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19361           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19362         return SDValue();
19363
19364     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19365     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19366       if (Ld->hasNUsesOfValue(1, 0)) {
19367         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19368         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19369         SDValue ResNode =
19370           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19371                                   Ld->getMemoryVT(),
19372                                   Ld->getPointerInfo(),
19373                                   Ld->getAlignment(),
19374                                   false/*isVolatile*/, true/*ReadMem*/,
19375                                   false/*WriteMem*/);
19376
19377         // Make sure the newly-created LOAD is in the same position as Ld in
19378         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19379         // and update uses of Ld's output chain to use the TokenFactor.
19380         if (Ld->hasAnyUseOfValue(1)) {
19381           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19382                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19383           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19384           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19385                                  SDValue(ResNode.getNode(), 1));
19386         }
19387
19388         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19389       }
19390     }
19391
19392     // Emit a zeroed vector and insert the desired subvector on its
19393     // first half.
19394     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19395     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19396     return DCI.CombineTo(N, InsV);
19397   }
19398
19399   //===--------------------------------------------------------------------===//
19400   // Combine some shuffles into subvector extracts and inserts:
19401   //
19402
19403   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19404   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19405     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19406     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19407     return DCI.CombineTo(N, InsV);
19408   }
19409
19410   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19411   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19412     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19413     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19414     return DCI.CombineTo(N, InsV);
19415   }
19416
19417   return SDValue();
19418 }
19419
19420 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19421 /// possible.
19422 ///
19423 /// This is the leaf of the recursive combinine below. When we have found some
19424 /// chain of single-use x86 shuffle instructions and accumulated the combined
19425 /// shuffle mask represented by them, this will try to pattern match that mask
19426 /// into either a single instruction if there is a special purpose instruction
19427 /// for this operation, or into a PSHUFB instruction which is a fully general
19428 /// instruction but should only be used to replace chains over a certain depth.
19429 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19430                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19431                                    TargetLowering::DAGCombinerInfo &DCI,
19432                                    const X86Subtarget *Subtarget) {
19433   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19434
19435   // Find the operand that enters the chain. Note that multiple uses are OK
19436   // here, we're not going to remove the operand we find.
19437   SDValue Input = Op.getOperand(0);
19438   while (Input.getOpcode() == ISD::BITCAST)
19439     Input = Input.getOperand(0);
19440
19441   MVT VT = Input.getSimpleValueType();
19442   MVT RootVT = Root.getSimpleValueType();
19443   SDLoc DL(Root);
19444
19445   // Just remove no-op shuffle masks.
19446   if (Mask.size() == 1) {
19447     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19448                   /*AddTo*/ true);
19449     return true;
19450   }
19451
19452   // Use the float domain if the operand type is a floating point type.
19453   bool FloatDomain = VT.isFloatingPoint();
19454
19455   // If we don't have access to VEX encodings, the generic PSHUF instructions
19456   // are preferable to some of the specialized forms despite requiring one more
19457   // byte to encode because they can implicitly copy.
19458   //
19459   // IF we *do* have VEX encodings, than we can use shorter, more specific
19460   // shuffle instructions freely as they can copy due to the extra register
19461   // operand.
19462   if (Subtarget->hasAVX()) {
19463     // We have both floating point and integer variants of shuffles that dup
19464     // either the low or high half of the vector.
19465     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19466       bool Lo = Mask.equals(0, 0);
19467       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19468                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19469       if (Depth == 1 && Root->getOpcode() == Shuffle)
19470         return false; // Nothing to do!
19471       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19472       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19473       DCI.AddToWorklist(Op.getNode());
19474       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19475       DCI.AddToWorklist(Op.getNode());
19476       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19477                     /*AddTo*/ true);
19478       return true;
19479     }
19480
19481     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19482
19483     // For the integer domain we have specialized instructions for duplicating
19484     // any element size from the low or high half.
19485     if (!FloatDomain &&
19486         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19487          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19488          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19489          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19490          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19491                      15))) {
19492       bool Lo = Mask[0] == 0;
19493       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19494       if (Depth == 1 && Root->getOpcode() == Shuffle)
19495         return false; // Nothing to do!
19496       MVT ShuffleVT;
19497       switch (Mask.size()) {
19498       case 4: ShuffleVT = MVT::v4i32; break;
19499       case 8: ShuffleVT = MVT::v8i16; break;
19500       case 16: ShuffleVT = MVT::v16i8; break;
19501       };
19502       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19503       DCI.AddToWorklist(Op.getNode());
19504       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19505       DCI.AddToWorklist(Op.getNode());
19506       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19507                     /*AddTo*/ true);
19508       return true;
19509     }
19510   }
19511
19512   // Don't try to re-form single instruction chains under any circumstances now
19513   // that we've done encoding canonicalization for them.
19514   if (Depth < 2)
19515     return false;
19516
19517   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19518   // can replace them with a single PSHUFB instruction profitably. Intel's
19519   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19520   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19521   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19522     SmallVector<SDValue, 16> PSHUFBMask;
19523     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19524     int Ratio = 16 / Mask.size();
19525     for (unsigned i = 0; i < 16; ++i) {
19526       int M = Mask[i / Ratio] != SM_SentinelZero
19527                   ? Ratio * Mask[i / Ratio] + i % Ratio
19528                   : 255;
19529       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19530     }
19531     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19532     DCI.AddToWorklist(Op.getNode());
19533     SDValue PSHUFBMaskOp =
19534         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19535     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19536     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19537     DCI.AddToWorklist(Op.getNode());
19538     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19539                   /*AddTo*/ true);
19540     return true;
19541   }
19542
19543   // Failed to find any combines.
19544   return false;
19545 }
19546
19547 /// \brief Fully generic combining of x86 shuffle instructions.
19548 ///
19549 /// This should be the last combine run over the x86 shuffle instructions. Once
19550 /// they have been fully optimized, this will recursively consider all chains
19551 /// of single-use shuffle instructions, build a generic model of the cumulative
19552 /// shuffle operation, and check for simpler instructions which implement this
19553 /// operation. We use this primarily for two purposes:
19554 ///
19555 /// 1) Collapse generic shuffles to specialized single instructions when
19556 ///    equivalent. In most cases, this is just an encoding size win, but
19557 ///    sometimes we will collapse multiple generic shuffles into a single
19558 ///    special-purpose shuffle.
19559 /// 2) Look for sequences of shuffle instructions with 3 or more total
19560 ///    instructions, and replace them with the slightly more expensive SSSE3
19561 ///    PSHUFB instruction if available. We do this as the last combining step
19562 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19563 ///    a suitable short sequence of other instructions. The PHUFB will either
19564 ///    use a register or have to read from memory and so is slightly (but only
19565 ///    slightly) more expensive than the other shuffle instructions.
19566 ///
19567 /// Because this is inherently a quadratic operation (for each shuffle in
19568 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19569 /// This should never be an issue in practice as the shuffle lowering doesn't
19570 /// produce sequences of more than 8 instructions.
19571 ///
19572 /// FIXME: We will currently miss some cases where the redundant shuffling
19573 /// would simplify under the threshold for PSHUFB formation because of
19574 /// combine-ordering. To fix this, we should do the redundant instruction
19575 /// combining in this recursive walk.
19576 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19577                                           ArrayRef<int> RootMask,
19578                                           int Depth, bool HasPSHUFB,
19579                                           SelectionDAG &DAG,
19580                                           TargetLowering::DAGCombinerInfo &DCI,
19581                                           const X86Subtarget *Subtarget) {
19582   // Bound the depth of our recursive combine because this is ultimately
19583   // quadratic in nature.
19584   if (Depth > 8)
19585     return false;
19586
19587   // Directly rip through bitcasts to find the underlying operand.
19588   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19589     Op = Op.getOperand(0);
19590
19591   MVT VT = Op.getSimpleValueType();
19592   if (!VT.isVector())
19593     return false; // Bail if we hit a non-vector.
19594   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19595   // version should be added.
19596   if (VT.getSizeInBits() != 128)
19597     return false;
19598
19599   assert(Root.getSimpleValueType().isVector() &&
19600          "Shuffles operate on vector types!");
19601   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19602          "Can only combine shuffles of the same vector register size.");
19603
19604   if (!isTargetShuffle(Op.getOpcode()))
19605     return false;
19606   SmallVector<int, 16> OpMask;
19607   bool IsUnary;
19608   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19609   // We only can combine unary shuffles which we can decode the mask for.
19610   if (!HaveMask || !IsUnary)
19611     return false;
19612
19613   assert(VT.getVectorNumElements() == OpMask.size() &&
19614          "Different mask size from vector size!");
19615   assert(((RootMask.size() > OpMask.size() &&
19616            RootMask.size() % OpMask.size() == 0) ||
19617           (OpMask.size() > RootMask.size() &&
19618            OpMask.size() % RootMask.size() == 0) ||
19619           OpMask.size() == RootMask.size()) &&
19620          "The smaller number of elements must divide the larger.");
19621   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19622   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19623   assert(((RootRatio == 1 && OpRatio == 1) ||
19624           (RootRatio == 1) != (OpRatio == 1)) &&
19625          "Must not have a ratio for both incoming and op masks!");
19626
19627   SmallVector<int, 16> Mask;
19628   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19629
19630   // Merge this shuffle operation's mask into our accumulated mask. Note that
19631   // this shuffle's mask will be the first applied to the input, followed by the
19632   // root mask to get us all the way to the root value arrangement. The reason
19633   // for this order is that we are recursing up the operation chain.
19634   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19635     int RootIdx = i / RootRatio;
19636     if (RootMask[RootIdx] == SM_SentinelZero) {
19637       // This is a zero-ed lane, we're done.
19638       Mask.push_back(SM_SentinelZero);
19639       continue;
19640     }
19641
19642     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19643     int OpIdx = RootMaskedIdx / OpRatio;
19644     if (OpMask[OpIdx] == SM_SentinelZero) {
19645       // The incoming lanes are zero, it doesn't matter which ones we are using.
19646       Mask.push_back(SM_SentinelZero);
19647       continue;
19648     }
19649
19650     // Ok, we have non-zero lanes, map them through.
19651     Mask.push_back(OpMask[OpIdx] * OpRatio +
19652                    RootMaskedIdx % OpRatio);
19653   }
19654
19655   // See if we can recurse into the operand to combine more things.
19656   switch (Op.getOpcode()) {
19657     case X86ISD::PSHUFB:
19658       HasPSHUFB = true;
19659     case X86ISD::PSHUFD:
19660     case X86ISD::PSHUFHW:
19661     case X86ISD::PSHUFLW:
19662       if (Op.getOperand(0).hasOneUse() &&
19663           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19664                                         HasPSHUFB, DAG, DCI, Subtarget))
19665         return true;
19666       break;
19667
19668     case X86ISD::UNPCKL:
19669     case X86ISD::UNPCKH:
19670       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19671       // We can't check for single use, we have to check that this shuffle is the only user.
19672       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19673           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19674                                         HasPSHUFB, DAG, DCI, Subtarget))
19675           return true;
19676       break;
19677   }
19678
19679   // Minor canonicalization of the accumulated shuffle mask to make it easier
19680   // to match below. All this does is detect masks with squential pairs of
19681   // elements, and shrink them to the half-width mask. It does this in a loop
19682   // so it will reduce the size of the mask to the minimal width mask which
19683   // performs an equivalent shuffle.
19684   while (Mask.size() > 1 && canWidenShuffleElements(Mask)) {
19685     for (int i = 0, e = Mask.size() / 2; i < e; ++i)
19686       Mask[i] = Mask[2 * i] / 2;
19687     Mask.resize(Mask.size() / 2);
19688   }
19689
19690   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19691                                 Subtarget);
19692 }
19693
19694 /// \brief Get the PSHUF-style mask from PSHUF node.
19695 ///
19696 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19697 /// PSHUF-style masks that can be reused with such instructions.
19698 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19699   SmallVector<int, 4> Mask;
19700   bool IsUnary;
19701   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19702   (void)HaveMask;
19703   assert(HaveMask);
19704
19705   switch (N.getOpcode()) {
19706   case X86ISD::PSHUFD:
19707     return Mask;
19708   case X86ISD::PSHUFLW:
19709     Mask.resize(4);
19710     return Mask;
19711   case X86ISD::PSHUFHW:
19712     Mask.erase(Mask.begin(), Mask.begin() + 4);
19713     for (int &M : Mask)
19714       M -= 4;
19715     return Mask;
19716   default:
19717     llvm_unreachable("No valid shuffle instruction found!");
19718   }
19719 }
19720
19721 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19722 ///
19723 /// We walk up the chain and look for a combinable shuffle, skipping over
19724 /// shuffles that we could hoist this shuffle's transformation past without
19725 /// altering anything.
19726 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19727                                          SelectionDAG &DAG,
19728                                          TargetLowering::DAGCombinerInfo &DCI) {
19729   assert(N.getOpcode() == X86ISD::PSHUFD &&
19730          "Called with something other than an x86 128-bit half shuffle!");
19731   SDLoc DL(N);
19732
19733   // Walk up a single-use chain looking for a combinable shuffle.
19734   SDValue V = N.getOperand(0);
19735   for (; V.hasOneUse(); V = V.getOperand(0)) {
19736     switch (V.getOpcode()) {
19737     default:
19738       return false; // Nothing combined!
19739
19740     case ISD::BITCAST:
19741       // Skip bitcasts as we always know the type for the target specific
19742       // instructions.
19743       continue;
19744
19745     case X86ISD::PSHUFD:
19746       // Found another dword shuffle.
19747       break;
19748
19749     case X86ISD::PSHUFLW:
19750       // Check that the low words (being shuffled) are the identity in the
19751       // dword shuffle, and the high words are self-contained.
19752       if (Mask[0] != 0 || Mask[1] != 1 ||
19753           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19754         return false;
19755
19756       continue;
19757
19758     case X86ISD::PSHUFHW:
19759       // Check that the high words (being shuffled) are the identity in the
19760       // dword shuffle, and the low words are self-contained.
19761       if (Mask[2] != 2 || Mask[3] != 3 ||
19762           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19763         return false;
19764
19765       continue;
19766
19767     case X86ISD::UNPCKL:
19768     case X86ISD::UNPCKH:
19769       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19770       // shuffle into a preceding word shuffle.
19771       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19772         return false;
19773
19774       // Search for a half-shuffle which we can combine with.
19775       unsigned CombineOp =
19776           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19777       if (V.getOperand(0) != V.getOperand(1) ||
19778           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19779         return false;
19780       V = V.getOperand(0);
19781       do {
19782         switch (V.getOpcode()) {
19783         default:
19784           return false; // Nothing to combine.
19785
19786         case X86ISD::PSHUFLW:
19787         case X86ISD::PSHUFHW:
19788           if (V.getOpcode() == CombineOp)
19789             break;
19790
19791           // Fallthrough!
19792         case ISD::BITCAST:
19793           V = V.getOperand(0);
19794           continue;
19795         }
19796         break;
19797       } while (V.hasOneUse());
19798       break;
19799     }
19800     // Break out of the loop if we break out of the switch.
19801     break;
19802   }
19803
19804   if (!V.hasOneUse())
19805     // We fell out of the loop without finding a viable combining instruction.
19806     return false;
19807
19808   // Record the old value to use in RAUW-ing.
19809   SDValue Old = V;
19810
19811   // Merge this node's mask and our incoming mask.
19812   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19813   for (int &M : Mask)
19814     M = VMask[M];
19815   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19816                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19817
19818   // It is possible that one of the combinable shuffles was completely absorbed
19819   // by the other, just replace it and revisit all users in that case.
19820   if (Old.getNode() == V.getNode()) {
19821     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19822     return true;
19823   }
19824
19825   // Replace N with its operand as we're going to combine that shuffle away.
19826   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19827
19828   // Replace the combinable shuffle with the combined one, updating all users
19829   // so that we re-evaluate the chain here.
19830   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19831   return true;
19832 }
19833
19834 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19835 ///
19836 /// We walk up the chain, skipping shuffles of the other half and looking
19837 /// through shuffles which switch halves trying to find a shuffle of the same
19838 /// pair of dwords.
19839 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19840                                         SelectionDAG &DAG,
19841                                         TargetLowering::DAGCombinerInfo &DCI) {
19842   assert(
19843       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19844       "Called with something other than an x86 128-bit half shuffle!");
19845   SDLoc DL(N);
19846   unsigned CombineOpcode = N.getOpcode();
19847
19848   // Walk up a single-use chain looking for a combinable shuffle.
19849   SDValue V = N.getOperand(0);
19850   for (; V.hasOneUse(); V = V.getOperand(0)) {
19851     switch (V.getOpcode()) {
19852     default:
19853       return false; // Nothing combined!
19854
19855     case ISD::BITCAST:
19856       // Skip bitcasts as we always know the type for the target specific
19857       // instructions.
19858       continue;
19859
19860     case X86ISD::PSHUFLW:
19861     case X86ISD::PSHUFHW:
19862       if (V.getOpcode() == CombineOpcode)
19863         break;
19864
19865       // Other-half shuffles are no-ops.
19866       continue;
19867     }
19868     // Break out of the loop if we break out of the switch.
19869     break;
19870   }
19871
19872   if (!V.hasOneUse())
19873     // We fell out of the loop without finding a viable combining instruction.
19874     return false;
19875
19876   // Combine away the bottom node as its shuffle will be accumulated into
19877   // a preceding shuffle.
19878   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19879
19880   // Record the old value.
19881   SDValue Old = V;
19882
19883   // Merge this node's mask and our incoming mask (adjusted to account for all
19884   // the pshufd instructions encountered).
19885   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19886   for (int &M : Mask)
19887     M = VMask[M];
19888   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19889                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19890
19891   // Check that the shuffles didn't cancel each other out. If not, we need to
19892   // combine to the new one.
19893   if (Old != V)
19894     // Replace the combinable shuffle with the combined one, updating all users
19895     // so that we re-evaluate the chain here.
19896     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19897
19898   return true;
19899 }
19900
19901 /// \brief Try to combine x86 target specific shuffles.
19902 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19903                                            TargetLowering::DAGCombinerInfo &DCI,
19904                                            const X86Subtarget *Subtarget) {
19905   SDLoc DL(N);
19906   MVT VT = N.getSimpleValueType();
19907   SmallVector<int, 4> Mask;
19908
19909   switch (N.getOpcode()) {
19910   case X86ISD::PSHUFD:
19911   case X86ISD::PSHUFLW:
19912   case X86ISD::PSHUFHW:
19913     Mask = getPSHUFShuffleMask(N);
19914     assert(Mask.size() == 4);
19915     break;
19916   default:
19917     return SDValue();
19918   }
19919
19920   // Nuke no-op shuffles that show up after combining.
19921   if (isNoopShuffleMask(Mask))
19922     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19923
19924   // Look for simplifications involving one or two shuffle instructions.
19925   SDValue V = N.getOperand(0);
19926   switch (N.getOpcode()) {
19927   default:
19928     break;
19929   case X86ISD::PSHUFLW:
19930   case X86ISD::PSHUFHW:
19931     assert(VT == MVT::v8i16);
19932     (void)VT;
19933
19934     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19935       return SDValue(); // We combined away this shuffle, so we're done.
19936
19937     // See if this reduces to a PSHUFD which is no more expensive and can
19938     // combine with more operations.
19939     if (canWidenShuffleElements(Mask)) {
19940       int DMask[] = {-1, -1, -1, -1};
19941       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19942       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19943       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19944       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19945       DCI.AddToWorklist(V.getNode());
19946       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19947                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19948       DCI.AddToWorklist(V.getNode());
19949       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19950     }
19951
19952     // Look for shuffle patterns which can be implemented as a single unpack.
19953     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19954     // only works when we have a PSHUFD followed by two half-shuffles.
19955     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19956         (V.getOpcode() == X86ISD::PSHUFLW ||
19957          V.getOpcode() == X86ISD::PSHUFHW) &&
19958         V.getOpcode() != N.getOpcode() &&
19959         V.hasOneUse()) {
19960       SDValue D = V.getOperand(0);
19961       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19962         D = D.getOperand(0);
19963       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19964         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19965         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19966         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19967         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19968         int WordMask[8];
19969         for (int i = 0; i < 4; ++i) {
19970           WordMask[i + NOffset] = Mask[i] + NOffset;
19971           WordMask[i + VOffset] = VMask[i] + VOffset;
19972         }
19973         // Map the word mask through the DWord mask.
19974         int MappedMask[8];
19975         for (int i = 0; i < 8; ++i)
19976           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19977         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19978         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19979         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19980                        std::begin(UnpackLoMask)) ||
19981             std::equal(std::begin(MappedMask), std::end(MappedMask),
19982                        std::begin(UnpackHiMask))) {
19983           // We can replace all three shuffles with an unpack.
19984           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19985           DCI.AddToWorklist(V.getNode());
19986           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19987                                                 : X86ISD::UNPCKH,
19988                              DL, MVT::v8i16, V, V);
19989         }
19990       }
19991     }
19992
19993     break;
19994
19995   case X86ISD::PSHUFD:
19996     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19997       return SDValue(); // We combined away this shuffle.
19998
19999     break;
20000   }
20001
20002   return SDValue();
20003 }
20004
20005 /// PerformShuffleCombine - Performs several different shuffle combines.
20006 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20007                                      TargetLowering::DAGCombinerInfo &DCI,
20008                                      const X86Subtarget *Subtarget) {
20009   SDLoc dl(N);
20010   SDValue N0 = N->getOperand(0);
20011   SDValue N1 = N->getOperand(1);
20012   EVT VT = N->getValueType(0);
20013
20014   // Don't create instructions with illegal types after legalize types has run.
20015   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20016   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20017     return SDValue();
20018
20019   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20020   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20021       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20022     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20023
20024   // During Type Legalization, when promoting illegal vector types,
20025   // the backend might introduce new shuffle dag nodes and bitcasts.
20026   //
20027   // This code performs the following transformation:
20028   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20029   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20030   //
20031   // We do this only if both the bitcast and the BINOP dag nodes have
20032   // one use. Also, perform this transformation only if the new binary
20033   // operation is legal. This is to avoid introducing dag nodes that
20034   // potentially need to be further expanded (or custom lowered) into a
20035   // less optimal sequence of dag nodes.
20036   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20037       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20038       N0.getOpcode() == ISD::BITCAST) {
20039     SDValue BC0 = N0.getOperand(0);
20040     EVT SVT = BC0.getValueType();
20041     unsigned Opcode = BC0.getOpcode();
20042     unsigned NumElts = VT.getVectorNumElements();
20043     
20044     if (BC0.hasOneUse() && SVT.isVector() &&
20045         SVT.getVectorNumElements() * 2 == NumElts &&
20046         TLI.isOperationLegal(Opcode, VT)) {
20047       bool CanFold = false;
20048       switch (Opcode) {
20049       default : break;
20050       case ISD::ADD :
20051       case ISD::FADD :
20052       case ISD::SUB :
20053       case ISD::FSUB :
20054       case ISD::MUL :
20055       case ISD::FMUL :
20056         CanFold = true;
20057       }
20058
20059       unsigned SVTNumElts = SVT.getVectorNumElements();
20060       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20061       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20062         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20063       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20064         CanFold = SVOp->getMaskElt(i) < 0;
20065
20066       if (CanFold) {
20067         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20068         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20069         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20070         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20071       }
20072     }
20073   }
20074
20075   // Only handle 128 wide vector from here on.
20076   if (!VT.is128BitVector())
20077     return SDValue();
20078
20079   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20080   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20081   // consecutive, non-overlapping, and in the right order.
20082   SmallVector<SDValue, 16> Elts;
20083   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20084     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20085
20086   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20087   if (LD.getNode())
20088     return LD;
20089
20090   if (isTargetShuffle(N->getOpcode())) {
20091     SDValue Shuffle =
20092         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20093     if (Shuffle.getNode())
20094       return Shuffle;
20095
20096     // Try recursively combining arbitrary sequences of x86 shuffle
20097     // instructions into higher-order shuffles. We do this after combining
20098     // specific PSHUF instruction sequences into their minimal form so that we
20099     // can evaluate how many specialized shuffle instructions are involved in
20100     // a particular chain.
20101     SmallVector<int, 1> NonceMask; // Just a placeholder.
20102     NonceMask.push_back(0);
20103     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20104                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20105                                       DCI, Subtarget))
20106       return SDValue(); // This routine will use CombineTo to replace N.
20107   }
20108
20109   return SDValue();
20110 }
20111
20112 /// PerformTruncateCombine - Converts truncate operation to
20113 /// a sequence of vector shuffle operations.
20114 /// It is possible when we truncate 256-bit vector to 128-bit vector
20115 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20116                                       TargetLowering::DAGCombinerInfo &DCI,
20117                                       const X86Subtarget *Subtarget)  {
20118   return SDValue();
20119 }
20120
20121 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20122 /// specific shuffle of a load can be folded into a single element load.
20123 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20124 /// shuffles have been customed lowered so we need to handle those here.
20125 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20126                                          TargetLowering::DAGCombinerInfo &DCI) {
20127   if (DCI.isBeforeLegalizeOps())
20128     return SDValue();
20129
20130   SDValue InVec = N->getOperand(0);
20131   SDValue EltNo = N->getOperand(1);
20132
20133   if (!isa<ConstantSDNode>(EltNo))
20134     return SDValue();
20135
20136   EVT VT = InVec.getValueType();
20137
20138   bool HasShuffleIntoBitcast = false;
20139   if (InVec.getOpcode() == ISD::BITCAST) {
20140     // Don't duplicate a load with other uses.
20141     if (!InVec.hasOneUse())
20142       return SDValue();
20143     EVT BCVT = InVec.getOperand(0).getValueType();
20144     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
20145       return SDValue();
20146     InVec = InVec.getOperand(0);
20147     HasShuffleIntoBitcast = true;
20148   }
20149
20150   if (!isTargetShuffle(InVec.getOpcode()))
20151     return SDValue();
20152
20153   // Don't duplicate a load with other uses.
20154   if (!InVec.hasOneUse())
20155     return SDValue();
20156
20157   SmallVector<int, 16> ShuffleMask;
20158   bool UnaryShuffle;
20159   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
20160                             UnaryShuffle))
20161     return SDValue();
20162
20163   // Select the input vector, guarding against out of range extract vector.
20164   unsigned NumElems = VT.getVectorNumElements();
20165   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20166   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20167   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20168                                          : InVec.getOperand(1);
20169
20170   // If inputs to shuffle are the same for both ops, then allow 2 uses
20171   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20172
20173   if (LdNode.getOpcode() == ISD::BITCAST) {
20174     // Don't duplicate a load with other uses.
20175     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20176       return SDValue();
20177
20178     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20179     LdNode = LdNode.getOperand(0);
20180   }
20181
20182   if (!ISD::isNormalLoad(LdNode.getNode()))
20183     return SDValue();
20184
20185   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20186
20187   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20188     return SDValue();
20189
20190   if (HasShuffleIntoBitcast) {
20191     // If there's a bitcast before the shuffle, check if the load type and
20192     // alignment is valid.
20193     unsigned Align = LN0->getAlignment();
20194     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20195     unsigned NewAlign = TLI.getDataLayout()->
20196       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
20197
20198     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
20199       return SDValue();
20200   }
20201
20202   // All checks match so transform back to vector_shuffle so that DAG combiner
20203   // can finish the job
20204   SDLoc dl(N);
20205
20206   // Create shuffle node taking into account the case that its a unary shuffle
20207   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
20208   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
20209                                  InVec.getOperand(0), Shuffle,
20210                                  &ShuffleMask[0]);
20211   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
20212   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20213                      EltNo);
20214 }
20215
20216 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20217 /// generation and convert it from being a bunch of shuffles and extracts
20218 /// to a simple store and scalar loads to extract the elements.
20219 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20220                                          TargetLowering::DAGCombinerInfo &DCI) {
20221   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20222   if (NewOp.getNode())
20223     return NewOp;
20224
20225   SDValue InputVector = N->getOperand(0);
20226
20227   // Detect whether we are trying to convert from mmx to i32 and the bitcast
20228   // from mmx to v2i32 has a single usage.
20229   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
20230       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
20231       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
20232     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20233                        N->getValueType(0),
20234                        InputVector.getNode()->getOperand(0));
20235
20236   // Only operate on vectors of 4 elements, where the alternative shuffling
20237   // gets to be more expensive.
20238   if (InputVector.getValueType() != MVT::v4i32)
20239     return SDValue();
20240
20241   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20242   // single use which is a sign-extend or zero-extend, and all elements are
20243   // used.
20244   SmallVector<SDNode *, 4> Uses;
20245   unsigned ExtractedElements = 0;
20246   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20247        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20248     if (UI.getUse().getResNo() != InputVector.getResNo())
20249       return SDValue();
20250
20251     SDNode *Extract = *UI;
20252     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20253       return SDValue();
20254
20255     if (Extract->getValueType(0) != MVT::i32)
20256       return SDValue();
20257     if (!Extract->hasOneUse())
20258       return SDValue();
20259     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20260         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20261       return SDValue();
20262     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20263       return SDValue();
20264
20265     // Record which element was extracted.
20266     ExtractedElements |=
20267       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20268
20269     Uses.push_back(Extract);
20270   }
20271
20272   // If not all the elements were used, this may not be worthwhile.
20273   if (ExtractedElements != 15)
20274     return SDValue();
20275
20276   // Ok, we've now decided to do the transformation.
20277   SDLoc dl(InputVector);
20278
20279   // Store the value to a temporary stack slot.
20280   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20281   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20282                             MachinePointerInfo(), false, false, 0);
20283
20284   // Replace each use (extract) with a load of the appropriate element.
20285   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20286        UE = Uses.end(); UI != UE; ++UI) {
20287     SDNode *Extract = *UI;
20288
20289     // cOMpute the element's address.
20290     SDValue Idx = Extract->getOperand(1);
20291     unsigned EltSize =
20292         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
20293     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
20294     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20295     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20296
20297     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20298                                      StackPtr, OffsetVal);
20299
20300     // Load the scalar.
20301     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
20302                                      ScalarAddr, MachinePointerInfo(),
20303                                      false, false, false, 0);
20304
20305     // Replace the exact with the load.
20306     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
20307   }
20308
20309   // The replacement was made in place; don't return anything.
20310   return SDValue();
20311 }
20312
20313 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20314 static std::pair<unsigned, bool>
20315 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20316                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20317   if (!VT.isVector())
20318     return std::make_pair(0, false);
20319
20320   bool NeedSplit = false;
20321   switch (VT.getSimpleVT().SimpleTy) {
20322   default: return std::make_pair(0, false);
20323   case MVT::v32i8:
20324   case MVT::v16i16:
20325   case MVT::v8i32:
20326     if (!Subtarget->hasAVX2())
20327       NeedSplit = true;
20328     if (!Subtarget->hasAVX())
20329       return std::make_pair(0, false);
20330     break;
20331   case MVT::v16i8:
20332   case MVT::v8i16:
20333   case MVT::v4i32:
20334     if (!Subtarget->hasSSE2())
20335       return std::make_pair(0, false);
20336   }
20337
20338   // SSE2 has only a small subset of the operations.
20339   bool hasUnsigned = Subtarget->hasSSE41() ||
20340                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20341   bool hasSigned = Subtarget->hasSSE41() ||
20342                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20343
20344   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20345
20346   unsigned Opc = 0;
20347   // Check for x CC y ? x : y.
20348   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20349       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20350     switch (CC) {
20351     default: break;
20352     case ISD::SETULT:
20353     case ISD::SETULE:
20354       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20355     case ISD::SETUGT:
20356     case ISD::SETUGE:
20357       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20358     case ISD::SETLT:
20359     case ISD::SETLE:
20360       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20361     case ISD::SETGT:
20362     case ISD::SETGE:
20363       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20364     }
20365   // Check for x CC y ? y : x -- a min/max with reversed arms.
20366   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20367              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20368     switch (CC) {
20369     default: break;
20370     case ISD::SETULT:
20371     case ISD::SETULE:
20372       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20373     case ISD::SETUGT:
20374     case ISD::SETUGE:
20375       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20376     case ISD::SETLT:
20377     case ISD::SETLE:
20378       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20379     case ISD::SETGT:
20380     case ISD::SETGE:
20381       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20382     }
20383   }
20384
20385   return std::make_pair(Opc, NeedSplit);
20386 }
20387
20388 static SDValue
20389 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20390                                       const X86Subtarget *Subtarget) {
20391   SDLoc dl(N);
20392   SDValue Cond = N->getOperand(0);
20393   SDValue LHS = N->getOperand(1);
20394   SDValue RHS = N->getOperand(2);
20395
20396   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20397     SDValue CondSrc = Cond->getOperand(0);
20398     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20399       Cond = CondSrc->getOperand(0);
20400   }
20401
20402   MVT VT = N->getSimpleValueType(0);
20403   MVT EltVT = VT.getVectorElementType();
20404   unsigned NumElems = VT.getVectorNumElements();
20405   // There is no blend with immediate in AVX-512.
20406   if (VT.is512BitVector())
20407     return SDValue();
20408
20409   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
20410     return SDValue();
20411   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
20412     return SDValue();
20413
20414   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20415     return SDValue();
20416
20417   unsigned MaskValue = 0;
20418   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20419     return SDValue();
20420
20421   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20422   for (unsigned i = 0; i < NumElems; ++i) {
20423     // Be sure we emit undef where we can.
20424     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20425       ShuffleMask[i] = -1;
20426     else
20427       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20428   }
20429
20430   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20431 }
20432
20433 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20434 /// nodes.
20435 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20436                                     TargetLowering::DAGCombinerInfo &DCI,
20437                                     const X86Subtarget *Subtarget) {
20438   SDLoc DL(N);
20439   SDValue Cond = N->getOperand(0);
20440   // Get the LHS/RHS of the select.
20441   SDValue LHS = N->getOperand(1);
20442   SDValue RHS = N->getOperand(2);
20443   EVT VT = LHS.getValueType();
20444   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20445
20446   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20447   // instructions match the semantics of the common C idiom x<y?x:y but not
20448   // x<=y?x:y, because of how they handle negative zero (which can be
20449   // ignored in unsafe-math mode).
20450   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20451       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20452       (Subtarget->hasSSE2() ||
20453        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20454     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20455
20456     unsigned Opcode = 0;
20457     // Check for x CC y ? x : y.
20458     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20459         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20460       switch (CC) {
20461       default: break;
20462       case ISD::SETULT:
20463         // Converting this to a min would handle NaNs incorrectly, and swapping
20464         // the operands would cause it to handle comparisons between positive
20465         // and negative zero incorrectly.
20466         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20467           if (!DAG.getTarget().Options.UnsafeFPMath &&
20468               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20469             break;
20470           std::swap(LHS, RHS);
20471         }
20472         Opcode = X86ISD::FMIN;
20473         break;
20474       case ISD::SETOLE:
20475         // Converting this to a min would handle comparisons between positive
20476         // and negative zero incorrectly.
20477         if (!DAG.getTarget().Options.UnsafeFPMath &&
20478             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20479           break;
20480         Opcode = X86ISD::FMIN;
20481         break;
20482       case ISD::SETULE:
20483         // Converting this to a min would handle both negative zeros and NaNs
20484         // incorrectly, but we can swap the operands to fix both.
20485         std::swap(LHS, RHS);
20486       case ISD::SETOLT:
20487       case ISD::SETLT:
20488       case ISD::SETLE:
20489         Opcode = X86ISD::FMIN;
20490         break;
20491
20492       case ISD::SETOGE:
20493         // Converting this to a max would handle comparisons between positive
20494         // and negative zero incorrectly.
20495         if (!DAG.getTarget().Options.UnsafeFPMath &&
20496             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20497           break;
20498         Opcode = X86ISD::FMAX;
20499         break;
20500       case ISD::SETUGT:
20501         // Converting this to a max would handle NaNs incorrectly, and swapping
20502         // the operands would cause it to handle comparisons between positive
20503         // and negative zero incorrectly.
20504         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20505           if (!DAG.getTarget().Options.UnsafeFPMath &&
20506               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20507             break;
20508           std::swap(LHS, RHS);
20509         }
20510         Opcode = X86ISD::FMAX;
20511         break;
20512       case ISD::SETUGE:
20513         // Converting this to a max would handle both negative zeros and NaNs
20514         // incorrectly, but we can swap the operands to fix both.
20515         std::swap(LHS, RHS);
20516       case ISD::SETOGT:
20517       case ISD::SETGT:
20518       case ISD::SETGE:
20519         Opcode = X86ISD::FMAX;
20520         break;
20521       }
20522     // Check for x CC y ? y : x -- a min/max with reversed arms.
20523     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20524                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20525       switch (CC) {
20526       default: break;
20527       case ISD::SETOGE:
20528         // Converting this to a min would handle comparisons between positive
20529         // and negative zero incorrectly, and swapping the operands would
20530         // cause it to handle NaNs incorrectly.
20531         if (!DAG.getTarget().Options.UnsafeFPMath &&
20532             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20533           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20534             break;
20535           std::swap(LHS, RHS);
20536         }
20537         Opcode = X86ISD::FMIN;
20538         break;
20539       case ISD::SETUGT:
20540         // Converting this to a min would handle NaNs incorrectly.
20541         if (!DAG.getTarget().Options.UnsafeFPMath &&
20542             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20543           break;
20544         Opcode = X86ISD::FMIN;
20545         break;
20546       case ISD::SETUGE:
20547         // Converting this to a min would handle both negative zeros and NaNs
20548         // incorrectly, but we can swap the operands to fix both.
20549         std::swap(LHS, RHS);
20550       case ISD::SETOGT:
20551       case ISD::SETGT:
20552       case ISD::SETGE:
20553         Opcode = X86ISD::FMIN;
20554         break;
20555
20556       case ISD::SETULT:
20557         // Converting this to a max would handle NaNs incorrectly.
20558         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20559           break;
20560         Opcode = X86ISD::FMAX;
20561         break;
20562       case ISD::SETOLE:
20563         // Converting this to a max would handle comparisons between positive
20564         // and negative zero incorrectly, and swapping the operands would
20565         // cause it to handle NaNs incorrectly.
20566         if (!DAG.getTarget().Options.UnsafeFPMath &&
20567             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20568           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20569             break;
20570           std::swap(LHS, RHS);
20571         }
20572         Opcode = X86ISD::FMAX;
20573         break;
20574       case ISD::SETULE:
20575         // Converting this to a max would handle both negative zeros and NaNs
20576         // incorrectly, but we can swap the operands to fix both.
20577         std::swap(LHS, RHS);
20578       case ISD::SETOLT:
20579       case ISD::SETLT:
20580       case ISD::SETLE:
20581         Opcode = X86ISD::FMAX;
20582         break;
20583       }
20584     }
20585
20586     if (Opcode)
20587       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20588   }
20589
20590   EVT CondVT = Cond.getValueType();
20591   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20592       CondVT.getVectorElementType() == MVT::i1) {
20593     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20594     // lowering on AVX-512. In this case we convert it to
20595     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20596     // The same situation for all 128 and 256-bit vectors of i8 and i16
20597     EVT OpVT = LHS.getValueType();
20598     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20599         (OpVT.getVectorElementType() == MVT::i8 ||
20600          OpVT.getVectorElementType() == MVT::i16)) {
20601       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20602       DCI.AddToWorklist(Cond.getNode());
20603       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20604     }
20605   }
20606   // If this is a select between two integer constants, try to do some
20607   // optimizations.
20608   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20609     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20610       // Don't do this for crazy integer types.
20611       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20612         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20613         // so that TrueC (the true value) is larger than FalseC.
20614         bool NeedsCondInvert = false;
20615
20616         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20617             // Efficiently invertible.
20618             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20619              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20620               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20621           NeedsCondInvert = true;
20622           std::swap(TrueC, FalseC);
20623         }
20624
20625         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20626         if (FalseC->getAPIntValue() == 0 &&
20627             TrueC->getAPIntValue().isPowerOf2()) {
20628           if (NeedsCondInvert) // Invert the condition if needed.
20629             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20630                                DAG.getConstant(1, Cond.getValueType()));
20631
20632           // Zero extend the condition if needed.
20633           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20634
20635           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20636           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20637                              DAG.getConstant(ShAmt, MVT::i8));
20638         }
20639
20640         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20641         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20642           if (NeedsCondInvert) // Invert the condition if needed.
20643             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20644                                DAG.getConstant(1, Cond.getValueType()));
20645
20646           // Zero extend the condition if needed.
20647           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20648                              FalseC->getValueType(0), Cond);
20649           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20650                              SDValue(FalseC, 0));
20651         }
20652
20653         // Optimize cases that will turn into an LEA instruction.  This requires
20654         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20655         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20656           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20657           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20658
20659           bool isFastMultiplier = false;
20660           if (Diff < 10) {
20661             switch ((unsigned char)Diff) {
20662               default: break;
20663               case 1:  // result = add base, cond
20664               case 2:  // result = lea base(    , cond*2)
20665               case 3:  // result = lea base(cond, cond*2)
20666               case 4:  // result = lea base(    , cond*4)
20667               case 5:  // result = lea base(cond, cond*4)
20668               case 8:  // result = lea base(    , cond*8)
20669               case 9:  // result = lea base(cond, cond*8)
20670                 isFastMultiplier = true;
20671                 break;
20672             }
20673           }
20674
20675           if (isFastMultiplier) {
20676             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20677             if (NeedsCondInvert) // Invert the condition if needed.
20678               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20679                                  DAG.getConstant(1, Cond.getValueType()));
20680
20681             // Zero extend the condition if needed.
20682             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20683                                Cond);
20684             // Scale the condition by the difference.
20685             if (Diff != 1)
20686               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20687                                  DAG.getConstant(Diff, Cond.getValueType()));
20688
20689             // Add the base if non-zero.
20690             if (FalseC->getAPIntValue() != 0)
20691               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20692                                  SDValue(FalseC, 0));
20693             return Cond;
20694           }
20695         }
20696       }
20697   }
20698
20699   // Canonicalize max and min:
20700   // (x > y) ? x : y -> (x >= y) ? x : y
20701   // (x < y) ? x : y -> (x <= y) ? x : y
20702   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20703   // the need for an extra compare
20704   // against zero. e.g.
20705   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20706   // subl   %esi, %edi
20707   // testl  %edi, %edi
20708   // movl   $0, %eax
20709   // cmovgl %edi, %eax
20710   // =>
20711   // xorl   %eax, %eax
20712   // subl   %esi, $edi
20713   // cmovsl %eax, %edi
20714   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20715       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20716       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20717     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20718     switch (CC) {
20719     default: break;
20720     case ISD::SETLT:
20721     case ISD::SETGT: {
20722       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20723       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20724                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20725       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20726     }
20727     }
20728   }
20729
20730   // Early exit check
20731   if (!TLI.isTypeLegal(VT))
20732     return SDValue();
20733
20734   // Match VSELECTs into subs with unsigned saturation.
20735   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20736       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20737       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20738        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20739     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20740
20741     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20742     // left side invert the predicate to simplify logic below.
20743     SDValue Other;
20744     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20745       Other = RHS;
20746       CC = ISD::getSetCCInverse(CC, true);
20747     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20748       Other = LHS;
20749     }
20750
20751     if (Other.getNode() && Other->getNumOperands() == 2 &&
20752         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20753       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20754       SDValue CondRHS = Cond->getOperand(1);
20755
20756       // Look for a general sub with unsigned saturation first.
20757       // x >= y ? x-y : 0 --> subus x, y
20758       // x >  y ? x-y : 0 --> subus x, y
20759       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20760           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20761         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20762
20763       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20764         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20765           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20766             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20767               // If the RHS is a constant we have to reverse the const
20768               // canonicalization.
20769               // x > C-1 ? x+-C : 0 --> subus x, C
20770               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20771                   CondRHSConst->getAPIntValue() ==
20772                       (-OpRHSConst->getAPIntValue() - 1))
20773                 return DAG.getNode(
20774                     X86ISD::SUBUS, DL, VT, OpLHS,
20775                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20776
20777           // Another special case: If C was a sign bit, the sub has been
20778           // canonicalized into a xor.
20779           // FIXME: Would it be better to use computeKnownBits to determine
20780           //        whether it's safe to decanonicalize the xor?
20781           // x s< 0 ? x^C : 0 --> subus x, C
20782           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20783               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20784               OpRHSConst->getAPIntValue().isSignBit())
20785             // Note that we have to rebuild the RHS constant here to ensure we
20786             // don't rely on particular values of undef lanes.
20787             return DAG.getNode(
20788                 X86ISD::SUBUS, DL, VT, OpLHS,
20789                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20790         }
20791     }
20792   }
20793
20794   // Try to match a min/max vector operation.
20795   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20796     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20797     unsigned Opc = ret.first;
20798     bool NeedSplit = ret.second;
20799
20800     if (Opc && NeedSplit) {
20801       unsigned NumElems = VT.getVectorNumElements();
20802       // Extract the LHS vectors
20803       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20804       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20805
20806       // Extract the RHS vectors
20807       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20808       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20809
20810       // Create min/max for each subvector
20811       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20812       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20813
20814       // Merge the result
20815       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20816     } else if (Opc)
20817       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20818   }
20819
20820   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20821   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20822       // Check if SETCC has already been promoted
20823       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20824       // Check that condition value type matches vselect operand type
20825       CondVT == VT) { 
20826
20827     assert(Cond.getValueType().isVector() &&
20828            "vector select expects a vector selector!");
20829
20830     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20831     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20832
20833     if (!TValIsAllOnes && !FValIsAllZeros) {
20834       // Try invert the condition if true value is not all 1s and false value
20835       // is not all 0s.
20836       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20837       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20838
20839       if (TValIsAllZeros || FValIsAllOnes) {
20840         SDValue CC = Cond.getOperand(2);
20841         ISD::CondCode NewCC =
20842           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20843                                Cond.getOperand(0).getValueType().isInteger());
20844         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20845         std::swap(LHS, RHS);
20846         TValIsAllOnes = FValIsAllOnes;
20847         FValIsAllZeros = TValIsAllZeros;
20848       }
20849     }
20850
20851     if (TValIsAllOnes || FValIsAllZeros) {
20852       SDValue Ret;
20853
20854       if (TValIsAllOnes && FValIsAllZeros)
20855         Ret = Cond;
20856       else if (TValIsAllOnes)
20857         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20858                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20859       else if (FValIsAllZeros)
20860         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20861                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20862
20863       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20864     }
20865   }
20866
20867   // Try to fold this VSELECT into a MOVSS/MOVSD
20868   if (N->getOpcode() == ISD::VSELECT &&
20869       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20870     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20871         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20872       bool CanFold = false;
20873       unsigned NumElems = Cond.getNumOperands();
20874       SDValue A = LHS;
20875       SDValue B = RHS;
20876       
20877       if (isZero(Cond.getOperand(0))) {
20878         CanFold = true;
20879
20880         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20881         // fold (vselect <0,-1> -> (movsd A, B)
20882         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20883           CanFold = isAllOnes(Cond.getOperand(i));
20884       } else if (isAllOnes(Cond.getOperand(0))) {
20885         CanFold = true;
20886         std::swap(A, B);
20887
20888         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20889         // fold (vselect <-1,0> -> (movsd B, A)
20890         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20891           CanFold = isZero(Cond.getOperand(i));
20892       }
20893
20894       if (CanFold) {
20895         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20896           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20897         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20898       }
20899
20900       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20901         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20902         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20903         //                             (v2i64 (bitcast B)))))
20904         //
20905         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20906         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20907         //                             (v2f64 (bitcast B)))))
20908         //
20909         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20910         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20911         //                             (v2i64 (bitcast A)))))
20912         //
20913         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20914         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20915         //                             (v2f64 (bitcast A)))))
20916
20917         CanFold = (isZero(Cond.getOperand(0)) &&
20918                    isZero(Cond.getOperand(1)) &&
20919                    isAllOnes(Cond.getOperand(2)) &&
20920                    isAllOnes(Cond.getOperand(3)));
20921
20922         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20923             isAllOnes(Cond.getOperand(1)) &&
20924             isZero(Cond.getOperand(2)) &&
20925             isZero(Cond.getOperand(3))) {
20926           CanFold = true;
20927           std::swap(LHS, RHS);
20928         }
20929
20930         if (CanFold) {
20931           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20932           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20933           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20934           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20935                                                 NewB, DAG);
20936           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20937         }
20938       }
20939     }
20940   }
20941
20942   // If we know that this node is legal then we know that it is going to be
20943   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20944   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20945   // to simplify previous instructions.
20946   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20947       !DCI.isBeforeLegalize() &&
20948       // We explicitly check against v8i16 and v16i16 because, although
20949       // they're marked as Custom, they might only be legal when Cond is a
20950       // build_vector of constants. This will be taken care in a later
20951       // condition.
20952       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20953        VT != MVT::v8i16)) {
20954     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20955
20956     // Don't optimize vector selects that map to mask-registers.
20957     if (BitWidth == 1)
20958       return SDValue();
20959
20960     // Check all uses of that condition operand to check whether it will be
20961     // consumed by non-BLEND instructions, which may depend on all bits are set
20962     // properly.
20963     for (SDNode::use_iterator I = Cond->use_begin(),
20964                               E = Cond->use_end(); I != E; ++I)
20965       if (I->getOpcode() != ISD::VSELECT)
20966         // TODO: Add other opcodes eventually lowered into BLEND.
20967         return SDValue();
20968
20969     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20970     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20971
20972     APInt KnownZero, KnownOne;
20973     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20974                                           DCI.isBeforeLegalizeOps());
20975     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20976         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20977       DCI.CommitTargetLoweringOpt(TLO);
20978   }
20979
20980   // We should generate an X86ISD::BLENDI from a vselect if its argument
20981   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20982   // constants. This specific pattern gets generated when we split a
20983   // selector for a 512 bit vector in a machine without AVX512 (but with
20984   // 256-bit vectors), during legalization:
20985   //
20986   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20987   //
20988   // Iff we find this pattern and the build_vectors are built from
20989   // constants, we translate the vselect into a shuffle_vector that we
20990   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20991   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20992     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20993     if (Shuffle.getNode())
20994       return Shuffle;
20995   }
20996
20997   return SDValue();
20998 }
20999
21000 // Check whether a boolean test is testing a boolean value generated by
21001 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21002 // code.
21003 //
21004 // Simplify the following patterns:
21005 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21006 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21007 // to (Op EFLAGS Cond)
21008 //
21009 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21010 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21011 // to (Op EFLAGS !Cond)
21012 //
21013 // where Op could be BRCOND or CMOV.
21014 //
21015 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21016   // Quit if not CMP and SUB with its value result used.
21017   if (Cmp.getOpcode() != X86ISD::CMP &&
21018       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21019       return SDValue();
21020
21021   // Quit if not used as a boolean value.
21022   if (CC != X86::COND_E && CC != X86::COND_NE)
21023     return SDValue();
21024
21025   // Check CMP operands. One of them should be 0 or 1 and the other should be
21026   // an SetCC or extended from it.
21027   SDValue Op1 = Cmp.getOperand(0);
21028   SDValue Op2 = Cmp.getOperand(1);
21029
21030   SDValue SetCC;
21031   const ConstantSDNode* C = nullptr;
21032   bool needOppositeCond = (CC == X86::COND_E);
21033   bool checkAgainstTrue = false; // Is it a comparison against 1?
21034
21035   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21036     SetCC = Op2;
21037   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21038     SetCC = Op1;
21039   else // Quit if all operands are not constants.
21040     return SDValue();
21041
21042   if (C->getZExtValue() == 1) {
21043     needOppositeCond = !needOppositeCond;
21044     checkAgainstTrue = true;
21045   } else if (C->getZExtValue() != 0)
21046     // Quit if the constant is neither 0 or 1.
21047     return SDValue();
21048
21049   bool truncatedToBoolWithAnd = false;
21050   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21051   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21052          SetCC.getOpcode() == ISD::TRUNCATE ||
21053          SetCC.getOpcode() == ISD::AND) {
21054     if (SetCC.getOpcode() == ISD::AND) {
21055       int OpIdx = -1;
21056       ConstantSDNode *CS;
21057       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21058           CS->getZExtValue() == 1)
21059         OpIdx = 1;
21060       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21061           CS->getZExtValue() == 1)
21062         OpIdx = 0;
21063       if (OpIdx == -1)
21064         break;
21065       SetCC = SetCC.getOperand(OpIdx);
21066       truncatedToBoolWithAnd = true;
21067     } else
21068       SetCC = SetCC.getOperand(0);
21069   }
21070
21071   switch (SetCC.getOpcode()) {
21072   case X86ISD::SETCC_CARRY:
21073     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21074     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21075     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21076     // truncated to i1 using 'and'.
21077     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21078       break;
21079     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21080            "Invalid use of SETCC_CARRY!");
21081     // FALL THROUGH
21082   case X86ISD::SETCC:
21083     // Set the condition code or opposite one if necessary.
21084     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21085     if (needOppositeCond)
21086       CC = X86::GetOppositeBranchCondition(CC);
21087     return SetCC.getOperand(1);
21088   case X86ISD::CMOV: {
21089     // Check whether false/true value has canonical one, i.e. 0 or 1.
21090     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21091     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21092     // Quit if true value is not a constant.
21093     if (!TVal)
21094       return SDValue();
21095     // Quit if false value is not a constant.
21096     if (!FVal) {
21097       SDValue Op = SetCC.getOperand(0);
21098       // Skip 'zext' or 'trunc' node.
21099       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21100           Op.getOpcode() == ISD::TRUNCATE)
21101         Op = Op.getOperand(0);
21102       // A special case for rdrand/rdseed, where 0 is set if false cond is
21103       // found.
21104       if ((Op.getOpcode() != X86ISD::RDRAND &&
21105            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21106         return SDValue();
21107     }
21108     // Quit if false value is not the constant 0 or 1.
21109     bool FValIsFalse = true;
21110     if (FVal && FVal->getZExtValue() != 0) {
21111       if (FVal->getZExtValue() != 1)
21112         return SDValue();
21113       // If FVal is 1, opposite cond is needed.
21114       needOppositeCond = !needOppositeCond;
21115       FValIsFalse = false;
21116     }
21117     // Quit if TVal is not the constant opposite of FVal.
21118     if (FValIsFalse && TVal->getZExtValue() != 1)
21119       return SDValue();
21120     if (!FValIsFalse && TVal->getZExtValue() != 0)
21121       return SDValue();
21122     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21123     if (needOppositeCond)
21124       CC = X86::GetOppositeBranchCondition(CC);
21125     return SetCC.getOperand(3);
21126   }
21127   }
21128
21129   return SDValue();
21130 }
21131
21132 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21133 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21134                                   TargetLowering::DAGCombinerInfo &DCI,
21135                                   const X86Subtarget *Subtarget) {
21136   SDLoc DL(N);
21137
21138   // If the flag operand isn't dead, don't touch this CMOV.
21139   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21140     return SDValue();
21141
21142   SDValue FalseOp = N->getOperand(0);
21143   SDValue TrueOp = N->getOperand(1);
21144   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21145   SDValue Cond = N->getOperand(3);
21146
21147   if (CC == X86::COND_E || CC == X86::COND_NE) {
21148     switch (Cond.getOpcode()) {
21149     default: break;
21150     case X86ISD::BSR:
21151     case X86ISD::BSF:
21152       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21153       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21154         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21155     }
21156   }
21157
21158   SDValue Flags;
21159
21160   Flags = checkBoolTestSetCCCombine(Cond, CC);
21161   if (Flags.getNode() &&
21162       // Extra check as FCMOV only supports a subset of X86 cond.
21163       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21164     SDValue Ops[] = { FalseOp, TrueOp,
21165                       DAG.getConstant(CC, MVT::i8), Flags };
21166     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21167   }
21168
21169   // If this is a select between two integer constants, try to do some
21170   // optimizations.  Note that the operands are ordered the opposite of SELECT
21171   // operands.
21172   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21173     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21174       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21175       // larger than FalseC (the false value).
21176       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21177         CC = X86::GetOppositeBranchCondition(CC);
21178         std::swap(TrueC, FalseC);
21179         std::swap(TrueOp, FalseOp);
21180       }
21181
21182       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21183       // This is efficient for any integer data type (including i8/i16) and
21184       // shift amount.
21185       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21186         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21187                            DAG.getConstant(CC, MVT::i8), Cond);
21188
21189         // Zero extend the condition if needed.
21190         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21191
21192         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21193         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21194                            DAG.getConstant(ShAmt, MVT::i8));
21195         if (N->getNumValues() == 2)  // Dead flag value?
21196           return DCI.CombineTo(N, Cond, SDValue());
21197         return Cond;
21198       }
21199
21200       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21201       // for any integer data type, including i8/i16.
21202       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21203         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21204                            DAG.getConstant(CC, MVT::i8), Cond);
21205
21206         // Zero extend the condition if needed.
21207         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21208                            FalseC->getValueType(0), Cond);
21209         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21210                            SDValue(FalseC, 0));
21211
21212         if (N->getNumValues() == 2)  // Dead flag value?
21213           return DCI.CombineTo(N, Cond, SDValue());
21214         return Cond;
21215       }
21216
21217       // Optimize cases that will turn into an LEA instruction.  This requires
21218       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21219       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21220         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21221         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21222
21223         bool isFastMultiplier = false;
21224         if (Diff < 10) {
21225           switch ((unsigned char)Diff) {
21226           default: break;
21227           case 1:  // result = add base, cond
21228           case 2:  // result = lea base(    , cond*2)
21229           case 3:  // result = lea base(cond, cond*2)
21230           case 4:  // result = lea base(    , cond*4)
21231           case 5:  // result = lea base(cond, cond*4)
21232           case 8:  // result = lea base(    , cond*8)
21233           case 9:  // result = lea base(cond, cond*8)
21234             isFastMultiplier = true;
21235             break;
21236           }
21237         }
21238
21239         if (isFastMultiplier) {
21240           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21241           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21242                              DAG.getConstant(CC, MVT::i8), Cond);
21243           // Zero extend the condition if needed.
21244           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21245                              Cond);
21246           // Scale the condition by the difference.
21247           if (Diff != 1)
21248             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21249                                DAG.getConstant(Diff, Cond.getValueType()));
21250
21251           // Add the base if non-zero.
21252           if (FalseC->getAPIntValue() != 0)
21253             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21254                                SDValue(FalseC, 0));
21255           if (N->getNumValues() == 2)  // Dead flag value?
21256             return DCI.CombineTo(N, Cond, SDValue());
21257           return Cond;
21258         }
21259       }
21260     }
21261   }
21262
21263   // Handle these cases:
21264   //   (select (x != c), e, c) -> select (x != c), e, x),
21265   //   (select (x == c), c, e) -> select (x == c), x, e)
21266   // where the c is an integer constant, and the "select" is the combination
21267   // of CMOV and CMP.
21268   //
21269   // The rationale for this change is that the conditional-move from a constant
21270   // needs two instructions, however, conditional-move from a register needs
21271   // only one instruction.
21272   //
21273   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21274   //  some instruction-combining opportunities. This opt needs to be
21275   //  postponed as late as possible.
21276   //
21277   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21278     // the DCI.xxxx conditions are provided to postpone the optimization as
21279     // late as possible.
21280
21281     ConstantSDNode *CmpAgainst = nullptr;
21282     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21283         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21284         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21285
21286       if (CC == X86::COND_NE &&
21287           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21288         CC = X86::GetOppositeBranchCondition(CC);
21289         std::swap(TrueOp, FalseOp);
21290       }
21291
21292       if (CC == X86::COND_E &&
21293           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21294         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21295                           DAG.getConstant(CC, MVT::i8), Cond };
21296         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21297       }
21298     }
21299   }
21300
21301   return SDValue();
21302 }
21303
21304 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21305                                                 const X86Subtarget *Subtarget) {
21306   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21307   switch (IntNo) {
21308   default: return SDValue();
21309   // SSE/AVX/AVX2 blend intrinsics.
21310   case Intrinsic::x86_avx2_pblendvb:
21311   case Intrinsic::x86_avx2_pblendw:
21312   case Intrinsic::x86_avx2_pblendd_128:
21313   case Intrinsic::x86_avx2_pblendd_256:
21314     // Don't try to simplify this intrinsic if we don't have AVX2.
21315     if (!Subtarget->hasAVX2())
21316       return SDValue();
21317     // FALL-THROUGH
21318   case Intrinsic::x86_avx_blend_pd_256:
21319   case Intrinsic::x86_avx_blend_ps_256:
21320   case Intrinsic::x86_avx_blendv_pd_256:
21321   case Intrinsic::x86_avx_blendv_ps_256:
21322     // Don't try to simplify this intrinsic if we don't have AVX.
21323     if (!Subtarget->hasAVX())
21324       return SDValue();
21325     // FALL-THROUGH
21326   case Intrinsic::x86_sse41_pblendw:
21327   case Intrinsic::x86_sse41_blendpd:
21328   case Intrinsic::x86_sse41_blendps:
21329   case Intrinsic::x86_sse41_blendvps:
21330   case Intrinsic::x86_sse41_blendvpd:
21331   case Intrinsic::x86_sse41_pblendvb: {
21332     SDValue Op0 = N->getOperand(1);
21333     SDValue Op1 = N->getOperand(2);
21334     SDValue Mask = N->getOperand(3);
21335
21336     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21337     if (!Subtarget->hasSSE41())
21338       return SDValue();
21339
21340     // fold (blend A, A, Mask) -> A
21341     if (Op0 == Op1)
21342       return Op0;
21343     // fold (blend A, B, allZeros) -> A
21344     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21345       return Op0;
21346     // fold (blend A, B, allOnes) -> B
21347     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21348       return Op1;
21349     
21350     // Simplify the case where the mask is a constant i32 value.
21351     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21352       if (C->isNullValue())
21353         return Op0;
21354       if (C->isAllOnesValue())
21355         return Op1;
21356     }
21357
21358     return SDValue();
21359   }
21360
21361   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21362   case Intrinsic::x86_sse2_psrai_w:
21363   case Intrinsic::x86_sse2_psrai_d:
21364   case Intrinsic::x86_avx2_psrai_w:
21365   case Intrinsic::x86_avx2_psrai_d:
21366   case Intrinsic::x86_sse2_psra_w:
21367   case Intrinsic::x86_sse2_psra_d:
21368   case Intrinsic::x86_avx2_psra_w:
21369   case Intrinsic::x86_avx2_psra_d: {
21370     SDValue Op0 = N->getOperand(1);
21371     SDValue Op1 = N->getOperand(2);
21372     EVT VT = Op0.getValueType();
21373     assert(VT.isVector() && "Expected a vector type!");
21374
21375     if (isa<BuildVectorSDNode>(Op1))
21376       Op1 = Op1.getOperand(0);
21377
21378     if (!isa<ConstantSDNode>(Op1))
21379       return SDValue();
21380
21381     EVT SVT = VT.getVectorElementType();
21382     unsigned SVTBits = SVT.getSizeInBits();
21383
21384     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21385     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21386     uint64_t ShAmt = C.getZExtValue();
21387
21388     // Don't try to convert this shift into a ISD::SRA if the shift
21389     // count is bigger than or equal to the element size.
21390     if (ShAmt >= SVTBits)
21391       return SDValue();
21392
21393     // Trivial case: if the shift count is zero, then fold this
21394     // into the first operand.
21395     if (ShAmt == 0)
21396       return Op0;
21397
21398     // Replace this packed shift intrinsic with a target independent
21399     // shift dag node.
21400     SDValue Splat = DAG.getConstant(C, VT);
21401     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21402   }
21403   }
21404 }
21405
21406 /// PerformMulCombine - Optimize a single multiply with constant into two
21407 /// in order to implement it with two cheaper instructions, e.g.
21408 /// LEA + SHL, LEA + LEA.
21409 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21410                                  TargetLowering::DAGCombinerInfo &DCI) {
21411   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21412     return SDValue();
21413
21414   EVT VT = N->getValueType(0);
21415   if (VT != MVT::i64)
21416     return SDValue();
21417
21418   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21419   if (!C)
21420     return SDValue();
21421   uint64_t MulAmt = C->getZExtValue();
21422   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21423     return SDValue();
21424
21425   uint64_t MulAmt1 = 0;
21426   uint64_t MulAmt2 = 0;
21427   if ((MulAmt % 9) == 0) {
21428     MulAmt1 = 9;
21429     MulAmt2 = MulAmt / 9;
21430   } else if ((MulAmt % 5) == 0) {
21431     MulAmt1 = 5;
21432     MulAmt2 = MulAmt / 5;
21433   } else if ((MulAmt % 3) == 0) {
21434     MulAmt1 = 3;
21435     MulAmt2 = MulAmt / 3;
21436   }
21437   if (MulAmt2 &&
21438       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21439     SDLoc DL(N);
21440
21441     if (isPowerOf2_64(MulAmt2) &&
21442         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21443       // If second multiplifer is pow2, issue it first. We want the multiply by
21444       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21445       // is an add.
21446       std::swap(MulAmt1, MulAmt2);
21447
21448     SDValue NewMul;
21449     if (isPowerOf2_64(MulAmt1))
21450       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21451                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21452     else
21453       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21454                            DAG.getConstant(MulAmt1, VT));
21455
21456     if (isPowerOf2_64(MulAmt2))
21457       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21458                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21459     else
21460       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21461                            DAG.getConstant(MulAmt2, VT));
21462
21463     // Do not add new nodes to DAG combiner worklist.
21464     DCI.CombineTo(N, NewMul, false);
21465   }
21466   return SDValue();
21467 }
21468
21469 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21470   SDValue N0 = N->getOperand(0);
21471   SDValue N1 = N->getOperand(1);
21472   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21473   EVT VT = N0.getValueType();
21474
21475   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21476   // since the result of setcc_c is all zero's or all ones.
21477   if (VT.isInteger() && !VT.isVector() &&
21478       N1C && N0.getOpcode() == ISD::AND &&
21479       N0.getOperand(1).getOpcode() == ISD::Constant) {
21480     SDValue N00 = N0.getOperand(0);
21481     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21482         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21483           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21484          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21485       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21486       APInt ShAmt = N1C->getAPIntValue();
21487       Mask = Mask.shl(ShAmt);
21488       if (Mask != 0)
21489         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21490                            N00, DAG.getConstant(Mask, VT));
21491     }
21492   }
21493
21494   // Hardware support for vector shifts is sparse which makes us scalarize the
21495   // vector operations in many cases. Also, on sandybridge ADD is faster than
21496   // shl.
21497   // (shl V, 1) -> add V,V
21498   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21499     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21500       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21501       // We shift all of the values by one. In many cases we do not have
21502       // hardware support for this operation. This is better expressed as an ADD
21503       // of two values.
21504       if (N1SplatC->getZExtValue() == 1)
21505         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21506     }
21507
21508   return SDValue();
21509 }
21510
21511 /// \brief Returns a vector of 0s if the node in input is a vector logical
21512 /// shift by a constant amount which is known to be bigger than or equal
21513 /// to the vector element size in bits.
21514 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21515                                       const X86Subtarget *Subtarget) {
21516   EVT VT = N->getValueType(0);
21517
21518   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21519       (!Subtarget->hasInt256() ||
21520        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21521     return SDValue();
21522
21523   SDValue Amt = N->getOperand(1);
21524   SDLoc DL(N);
21525   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21526     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21527       APInt ShiftAmt = AmtSplat->getAPIntValue();
21528       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21529
21530       // SSE2/AVX2 logical shifts always return a vector of 0s
21531       // if the shift amount is bigger than or equal to
21532       // the element size. The constant shift amount will be
21533       // encoded as a 8-bit immediate.
21534       if (ShiftAmt.trunc(8).uge(MaxAmount))
21535         return getZeroVector(VT, Subtarget, DAG, DL);
21536     }
21537
21538   return SDValue();
21539 }
21540
21541 /// PerformShiftCombine - Combine shifts.
21542 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21543                                    TargetLowering::DAGCombinerInfo &DCI,
21544                                    const X86Subtarget *Subtarget) {
21545   if (N->getOpcode() == ISD::SHL) {
21546     SDValue V = PerformSHLCombine(N, DAG);
21547     if (V.getNode()) return V;
21548   }
21549
21550   if (N->getOpcode() != ISD::SRA) {
21551     // Try to fold this logical shift into a zero vector.
21552     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21553     if (V.getNode()) return V;
21554   }
21555
21556   return SDValue();
21557 }
21558
21559 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21560 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21561 // and friends.  Likewise for OR -> CMPNEQSS.
21562 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21563                             TargetLowering::DAGCombinerInfo &DCI,
21564                             const X86Subtarget *Subtarget) {
21565   unsigned opcode;
21566
21567   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21568   // we're requiring SSE2 for both.
21569   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21570     SDValue N0 = N->getOperand(0);
21571     SDValue N1 = N->getOperand(1);
21572     SDValue CMP0 = N0->getOperand(1);
21573     SDValue CMP1 = N1->getOperand(1);
21574     SDLoc DL(N);
21575
21576     // The SETCCs should both refer to the same CMP.
21577     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21578       return SDValue();
21579
21580     SDValue CMP00 = CMP0->getOperand(0);
21581     SDValue CMP01 = CMP0->getOperand(1);
21582     EVT     VT    = CMP00.getValueType();
21583
21584     if (VT == MVT::f32 || VT == MVT::f64) {
21585       bool ExpectingFlags = false;
21586       // Check for any users that want flags:
21587       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21588            !ExpectingFlags && UI != UE; ++UI)
21589         switch (UI->getOpcode()) {
21590         default:
21591         case ISD::BR_CC:
21592         case ISD::BRCOND:
21593         case ISD::SELECT:
21594           ExpectingFlags = true;
21595           break;
21596         case ISD::CopyToReg:
21597         case ISD::SIGN_EXTEND:
21598         case ISD::ZERO_EXTEND:
21599         case ISD::ANY_EXTEND:
21600           break;
21601         }
21602
21603       if (!ExpectingFlags) {
21604         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21605         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21606
21607         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21608           X86::CondCode tmp = cc0;
21609           cc0 = cc1;
21610           cc1 = tmp;
21611         }
21612
21613         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21614             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21615           // FIXME: need symbolic constants for these magic numbers.
21616           // See X86ATTInstPrinter.cpp:printSSECC().
21617           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21618           if (Subtarget->hasAVX512()) {
21619             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21620                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21621             if (N->getValueType(0) != MVT::i1)
21622               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21623                                  FSetCC);
21624             return FSetCC;
21625           }
21626           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21627                                               CMP00.getValueType(), CMP00, CMP01,
21628                                               DAG.getConstant(x86cc, MVT::i8));
21629
21630           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21631           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21632
21633           if (is64BitFP && !Subtarget->is64Bit()) {
21634             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21635             // 64-bit integer, since that's not a legal type. Since
21636             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21637             // bits, but can do this little dance to extract the lowest 32 bits
21638             // and work with those going forward.
21639             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21640                                            OnesOrZeroesF);
21641             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21642                                            Vector64);
21643             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21644                                         Vector32, DAG.getIntPtrConstant(0));
21645             IntVT = MVT::i32;
21646           }
21647
21648           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21649           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21650                                       DAG.getConstant(1, IntVT));
21651           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21652           return OneBitOfTruth;
21653         }
21654       }
21655     }
21656   }
21657   return SDValue();
21658 }
21659
21660 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21661 /// so it can be folded inside ANDNP.
21662 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21663   EVT VT = N->getValueType(0);
21664
21665   // Match direct AllOnes for 128 and 256-bit vectors
21666   if (ISD::isBuildVectorAllOnes(N))
21667     return true;
21668
21669   // Look through a bit convert.
21670   if (N->getOpcode() == ISD::BITCAST)
21671     N = N->getOperand(0).getNode();
21672
21673   // Sometimes the operand may come from a insert_subvector building a 256-bit
21674   // allones vector
21675   if (VT.is256BitVector() &&
21676       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21677     SDValue V1 = N->getOperand(0);
21678     SDValue V2 = N->getOperand(1);
21679
21680     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21681         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21682         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21683         ISD::isBuildVectorAllOnes(V2.getNode()))
21684       return true;
21685   }
21686
21687   return false;
21688 }
21689
21690 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21691 // register. In most cases we actually compare or select YMM-sized registers
21692 // and mixing the two types creates horrible code. This method optimizes
21693 // some of the transition sequences.
21694 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21695                                  TargetLowering::DAGCombinerInfo &DCI,
21696                                  const X86Subtarget *Subtarget) {
21697   EVT VT = N->getValueType(0);
21698   if (!VT.is256BitVector())
21699     return SDValue();
21700
21701   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21702           N->getOpcode() == ISD::ZERO_EXTEND ||
21703           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21704
21705   SDValue Narrow = N->getOperand(0);
21706   EVT NarrowVT = Narrow->getValueType(0);
21707   if (!NarrowVT.is128BitVector())
21708     return SDValue();
21709
21710   if (Narrow->getOpcode() != ISD::XOR &&
21711       Narrow->getOpcode() != ISD::AND &&
21712       Narrow->getOpcode() != ISD::OR)
21713     return SDValue();
21714
21715   SDValue N0  = Narrow->getOperand(0);
21716   SDValue N1  = Narrow->getOperand(1);
21717   SDLoc DL(Narrow);
21718
21719   // The Left side has to be a trunc.
21720   if (N0.getOpcode() != ISD::TRUNCATE)
21721     return SDValue();
21722
21723   // The type of the truncated inputs.
21724   EVT WideVT = N0->getOperand(0)->getValueType(0);
21725   if (WideVT != VT)
21726     return SDValue();
21727
21728   // The right side has to be a 'trunc' or a constant vector.
21729   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21730   ConstantSDNode *RHSConstSplat = nullptr;
21731   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21732     RHSConstSplat = RHSBV->getConstantSplatNode();
21733   if (!RHSTrunc && !RHSConstSplat)
21734     return SDValue();
21735
21736   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21737
21738   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21739     return SDValue();
21740
21741   // Set N0 and N1 to hold the inputs to the new wide operation.
21742   N0 = N0->getOperand(0);
21743   if (RHSConstSplat) {
21744     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21745                      SDValue(RHSConstSplat, 0));
21746     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21747     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21748   } else if (RHSTrunc) {
21749     N1 = N1->getOperand(0);
21750   }
21751
21752   // Generate the wide operation.
21753   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21754   unsigned Opcode = N->getOpcode();
21755   switch (Opcode) {
21756   case ISD::ANY_EXTEND:
21757     return Op;
21758   case ISD::ZERO_EXTEND: {
21759     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21760     APInt Mask = APInt::getAllOnesValue(InBits);
21761     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21762     return DAG.getNode(ISD::AND, DL, VT,
21763                        Op, DAG.getConstant(Mask, VT));
21764   }
21765   case ISD::SIGN_EXTEND:
21766     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21767                        Op, DAG.getValueType(NarrowVT));
21768   default:
21769     llvm_unreachable("Unexpected opcode");
21770   }
21771 }
21772
21773 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21774                                  TargetLowering::DAGCombinerInfo &DCI,
21775                                  const X86Subtarget *Subtarget) {
21776   EVT VT = N->getValueType(0);
21777   if (DCI.isBeforeLegalizeOps())
21778     return SDValue();
21779
21780   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21781   if (R.getNode())
21782     return R;
21783
21784   // Create BEXTR instructions
21785   // BEXTR is ((X >> imm) & (2**size-1))
21786   if (VT == MVT::i32 || VT == MVT::i64) {
21787     SDValue N0 = N->getOperand(0);
21788     SDValue N1 = N->getOperand(1);
21789     SDLoc DL(N);
21790
21791     // Check for BEXTR.
21792     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21793         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21794       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21795       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21796       if (MaskNode && ShiftNode) {
21797         uint64_t Mask = MaskNode->getZExtValue();
21798         uint64_t Shift = ShiftNode->getZExtValue();
21799         if (isMask_64(Mask)) {
21800           uint64_t MaskSize = CountPopulation_64(Mask);
21801           if (Shift + MaskSize <= VT.getSizeInBits())
21802             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21803                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21804         }
21805       }
21806     } // BEXTR
21807
21808     return SDValue();
21809   }
21810
21811   // Want to form ANDNP nodes:
21812   // 1) In the hopes of then easily combining them with OR and AND nodes
21813   //    to form PBLEND/PSIGN.
21814   // 2) To match ANDN packed intrinsics
21815   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21816     return SDValue();
21817
21818   SDValue N0 = N->getOperand(0);
21819   SDValue N1 = N->getOperand(1);
21820   SDLoc DL(N);
21821
21822   // Check LHS for vnot
21823   if (N0.getOpcode() == ISD::XOR &&
21824       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21825       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21826     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21827
21828   // Check RHS for vnot
21829   if (N1.getOpcode() == ISD::XOR &&
21830       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21831       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21832     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21833
21834   return SDValue();
21835 }
21836
21837 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21838                                 TargetLowering::DAGCombinerInfo &DCI,
21839                                 const X86Subtarget *Subtarget) {
21840   if (DCI.isBeforeLegalizeOps())
21841     return SDValue();
21842
21843   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21844   if (R.getNode())
21845     return R;
21846
21847   SDValue N0 = N->getOperand(0);
21848   SDValue N1 = N->getOperand(1);
21849   EVT VT = N->getValueType(0);
21850
21851   // look for psign/blend
21852   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21853     if (!Subtarget->hasSSSE3() ||
21854         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21855       return SDValue();
21856
21857     // Canonicalize pandn to RHS
21858     if (N0.getOpcode() == X86ISD::ANDNP)
21859       std::swap(N0, N1);
21860     // or (and (m, y), (pandn m, x))
21861     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21862       SDValue Mask = N1.getOperand(0);
21863       SDValue X    = N1.getOperand(1);
21864       SDValue Y;
21865       if (N0.getOperand(0) == Mask)
21866         Y = N0.getOperand(1);
21867       if (N0.getOperand(1) == Mask)
21868         Y = N0.getOperand(0);
21869
21870       // Check to see if the mask appeared in both the AND and ANDNP and
21871       if (!Y.getNode())
21872         return SDValue();
21873
21874       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21875       // Look through mask bitcast.
21876       if (Mask.getOpcode() == ISD::BITCAST)
21877         Mask = Mask.getOperand(0);
21878       if (X.getOpcode() == ISD::BITCAST)
21879         X = X.getOperand(0);
21880       if (Y.getOpcode() == ISD::BITCAST)
21881         Y = Y.getOperand(0);
21882
21883       EVT MaskVT = Mask.getValueType();
21884
21885       // Validate that the Mask operand is a vector sra node.
21886       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21887       // there is no psrai.b
21888       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21889       unsigned SraAmt = ~0;
21890       if (Mask.getOpcode() == ISD::SRA) {
21891         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21892           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21893             SraAmt = AmtConst->getZExtValue();
21894       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21895         SDValue SraC = Mask.getOperand(1);
21896         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21897       }
21898       if ((SraAmt + 1) != EltBits)
21899         return SDValue();
21900
21901       SDLoc DL(N);
21902
21903       // Now we know we at least have a plendvb with the mask val.  See if
21904       // we can form a psignb/w/d.
21905       // psign = x.type == y.type == mask.type && y = sub(0, x);
21906       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21907           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21908           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21909         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21910                "Unsupported VT for PSIGN");
21911         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21912         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21913       }
21914       // PBLENDVB only available on SSE 4.1
21915       if (!Subtarget->hasSSE41())
21916         return SDValue();
21917
21918       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21919
21920       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21921       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21922       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21923       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21924       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21925     }
21926   }
21927
21928   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21929     return SDValue();
21930
21931   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21932   MachineFunction &MF = DAG.getMachineFunction();
21933   bool OptForSize = MF.getFunction()->getAttributes().
21934     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21935
21936   // SHLD/SHRD instructions have lower register pressure, but on some
21937   // platforms they have higher latency than the equivalent
21938   // series of shifts/or that would otherwise be generated.
21939   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21940   // have higher latencies and we are not optimizing for size.
21941   if (!OptForSize && Subtarget->isSHLDSlow())
21942     return SDValue();
21943
21944   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21945     std::swap(N0, N1);
21946   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21947     return SDValue();
21948   if (!N0.hasOneUse() || !N1.hasOneUse())
21949     return SDValue();
21950
21951   SDValue ShAmt0 = N0.getOperand(1);
21952   if (ShAmt0.getValueType() != MVT::i8)
21953     return SDValue();
21954   SDValue ShAmt1 = N1.getOperand(1);
21955   if (ShAmt1.getValueType() != MVT::i8)
21956     return SDValue();
21957   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21958     ShAmt0 = ShAmt0.getOperand(0);
21959   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21960     ShAmt1 = ShAmt1.getOperand(0);
21961
21962   SDLoc DL(N);
21963   unsigned Opc = X86ISD::SHLD;
21964   SDValue Op0 = N0.getOperand(0);
21965   SDValue Op1 = N1.getOperand(0);
21966   if (ShAmt0.getOpcode() == ISD::SUB) {
21967     Opc = X86ISD::SHRD;
21968     std::swap(Op0, Op1);
21969     std::swap(ShAmt0, ShAmt1);
21970   }
21971
21972   unsigned Bits = VT.getSizeInBits();
21973   if (ShAmt1.getOpcode() == ISD::SUB) {
21974     SDValue Sum = ShAmt1.getOperand(0);
21975     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21976       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21977       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21978         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21979       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21980         return DAG.getNode(Opc, DL, VT,
21981                            Op0, Op1,
21982                            DAG.getNode(ISD::TRUNCATE, DL,
21983                                        MVT::i8, ShAmt0));
21984     }
21985   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21986     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21987     if (ShAmt0C &&
21988         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21989       return DAG.getNode(Opc, DL, VT,
21990                          N0.getOperand(0), N1.getOperand(0),
21991                          DAG.getNode(ISD::TRUNCATE, DL,
21992                                        MVT::i8, ShAmt0));
21993   }
21994
21995   return SDValue();
21996 }
21997
21998 // Generate NEG and CMOV for integer abs.
21999 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22000   EVT VT = N->getValueType(0);
22001
22002   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22003   // 8-bit integer abs to NEG and CMOV.
22004   if (VT.isInteger() && VT.getSizeInBits() == 8)
22005     return SDValue();
22006
22007   SDValue N0 = N->getOperand(0);
22008   SDValue N1 = N->getOperand(1);
22009   SDLoc DL(N);
22010
22011   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22012   // and change it to SUB and CMOV.
22013   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22014       N0.getOpcode() == ISD::ADD &&
22015       N0.getOperand(1) == N1 &&
22016       N1.getOpcode() == ISD::SRA &&
22017       N1.getOperand(0) == N0.getOperand(0))
22018     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22019       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22020         // Generate SUB & CMOV.
22021         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22022                                   DAG.getConstant(0, VT), N0.getOperand(0));
22023
22024         SDValue Ops[] = { N0.getOperand(0), Neg,
22025                           DAG.getConstant(X86::COND_GE, MVT::i8),
22026                           SDValue(Neg.getNode(), 1) };
22027         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22028       }
22029   return SDValue();
22030 }
22031
22032 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22033 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22034                                  TargetLowering::DAGCombinerInfo &DCI,
22035                                  const X86Subtarget *Subtarget) {
22036   if (DCI.isBeforeLegalizeOps())
22037     return SDValue();
22038
22039   if (Subtarget->hasCMov()) {
22040     SDValue RV = performIntegerAbsCombine(N, DAG);
22041     if (RV.getNode())
22042       return RV;
22043   }
22044
22045   return SDValue();
22046 }
22047
22048 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22049 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22050                                   TargetLowering::DAGCombinerInfo &DCI,
22051                                   const X86Subtarget *Subtarget) {
22052   LoadSDNode *Ld = cast<LoadSDNode>(N);
22053   EVT RegVT = Ld->getValueType(0);
22054   EVT MemVT = Ld->getMemoryVT();
22055   SDLoc dl(Ld);
22056   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22057
22058   // On Sandybridge unaligned 256bit loads are inefficient.
22059   ISD::LoadExtType Ext = Ld->getExtensionType();
22060   unsigned Alignment = Ld->getAlignment();
22061   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22062   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
22063       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22064     unsigned NumElems = RegVT.getVectorNumElements();
22065     if (NumElems < 2)
22066       return SDValue();
22067
22068     SDValue Ptr = Ld->getBasePtr();
22069     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22070
22071     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22072                                   NumElems/2);
22073     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22074                                 Ld->getPointerInfo(), Ld->isVolatile(),
22075                                 Ld->isNonTemporal(), Ld->isInvariant(),
22076                                 Alignment);
22077     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22078     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22079                                 Ld->getPointerInfo(), Ld->isVolatile(),
22080                                 Ld->isNonTemporal(), Ld->isInvariant(),
22081                                 std::min(16U, Alignment));
22082     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22083                              Load1.getValue(1),
22084                              Load2.getValue(1));
22085
22086     SDValue NewVec = DAG.getUNDEF(RegVT);
22087     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22088     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22089     return DCI.CombineTo(N, NewVec, TF, true);
22090   }
22091
22092   return SDValue();
22093 }
22094
22095 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22096 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22097                                    const X86Subtarget *Subtarget) {
22098   StoreSDNode *St = cast<StoreSDNode>(N);
22099   EVT VT = St->getValue().getValueType();
22100   EVT StVT = St->getMemoryVT();
22101   SDLoc dl(St);
22102   SDValue StoredVal = St->getOperand(1);
22103   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22104
22105   // If we are saving a concatenation of two XMM registers, perform two stores.
22106   // On Sandy Bridge, 256-bit memory operations are executed by two
22107   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
22108   // memory  operation.
22109   unsigned Alignment = St->getAlignment();
22110   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22111   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
22112       StVT == VT && !IsAligned) {
22113     unsigned NumElems = VT.getVectorNumElements();
22114     if (NumElems < 2)
22115       return SDValue();
22116
22117     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22118     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22119
22120     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22121     SDValue Ptr0 = St->getBasePtr();
22122     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22123
22124     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22125                                 St->getPointerInfo(), St->isVolatile(),
22126                                 St->isNonTemporal(), Alignment);
22127     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22128                                 St->getPointerInfo(), St->isVolatile(),
22129                                 St->isNonTemporal(),
22130                                 std::min(16U, Alignment));
22131     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22132   }
22133
22134   // Optimize trunc store (of multiple scalars) to shuffle and store.
22135   // First, pack all of the elements in one place. Next, store to memory
22136   // in fewer chunks.
22137   if (St->isTruncatingStore() && VT.isVector()) {
22138     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22139     unsigned NumElems = VT.getVectorNumElements();
22140     assert(StVT != VT && "Cannot truncate to the same type");
22141     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22142     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22143
22144     // From, To sizes and ElemCount must be pow of two
22145     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22146     // We are going to use the original vector elt for storing.
22147     // Accumulated smaller vector elements must be a multiple of the store size.
22148     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22149
22150     unsigned SizeRatio  = FromSz / ToSz;
22151
22152     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22153
22154     // Create a type on which we perform the shuffle
22155     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22156             StVT.getScalarType(), NumElems*SizeRatio);
22157
22158     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22159
22160     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22161     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22162     for (unsigned i = 0; i != NumElems; ++i)
22163       ShuffleVec[i] = i * SizeRatio;
22164
22165     // Can't shuffle using an illegal type.
22166     if (!TLI.isTypeLegal(WideVecVT))
22167       return SDValue();
22168
22169     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22170                                          DAG.getUNDEF(WideVecVT),
22171                                          &ShuffleVec[0]);
22172     // At this point all of the data is stored at the bottom of the
22173     // register. We now need to save it to mem.
22174
22175     // Find the largest store unit
22176     MVT StoreType = MVT::i8;
22177     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
22178          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
22179       MVT Tp = (MVT::SimpleValueType)tp;
22180       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22181         StoreType = Tp;
22182     }
22183
22184     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22185     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22186         (64 <= NumElems * ToSz))
22187       StoreType = MVT::f64;
22188
22189     // Bitcast the original vector into a vector of store-size units
22190     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22191             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22192     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22193     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22194     SmallVector<SDValue, 8> Chains;
22195     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22196                                         TLI.getPointerTy());
22197     SDValue Ptr = St->getBasePtr();
22198
22199     // Perform one or more big stores into memory.
22200     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22201       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22202                                    StoreType, ShuffWide,
22203                                    DAG.getIntPtrConstant(i));
22204       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22205                                 St->getPointerInfo(), St->isVolatile(),
22206                                 St->isNonTemporal(), St->getAlignment());
22207       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22208       Chains.push_back(Ch);
22209     }
22210
22211     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22212   }
22213
22214   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
22215   // the FP state in cases where an emms may be missing.
22216   // A preferable solution to the general problem is to figure out the right
22217   // places to insert EMMS.  This qualifies as a quick hack.
22218
22219   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22220   if (VT.getSizeInBits() != 64)
22221     return SDValue();
22222
22223   const Function *F = DAG.getMachineFunction().getFunction();
22224   bool NoImplicitFloatOps = F->getAttributes().
22225     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
22226   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22227                      && Subtarget->hasSSE2();
22228   if ((VT.isVector() ||
22229        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22230       isa<LoadSDNode>(St->getValue()) &&
22231       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22232       St->getChain().hasOneUse() && !St->isVolatile()) {
22233     SDNode* LdVal = St->getValue().getNode();
22234     LoadSDNode *Ld = nullptr;
22235     int TokenFactorIndex = -1;
22236     SmallVector<SDValue, 8> Ops;
22237     SDNode* ChainVal = St->getChain().getNode();
22238     // Must be a store of a load.  We currently handle two cases:  the load
22239     // is a direct child, and it's under an intervening TokenFactor.  It is
22240     // possible to dig deeper under nested TokenFactors.
22241     if (ChainVal == LdVal)
22242       Ld = cast<LoadSDNode>(St->getChain());
22243     else if (St->getValue().hasOneUse() &&
22244              ChainVal->getOpcode() == ISD::TokenFactor) {
22245       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22246         if (ChainVal->getOperand(i).getNode() == LdVal) {
22247           TokenFactorIndex = i;
22248           Ld = cast<LoadSDNode>(St->getValue());
22249         } else
22250           Ops.push_back(ChainVal->getOperand(i));
22251       }
22252     }
22253
22254     if (!Ld || !ISD::isNormalLoad(Ld))
22255       return SDValue();
22256
22257     // If this is not the MMX case, i.e. we are just turning i64 load/store
22258     // into f64 load/store, avoid the transformation if there are multiple
22259     // uses of the loaded value.
22260     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22261       return SDValue();
22262
22263     SDLoc LdDL(Ld);
22264     SDLoc StDL(N);
22265     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22266     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22267     // pair instead.
22268     if (Subtarget->is64Bit() || F64IsLegal) {
22269       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22270       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22271                                   Ld->getPointerInfo(), Ld->isVolatile(),
22272                                   Ld->isNonTemporal(), Ld->isInvariant(),
22273                                   Ld->getAlignment());
22274       SDValue NewChain = NewLd.getValue(1);
22275       if (TokenFactorIndex != -1) {
22276         Ops.push_back(NewChain);
22277         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22278       }
22279       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22280                           St->getPointerInfo(),
22281                           St->isVolatile(), St->isNonTemporal(),
22282                           St->getAlignment());
22283     }
22284
22285     // Otherwise, lower to two pairs of 32-bit loads / stores.
22286     SDValue LoAddr = Ld->getBasePtr();
22287     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22288                                  DAG.getConstant(4, MVT::i32));
22289
22290     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22291                                Ld->getPointerInfo(),
22292                                Ld->isVolatile(), Ld->isNonTemporal(),
22293                                Ld->isInvariant(), Ld->getAlignment());
22294     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22295                                Ld->getPointerInfo().getWithOffset(4),
22296                                Ld->isVolatile(), Ld->isNonTemporal(),
22297                                Ld->isInvariant(),
22298                                MinAlign(Ld->getAlignment(), 4));
22299
22300     SDValue NewChain = LoLd.getValue(1);
22301     if (TokenFactorIndex != -1) {
22302       Ops.push_back(LoLd);
22303       Ops.push_back(HiLd);
22304       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22305     }
22306
22307     LoAddr = St->getBasePtr();
22308     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22309                          DAG.getConstant(4, MVT::i32));
22310
22311     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22312                                 St->getPointerInfo(),
22313                                 St->isVolatile(), St->isNonTemporal(),
22314                                 St->getAlignment());
22315     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22316                                 St->getPointerInfo().getWithOffset(4),
22317                                 St->isVolatile(),
22318                                 St->isNonTemporal(),
22319                                 MinAlign(St->getAlignment(), 4));
22320     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22321   }
22322   return SDValue();
22323 }
22324
22325 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
22326 /// and return the operands for the horizontal operation in LHS and RHS.  A
22327 /// horizontal operation performs the binary operation on successive elements
22328 /// of its first operand, then on successive elements of its second operand,
22329 /// returning the resulting values in a vector.  For example, if
22330 ///   A = < float a0, float a1, float a2, float a3 >
22331 /// and
22332 ///   B = < float b0, float b1, float b2, float b3 >
22333 /// then the result of doing a horizontal operation on A and B is
22334 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22335 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22336 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22337 /// set to A, RHS to B, and the routine returns 'true'.
22338 /// Note that the binary operation should have the property that if one of the
22339 /// operands is UNDEF then the result is UNDEF.
22340 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22341   // Look for the following pattern: if
22342   //   A = < float a0, float a1, float a2, float a3 >
22343   //   B = < float b0, float b1, float b2, float b3 >
22344   // and
22345   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22346   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22347   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22348   // which is A horizontal-op B.
22349
22350   // At least one of the operands should be a vector shuffle.
22351   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22352       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22353     return false;
22354
22355   MVT VT = LHS.getSimpleValueType();
22356
22357   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22358          "Unsupported vector type for horizontal add/sub");
22359
22360   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22361   // operate independently on 128-bit lanes.
22362   unsigned NumElts = VT.getVectorNumElements();
22363   unsigned NumLanes = VT.getSizeInBits()/128;
22364   unsigned NumLaneElts = NumElts / NumLanes;
22365   assert((NumLaneElts % 2 == 0) &&
22366          "Vector type should have an even number of elements in each lane");
22367   unsigned HalfLaneElts = NumLaneElts/2;
22368
22369   // View LHS in the form
22370   //   LHS = VECTOR_SHUFFLE A, B, LMask
22371   // If LHS is not a shuffle then pretend it is the shuffle
22372   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22373   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22374   // type VT.
22375   SDValue A, B;
22376   SmallVector<int, 16> LMask(NumElts);
22377   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22378     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22379       A = LHS.getOperand(0);
22380     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22381       B = LHS.getOperand(1);
22382     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22383     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22384   } else {
22385     if (LHS.getOpcode() != ISD::UNDEF)
22386       A = LHS;
22387     for (unsigned i = 0; i != NumElts; ++i)
22388       LMask[i] = i;
22389   }
22390
22391   // Likewise, view RHS in the form
22392   //   RHS = VECTOR_SHUFFLE C, D, RMask
22393   SDValue C, D;
22394   SmallVector<int, 16> RMask(NumElts);
22395   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22396     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22397       C = RHS.getOperand(0);
22398     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22399       D = RHS.getOperand(1);
22400     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22401     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22402   } else {
22403     if (RHS.getOpcode() != ISD::UNDEF)
22404       C = RHS;
22405     for (unsigned i = 0; i != NumElts; ++i)
22406       RMask[i] = i;
22407   }
22408
22409   // Check that the shuffles are both shuffling the same vectors.
22410   if (!(A == C && B == D) && !(A == D && B == C))
22411     return false;
22412
22413   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22414   if (!A.getNode() && !B.getNode())
22415     return false;
22416
22417   // If A and B occur in reverse order in RHS, then "swap" them (which means
22418   // rewriting the mask).
22419   if (A != C)
22420     CommuteVectorShuffleMask(RMask, NumElts);
22421
22422   // At this point LHS and RHS are equivalent to
22423   //   LHS = VECTOR_SHUFFLE A, B, LMask
22424   //   RHS = VECTOR_SHUFFLE A, B, RMask
22425   // Check that the masks correspond to performing a horizontal operation.
22426   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22427     for (unsigned i = 0; i != NumLaneElts; ++i) {
22428       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22429
22430       // Ignore any UNDEF components.
22431       if (LIdx < 0 || RIdx < 0 ||
22432           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22433           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22434         continue;
22435
22436       // Check that successive elements are being operated on.  If not, this is
22437       // not a horizontal operation.
22438       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22439       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22440       if (!(LIdx == Index && RIdx == Index + 1) &&
22441           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22442         return false;
22443     }
22444   }
22445
22446   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22447   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22448   return true;
22449 }
22450
22451 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22452 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22453                                   const X86Subtarget *Subtarget) {
22454   EVT VT = N->getValueType(0);
22455   SDValue LHS = N->getOperand(0);
22456   SDValue RHS = N->getOperand(1);
22457
22458   // Try to synthesize horizontal adds from adds of shuffles.
22459   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22460        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22461       isHorizontalBinOp(LHS, RHS, true))
22462     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22463   return SDValue();
22464 }
22465
22466 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22467 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22468                                   const X86Subtarget *Subtarget) {
22469   EVT VT = N->getValueType(0);
22470   SDValue LHS = N->getOperand(0);
22471   SDValue RHS = N->getOperand(1);
22472
22473   // Try to synthesize horizontal subs from subs of shuffles.
22474   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22475        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22476       isHorizontalBinOp(LHS, RHS, false))
22477     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22478   return SDValue();
22479 }
22480
22481 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22482 /// X86ISD::FXOR nodes.
22483 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22484   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22485   // F[X]OR(0.0, x) -> x
22486   // F[X]OR(x, 0.0) -> x
22487   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22488     if (C->getValueAPF().isPosZero())
22489       return N->getOperand(1);
22490   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22491     if (C->getValueAPF().isPosZero())
22492       return N->getOperand(0);
22493   return SDValue();
22494 }
22495
22496 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22497 /// X86ISD::FMAX nodes.
22498 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22499   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22500
22501   // Only perform optimizations if UnsafeMath is used.
22502   if (!DAG.getTarget().Options.UnsafeFPMath)
22503     return SDValue();
22504
22505   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22506   // into FMINC and FMAXC, which are Commutative operations.
22507   unsigned NewOp = 0;
22508   switch (N->getOpcode()) {
22509     default: llvm_unreachable("unknown opcode");
22510     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22511     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22512   }
22513
22514   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22515                      N->getOperand(0), N->getOperand(1));
22516 }
22517
22518 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22519 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22520   // FAND(0.0, x) -> 0.0
22521   // FAND(x, 0.0) -> 0.0
22522   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22523     if (C->getValueAPF().isPosZero())
22524       return N->getOperand(0);
22525   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22526     if (C->getValueAPF().isPosZero())
22527       return N->getOperand(1);
22528   return SDValue();
22529 }
22530
22531 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22532 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22533   // FANDN(x, 0.0) -> 0.0
22534   // FANDN(0.0, x) -> x
22535   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22536     if (C->getValueAPF().isPosZero())
22537       return N->getOperand(1);
22538   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22539     if (C->getValueAPF().isPosZero())
22540       return N->getOperand(1);
22541   return SDValue();
22542 }
22543
22544 static SDValue PerformBTCombine(SDNode *N,
22545                                 SelectionDAG &DAG,
22546                                 TargetLowering::DAGCombinerInfo &DCI) {
22547   // BT ignores high bits in the bit index operand.
22548   SDValue Op1 = N->getOperand(1);
22549   if (Op1.hasOneUse()) {
22550     unsigned BitWidth = Op1.getValueSizeInBits();
22551     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22552     APInt KnownZero, KnownOne;
22553     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22554                                           !DCI.isBeforeLegalizeOps());
22555     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22556     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22557         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22558       DCI.CommitTargetLoweringOpt(TLO);
22559   }
22560   return SDValue();
22561 }
22562
22563 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22564   SDValue Op = N->getOperand(0);
22565   if (Op.getOpcode() == ISD::BITCAST)
22566     Op = Op.getOperand(0);
22567   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22568   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22569       VT.getVectorElementType().getSizeInBits() ==
22570       OpVT.getVectorElementType().getSizeInBits()) {
22571     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22572   }
22573   return SDValue();
22574 }
22575
22576 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22577                                                const X86Subtarget *Subtarget) {
22578   EVT VT = N->getValueType(0);
22579   if (!VT.isVector())
22580     return SDValue();
22581
22582   SDValue N0 = N->getOperand(0);
22583   SDValue N1 = N->getOperand(1);
22584   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22585   SDLoc dl(N);
22586
22587   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22588   // both SSE and AVX2 since there is no sign-extended shift right
22589   // operation on a vector with 64-bit elements.
22590   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22591   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22592   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22593       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22594     SDValue N00 = N0.getOperand(0);
22595
22596     // EXTLOAD has a better solution on AVX2,
22597     // it may be replaced with X86ISD::VSEXT node.
22598     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22599       if (!ISD::isNormalLoad(N00.getNode()))
22600         return SDValue();
22601
22602     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22603         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22604                                   N00, N1);
22605       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22606     }
22607   }
22608   return SDValue();
22609 }
22610
22611 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22612                                   TargetLowering::DAGCombinerInfo &DCI,
22613                                   const X86Subtarget *Subtarget) {
22614   if (!DCI.isBeforeLegalizeOps())
22615     return SDValue();
22616
22617   if (!Subtarget->hasFp256())
22618     return SDValue();
22619
22620   EVT VT = N->getValueType(0);
22621   if (VT.isVector() && VT.getSizeInBits() == 256) {
22622     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22623     if (R.getNode())
22624       return R;
22625   }
22626
22627   return SDValue();
22628 }
22629
22630 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22631                                  const X86Subtarget* Subtarget) {
22632   SDLoc dl(N);
22633   EVT VT = N->getValueType(0);
22634
22635   // Let legalize expand this if it isn't a legal type yet.
22636   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22637     return SDValue();
22638
22639   EVT ScalarVT = VT.getScalarType();
22640   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22641       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22642     return SDValue();
22643
22644   SDValue A = N->getOperand(0);
22645   SDValue B = N->getOperand(1);
22646   SDValue C = N->getOperand(2);
22647
22648   bool NegA = (A.getOpcode() == ISD::FNEG);
22649   bool NegB = (B.getOpcode() == ISD::FNEG);
22650   bool NegC = (C.getOpcode() == ISD::FNEG);
22651
22652   // Negative multiplication when NegA xor NegB
22653   bool NegMul = (NegA != NegB);
22654   if (NegA)
22655     A = A.getOperand(0);
22656   if (NegB)
22657     B = B.getOperand(0);
22658   if (NegC)
22659     C = C.getOperand(0);
22660
22661   unsigned Opcode;
22662   if (!NegMul)
22663     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22664   else
22665     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22666
22667   return DAG.getNode(Opcode, dl, VT, A, B, C);
22668 }
22669
22670 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22671                                   TargetLowering::DAGCombinerInfo &DCI,
22672                                   const X86Subtarget *Subtarget) {
22673   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22674   //           (and (i32 x86isd::setcc_carry), 1)
22675   // This eliminates the zext. This transformation is necessary because
22676   // ISD::SETCC is always legalized to i8.
22677   SDLoc dl(N);
22678   SDValue N0 = N->getOperand(0);
22679   EVT VT = N->getValueType(0);
22680
22681   if (N0.getOpcode() == ISD::AND &&
22682       N0.hasOneUse() &&
22683       N0.getOperand(0).hasOneUse()) {
22684     SDValue N00 = N0.getOperand(0);
22685     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22686       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22687       if (!C || C->getZExtValue() != 1)
22688         return SDValue();
22689       return DAG.getNode(ISD::AND, dl, VT,
22690                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22691                                      N00.getOperand(0), N00.getOperand(1)),
22692                          DAG.getConstant(1, VT));
22693     }
22694   }
22695
22696   if (N0.getOpcode() == ISD::TRUNCATE &&
22697       N0.hasOneUse() &&
22698       N0.getOperand(0).hasOneUse()) {
22699     SDValue N00 = N0.getOperand(0);
22700     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22701       return DAG.getNode(ISD::AND, dl, VT,
22702                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22703                                      N00.getOperand(0), N00.getOperand(1)),
22704                          DAG.getConstant(1, VT));
22705     }
22706   }
22707   if (VT.is256BitVector()) {
22708     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22709     if (R.getNode())
22710       return R;
22711   }
22712
22713   return SDValue();
22714 }
22715
22716 // Optimize x == -y --> x+y == 0
22717 //          x != -y --> x+y != 0
22718 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22719                                       const X86Subtarget* Subtarget) {
22720   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22721   SDValue LHS = N->getOperand(0);
22722   SDValue RHS = N->getOperand(1);
22723   EVT VT = N->getValueType(0);
22724   SDLoc DL(N);
22725
22726   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22727     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22728       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22729         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22730                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22731         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22732                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22733       }
22734   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22735     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22736       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22737         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22738                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22739         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22740                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22741       }
22742
22743   if (VT.getScalarType() == MVT::i1) {
22744     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22745       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22746     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22747     if (!IsSEXT0 && !IsVZero0)
22748       return SDValue();
22749     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22750       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22751     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22752
22753     if (!IsSEXT1 && !IsVZero1)
22754       return SDValue();
22755
22756     if (IsSEXT0 && IsVZero1) {
22757       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22758       if (CC == ISD::SETEQ)
22759         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22760       return LHS.getOperand(0);
22761     }
22762     if (IsSEXT1 && IsVZero0) {
22763       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22764       if (CC == ISD::SETEQ)
22765         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22766       return RHS.getOperand(0);
22767     }
22768   }
22769
22770   return SDValue();
22771 }
22772
22773 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22774                                       const X86Subtarget *Subtarget) {
22775   SDLoc dl(N);
22776   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22777   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22778          "X86insertps is only defined for v4x32");
22779
22780   SDValue Ld = N->getOperand(1);
22781   if (MayFoldLoad(Ld)) {
22782     // Extract the countS bits from the immediate so we can get the proper
22783     // address when narrowing the vector load to a specific element.
22784     // When the second source op is a memory address, interps doesn't use
22785     // countS and just gets an f32 from that address.
22786     unsigned DestIndex =
22787         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22788     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22789   } else
22790     return SDValue();
22791
22792   // Create this as a scalar to vector to match the instruction pattern.
22793   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22794   // countS bits are ignored when loading from memory on insertps, which
22795   // means we don't need to explicitly set them to 0.
22796   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22797                      LoadScalarToVector, N->getOperand(2));
22798 }
22799
22800 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22801 // as "sbb reg,reg", since it can be extended without zext and produces
22802 // an all-ones bit which is more useful than 0/1 in some cases.
22803 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22804                                MVT VT) {
22805   if (VT == MVT::i8)
22806     return DAG.getNode(ISD::AND, DL, VT,
22807                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22808                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22809                        DAG.getConstant(1, VT));
22810   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22811   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22812                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22813                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22814 }
22815
22816 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22817 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22818                                    TargetLowering::DAGCombinerInfo &DCI,
22819                                    const X86Subtarget *Subtarget) {
22820   SDLoc DL(N);
22821   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22822   SDValue EFLAGS = N->getOperand(1);
22823
22824   if (CC == X86::COND_A) {
22825     // Try to convert COND_A into COND_B in an attempt to facilitate
22826     // materializing "setb reg".
22827     //
22828     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22829     // cannot take an immediate as its first operand.
22830     //
22831     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22832         EFLAGS.getValueType().isInteger() &&
22833         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22834       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22835                                    EFLAGS.getNode()->getVTList(),
22836                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22837       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22838       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22839     }
22840   }
22841
22842   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22843   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22844   // cases.
22845   if (CC == X86::COND_B)
22846     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22847
22848   SDValue Flags;
22849
22850   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22851   if (Flags.getNode()) {
22852     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22853     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22854   }
22855
22856   return SDValue();
22857 }
22858
22859 // Optimize branch condition evaluation.
22860 //
22861 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22862                                     TargetLowering::DAGCombinerInfo &DCI,
22863                                     const X86Subtarget *Subtarget) {
22864   SDLoc DL(N);
22865   SDValue Chain = N->getOperand(0);
22866   SDValue Dest = N->getOperand(1);
22867   SDValue EFLAGS = N->getOperand(3);
22868   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22869
22870   SDValue Flags;
22871
22872   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22873   if (Flags.getNode()) {
22874     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22875     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22876                        Flags);
22877   }
22878
22879   return SDValue();
22880 }
22881
22882 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22883                                                          SelectionDAG &DAG) {
22884   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22885   // optimize away operation when it's from a constant.
22886   //
22887   // The general transformation is:
22888   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22889   //       AND(VECTOR_CMP(x,y), constant2)
22890   //    constant2 = UNARYOP(constant)
22891
22892   // Early exit if this isn't a vector operation, the operand of the
22893   // unary operation isn't a bitwise AND, or if the sizes of the operations
22894   // aren't the same.
22895   EVT VT = N->getValueType(0);
22896   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22897       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22898       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22899     return SDValue();
22900
22901   // Now check that the other operand of the AND is a constant. We could
22902   // make the transformation for non-constant splats as well, but it's unclear
22903   // that would be a benefit as it would not eliminate any operations, just
22904   // perform one more step in scalar code before moving to the vector unit.
22905   if (BuildVectorSDNode *BV =
22906           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22907     // Bail out if the vector isn't a constant.
22908     if (!BV->isConstant())
22909       return SDValue();
22910
22911     // Everything checks out. Build up the new and improved node.
22912     SDLoc DL(N);
22913     EVT IntVT = BV->getValueType(0);
22914     // Create a new constant of the appropriate type for the transformed
22915     // DAG.
22916     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22917     // The AND node needs bitcasts to/from an integer vector type around it.
22918     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22919     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22920                                  N->getOperand(0)->getOperand(0), MaskConst);
22921     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22922     return Res;
22923   }
22924
22925   return SDValue();
22926 }
22927
22928 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22929                                         const X86TargetLowering *XTLI) {
22930   // First try to optimize away the conversion entirely when it's
22931   // conditionally from a constant. Vectors only.
22932   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22933   if (Res != SDValue())
22934     return Res;
22935
22936   // Now move on to more general possibilities.
22937   SDValue Op0 = N->getOperand(0);
22938   EVT InVT = Op0->getValueType(0);
22939
22940   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22941   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22942     SDLoc dl(N);
22943     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22944     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22945     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22946   }
22947
22948   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22949   // a 32-bit target where SSE doesn't support i64->FP operations.
22950   if (Op0.getOpcode() == ISD::LOAD) {
22951     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22952     EVT VT = Ld->getValueType(0);
22953     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22954         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22955         !XTLI->getSubtarget()->is64Bit() &&
22956         VT == MVT::i64) {
22957       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22958                                           Ld->getChain(), Op0, DAG);
22959       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22960       return FILDChain;
22961     }
22962   }
22963   return SDValue();
22964 }
22965
22966 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22967 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22968                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22969   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22970   // the result is either zero or one (depending on the input carry bit).
22971   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22972   if (X86::isZeroNode(N->getOperand(0)) &&
22973       X86::isZeroNode(N->getOperand(1)) &&
22974       // We don't have a good way to replace an EFLAGS use, so only do this when
22975       // dead right now.
22976       SDValue(N, 1).use_empty()) {
22977     SDLoc DL(N);
22978     EVT VT = N->getValueType(0);
22979     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22980     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22981                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22982                                            DAG.getConstant(X86::COND_B,MVT::i8),
22983                                            N->getOperand(2)),
22984                                DAG.getConstant(1, VT));
22985     return DCI.CombineTo(N, Res1, CarryOut);
22986   }
22987
22988   return SDValue();
22989 }
22990
22991 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22992 //      (add Y, (setne X, 0)) -> sbb -1, Y
22993 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22994 //      (sub (setne X, 0), Y) -> adc -1, Y
22995 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22996   SDLoc DL(N);
22997
22998   // Look through ZExts.
22999   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23000   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23001     return SDValue();
23002
23003   SDValue SetCC = Ext.getOperand(0);
23004   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23005     return SDValue();
23006
23007   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23008   if (CC != X86::COND_E && CC != X86::COND_NE)
23009     return SDValue();
23010
23011   SDValue Cmp = SetCC.getOperand(1);
23012   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23013       !X86::isZeroNode(Cmp.getOperand(1)) ||
23014       !Cmp.getOperand(0).getValueType().isInteger())
23015     return SDValue();
23016
23017   SDValue CmpOp0 = Cmp.getOperand(0);
23018   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23019                                DAG.getConstant(1, CmpOp0.getValueType()));
23020
23021   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23022   if (CC == X86::COND_NE)
23023     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23024                        DL, OtherVal.getValueType(), OtherVal,
23025                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23026   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23027                      DL, OtherVal.getValueType(), OtherVal,
23028                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23029 }
23030
23031 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23032 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23033                                  const X86Subtarget *Subtarget) {
23034   EVT VT = N->getValueType(0);
23035   SDValue Op0 = N->getOperand(0);
23036   SDValue Op1 = N->getOperand(1);
23037
23038   // Try to synthesize horizontal adds from adds of shuffles.
23039   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23040        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23041       isHorizontalBinOp(Op0, Op1, true))
23042     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23043
23044   return OptimizeConditionalInDecrement(N, DAG);
23045 }
23046
23047 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23048                                  const X86Subtarget *Subtarget) {
23049   SDValue Op0 = N->getOperand(0);
23050   SDValue Op1 = N->getOperand(1);
23051
23052   // X86 can't encode an immediate LHS of a sub. See if we can push the
23053   // negation into a preceding instruction.
23054   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23055     // If the RHS of the sub is a XOR with one use and a constant, invert the
23056     // immediate. Then add one to the LHS of the sub so we can turn
23057     // X-Y -> X+~Y+1, saving one register.
23058     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23059         isa<ConstantSDNode>(Op1.getOperand(1))) {
23060       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23061       EVT VT = Op0.getValueType();
23062       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23063                                    Op1.getOperand(0),
23064                                    DAG.getConstant(~XorC, VT));
23065       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23066                          DAG.getConstant(C->getAPIntValue()+1, VT));
23067     }
23068   }
23069
23070   // Try to synthesize horizontal adds from adds of shuffles.
23071   EVT VT = N->getValueType(0);
23072   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23073        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23074       isHorizontalBinOp(Op0, Op1, true))
23075     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23076
23077   return OptimizeConditionalInDecrement(N, DAG);
23078 }
23079
23080 /// performVZEXTCombine - Performs build vector combines
23081 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23082                                         TargetLowering::DAGCombinerInfo &DCI,
23083                                         const X86Subtarget *Subtarget) {
23084   // (vzext (bitcast (vzext (x)) -> (vzext x)
23085   SDValue In = N->getOperand(0);
23086   while (In.getOpcode() == ISD::BITCAST)
23087     In = In.getOperand(0);
23088
23089   if (In.getOpcode() != X86ISD::VZEXT)
23090     return SDValue();
23091
23092   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
23093                      In.getOperand(0));
23094 }
23095
23096 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23097                                              DAGCombinerInfo &DCI) const {
23098   SelectionDAG &DAG = DCI.DAG;
23099   switch (N->getOpcode()) {
23100   default: break;
23101   case ISD::EXTRACT_VECTOR_ELT:
23102     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23103   case ISD::VSELECT:
23104   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23105   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23106   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
23107   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
23108   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
23109   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
23110   case ISD::SHL:
23111   case ISD::SRA:
23112   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
23113   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
23114   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
23115   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
23116   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
23117   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
23118   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
23119   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
23120   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
23121   case X86ISD::FXOR:
23122   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
23123   case X86ISD::FMIN:
23124   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
23125   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
23126   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
23127   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
23128   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
23129   case ISD::ANY_EXTEND:
23130   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
23131   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
23132   case ISD::SIGN_EXTEND_INREG:
23133     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23134   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23135   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
23136   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23137   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23138   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
23139   case X86ISD::SHUFP:       // Handle all target specific shuffles
23140   case X86ISD::PALIGNR:
23141   case X86ISD::UNPCKH:
23142   case X86ISD::UNPCKL:
23143   case X86ISD::MOVHLPS:
23144   case X86ISD::MOVLHPS:
23145   case X86ISD::PSHUFB:
23146   case X86ISD::PSHUFD:
23147   case X86ISD::PSHUFHW:
23148   case X86ISD::PSHUFLW:
23149   case X86ISD::MOVSS:
23150   case X86ISD::MOVSD:
23151   case X86ISD::VPERMILP:
23152   case X86ISD::VPERM2X128:
23153   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23154   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
23155   case ISD::INTRINSIC_WO_CHAIN:
23156     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23157   case X86ISD::INSERTPS:
23158     return PerformINSERTPSCombine(N, DAG, Subtarget);
23159   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23160   }
23161
23162   return SDValue();
23163 }
23164
23165 /// isTypeDesirableForOp - Return true if the target has native support for
23166 /// the specified value type and it is 'desirable' to use the type for the
23167 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23168 /// instruction encodings are longer and some i16 instructions are slow.
23169 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23170   if (!isTypeLegal(VT))
23171     return false;
23172   if (VT != MVT::i16)
23173     return true;
23174
23175   switch (Opc) {
23176   default:
23177     return true;
23178   case ISD::LOAD:
23179   case ISD::SIGN_EXTEND:
23180   case ISD::ZERO_EXTEND:
23181   case ISD::ANY_EXTEND:
23182   case ISD::SHL:
23183   case ISD::SRL:
23184   case ISD::SUB:
23185   case ISD::ADD:
23186   case ISD::MUL:
23187   case ISD::AND:
23188   case ISD::OR:
23189   case ISD::XOR:
23190     return false;
23191   }
23192 }
23193
23194 /// IsDesirableToPromoteOp - This method query the target whether it is
23195 /// beneficial for dag combiner to promote the specified node. If true, it
23196 /// should return the desired promotion type by reference.
23197 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23198   EVT VT = Op.getValueType();
23199   if (VT != MVT::i16)
23200     return false;
23201
23202   bool Promote = false;
23203   bool Commute = false;
23204   switch (Op.getOpcode()) {
23205   default: break;
23206   case ISD::LOAD: {
23207     LoadSDNode *LD = cast<LoadSDNode>(Op);
23208     // If the non-extending load has a single use and it's not live out, then it
23209     // might be folded.
23210     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23211                                                      Op.hasOneUse()*/) {
23212       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23213              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23214         // The only case where we'd want to promote LOAD (rather then it being
23215         // promoted as an operand is when it's only use is liveout.
23216         if (UI->getOpcode() != ISD::CopyToReg)
23217           return false;
23218       }
23219     }
23220     Promote = true;
23221     break;
23222   }
23223   case ISD::SIGN_EXTEND:
23224   case ISD::ZERO_EXTEND:
23225   case ISD::ANY_EXTEND:
23226     Promote = true;
23227     break;
23228   case ISD::SHL:
23229   case ISD::SRL: {
23230     SDValue N0 = Op.getOperand(0);
23231     // Look out for (store (shl (load), x)).
23232     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23233       return false;
23234     Promote = true;
23235     break;
23236   }
23237   case ISD::ADD:
23238   case ISD::MUL:
23239   case ISD::AND:
23240   case ISD::OR:
23241   case ISD::XOR:
23242     Commute = true;
23243     // fallthrough
23244   case ISD::SUB: {
23245     SDValue N0 = Op.getOperand(0);
23246     SDValue N1 = Op.getOperand(1);
23247     if (!Commute && MayFoldLoad(N1))
23248       return false;
23249     // Avoid disabling potential load folding opportunities.
23250     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23251       return false;
23252     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23253       return false;
23254     Promote = true;
23255   }
23256   }
23257
23258   PVT = MVT::i32;
23259   return Promote;
23260 }
23261
23262 //===----------------------------------------------------------------------===//
23263 //                           X86 Inline Assembly Support
23264 //===----------------------------------------------------------------------===//
23265
23266 namespace {
23267   // Helper to match a string separated by whitespace.
23268   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
23269     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
23270
23271     for (unsigned i = 0, e = args.size(); i != e; ++i) {
23272       StringRef piece(*args[i]);
23273       if (!s.startswith(piece)) // Check if the piece matches.
23274         return false;
23275
23276       s = s.substr(piece.size());
23277       StringRef::size_type pos = s.find_first_not_of(" \t");
23278       if (pos == 0) // We matched a prefix.
23279         return false;
23280
23281       s = s.substr(pos);
23282     }
23283
23284     return s.empty();
23285   }
23286   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
23287 }
23288
23289 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23290
23291   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23292     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23293         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23294         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23295
23296       if (AsmPieces.size() == 3)
23297         return true;
23298       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23299         return true;
23300     }
23301   }
23302   return false;
23303 }
23304
23305 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23306   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23307
23308   std::string AsmStr = IA->getAsmString();
23309
23310   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23311   if (!Ty || Ty->getBitWidth() % 16 != 0)
23312     return false;
23313
23314   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23315   SmallVector<StringRef, 4> AsmPieces;
23316   SplitString(AsmStr, AsmPieces, ";\n");
23317
23318   switch (AsmPieces.size()) {
23319   default: return false;
23320   case 1:
23321     // FIXME: this should verify that we are targeting a 486 or better.  If not,
23322     // we will turn this bswap into something that will be lowered to logical
23323     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
23324     // lower so don't worry about this.
23325     // bswap $0
23326     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
23327         matchAsm(AsmPieces[0], "bswapl", "$0") ||
23328         matchAsm(AsmPieces[0], "bswapq", "$0") ||
23329         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
23330         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
23331         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
23332       // No need to check constraints, nothing other than the equivalent of
23333       // "=r,0" would be valid here.
23334       return IntrinsicLowering::LowerToByteSwap(CI);
23335     }
23336
23337     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
23338     if (CI->getType()->isIntegerTy(16) &&
23339         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23340         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
23341          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23342       AsmPieces.clear();
23343       const std::string &ConstraintsStr = IA->getConstraintString();
23344       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23345       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23346       if (clobbersFlagRegisters(AsmPieces))
23347         return IntrinsicLowering::LowerToByteSwap(CI);
23348     }
23349     break;
23350   case 3:
23351     if (CI->getType()->isIntegerTy(32) &&
23352         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23353         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23354         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23355         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23356       AsmPieces.clear();
23357       const std::string &ConstraintsStr = IA->getConstraintString();
23358       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23359       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23360       if (clobbersFlagRegisters(AsmPieces))
23361         return IntrinsicLowering::LowerToByteSwap(CI);
23362     }
23363
23364     if (CI->getType()->isIntegerTy(64)) {
23365       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23366       if (Constraints.size() >= 2 &&
23367           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23368           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23369         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
23370         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23371             matchAsm(AsmPieces[1], "bswap", "%edx") &&
23372             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23373           return IntrinsicLowering::LowerToByteSwap(CI);
23374       }
23375     }
23376     break;
23377   }
23378   return false;
23379 }
23380
23381 /// getConstraintType - Given a constraint letter, return the type of
23382 /// constraint it is for this target.
23383 X86TargetLowering::ConstraintType
23384 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23385   if (Constraint.size() == 1) {
23386     switch (Constraint[0]) {
23387     case 'R':
23388     case 'q':
23389     case 'Q':
23390     case 'f':
23391     case 't':
23392     case 'u':
23393     case 'y':
23394     case 'x':
23395     case 'Y':
23396     case 'l':
23397       return C_RegisterClass;
23398     case 'a':
23399     case 'b':
23400     case 'c':
23401     case 'd':
23402     case 'S':
23403     case 'D':
23404     case 'A':
23405       return C_Register;
23406     case 'I':
23407     case 'J':
23408     case 'K':
23409     case 'L':
23410     case 'M':
23411     case 'N':
23412     case 'G':
23413     case 'C':
23414     case 'e':
23415     case 'Z':
23416       return C_Other;
23417     default:
23418       break;
23419     }
23420   }
23421   return TargetLowering::getConstraintType(Constraint);
23422 }
23423
23424 /// Examine constraint type and operand type and determine a weight value.
23425 /// This object must already have been set up with the operand type
23426 /// and the current alternative constraint selected.
23427 TargetLowering::ConstraintWeight
23428   X86TargetLowering::getSingleConstraintMatchWeight(
23429     AsmOperandInfo &info, const char *constraint) const {
23430   ConstraintWeight weight = CW_Invalid;
23431   Value *CallOperandVal = info.CallOperandVal;
23432     // If we don't have a value, we can't do a match,
23433     // but allow it at the lowest weight.
23434   if (!CallOperandVal)
23435     return CW_Default;
23436   Type *type = CallOperandVal->getType();
23437   // Look at the constraint type.
23438   switch (*constraint) {
23439   default:
23440     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23441   case 'R':
23442   case 'q':
23443   case 'Q':
23444   case 'a':
23445   case 'b':
23446   case 'c':
23447   case 'd':
23448   case 'S':
23449   case 'D':
23450   case 'A':
23451     if (CallOperandVal->getType()->isIntegerTy())
23452       weight = CW_SpecificReg;
23453     break;
23454   case 'f':
23455   case 't':
23456   case 'u':
23457     if (type->isFloatingPointTy())
23458       weight = CW_SpecificReg;
23459     break;
23460   case 'y':
23461     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23462       weight = CW_SpecificReg;
23463     break;
23464   case 'x':
23465   case 'Y':
23466     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23467         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23468       weight = CW_Register;
23469     break;
23470   case 'I':
23471     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23472       if (C->getZExtValue() <= 31)
23473         weight = CW_Constant;
23474     }
23475     break;
23476   case 'J':
23477     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23478       if (C->getZExtValue() <= 63)
23479         weight = CW_Constant;
23480     }
23481     break;
23482   case 'K':
23483     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23484       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23485         weight = CW_Constant;
23486     }
23487     break;
23488   case 'L':
23489     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23490       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23491         weight = CW_Constant;
23492     }
23493     break;
23494   case 'M':
23495     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23496       if (C->getZExtValue() <= 3)
23497         weight = CW_Constant;
23498     }
23499     break;
23500   case 'N':
23501     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23502       if (C->getZExtValue() <= 0xff)
23503         weight = CW_Constant;
23504     }
23505     break;
23506   case 'G':
23507   case 'C':
23508     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23509       weight = CW_Constant;
23510     }
23511     break;
23512   case 'e':
23513     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23514       if ((C->getSExtValue() >= -0x80000000LL) &&
23515           (C->getSExtValue() <= 0x7fffffffLL))
23516         weight = CW_Constant;
23517     }
23518     break;
23519   case 'Z':
23520     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23521       if (C->getZExtValue() <= 0xffffffff)
23522         weight = CW_Constant;
23523     }
23524     break;
23525   }
23526   return weight;
23527 }
23528
23529 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23530 /// with another that has more specific requirements based on the type of the
23531 /// corresponding operand.
23532 const char *X86TargetLowering::
23533 LowerXConstraint(EVT ConstraintVT) const {
23534   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23535   // 'f' like normal targets.
23536   if (ConstraintVT.isFloatingPoint()) {
23537     if (Subtarget->hasSSE2())
23538       return "Y";
23539     if (Subtarget->hasSSE1())
23540       return "x";
23541   }
23542
23543   return TargetLowering::LowerXConstraint(ConstraintVT);
23544 }
23545
23546 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23547 /// vector.  If it is invalid, don't add anything to Ops.
23548 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23549                                                      std::string &Constraint,
23550                                                      std::vector<SDValue>&Ops,
23551                                                      SelectionDAG &DAG) const {
23552   SDValue Result;
23553
23554   // Only support length 1 constraints for now.
23555   if (Constraint.length() > 1) return;
23556
23557   char ConstraintLetter = Constraint[0];
23558   switch (ConstraintLetter) {
23559   default: break;
23560   case 'I':
23561     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23562       if (C->getZExtValue() <= 31) {
23563         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23564         break;
23565       }
23566     }
23567     return;
23568   case 'J':
23569     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23570       if (C->getZExtValue() <= 63) {
23571         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23572         break;
23573       }
23574     }
23575     return;
23576   case 'K':
23577     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23578       if (isInt<8>(C->getSExtValue())) {
23579         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23580         break;
23581       }
23582     }
23583     return;
23584   case 'N':
23585     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23586       if (C->getZExtValue() <= 255) {
23587         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23588         break;
23589       }
23590     }
23591     return;
23592   case 'e': {
23593     // 32-bit signed value
23594     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23595       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23596                                            C->getSExtValue())) {
23597         // Widen to 64 bits here to get it sign extended.
23598         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23599         break;
23600       }
23601     // FIXME gcc accepts some relocatable values here too, but only in certain
23602     // memory models; it's complicated.
23603     }
23604     return;
23605   }
23606   case 'Z': {
23607     // 32-bit unsigned value
23608     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23609       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23610                                            C->getZExtValue())) {
23611         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23612         break;
23613       }
23614     }
23615     // FIXME gcc accepts some relocatable values here too, but only in certain
23616     // memory models; it's complicated.
23617     return;
23618   }
23619   case 'i': {
23620     // Literal immediates are always ok.
23621     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23622       // Widen to 64 bits here to get it sign extended.
23623       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23624       break;
23625     }
23626
23627     // In any sort of PIC mode addresses need to be computed at runtime by
23628     // adding in a register or some sort of table lookup.  These can't
23629     // be used as immediates.
23630     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23631       return;
23632
23633     // If we are in non-pic codegen mode, we allow the address of a global (with
23634     // an optional displacement) to be used with 'i'.
23635     GlobalAddressSDNode *GA = nullptr;
23636     int64_t Offset = 0;
23637
23638     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23639     while (1) {
23640       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23641         Offset += GA->getOffset();
23642         break;
23643       } else if (Op.getOpcode() == ISD::ADD) {
23644         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23645           Offset += C->getZExtValue();
23646           Op = Op.getOperand(0);
23647           continue;
23648         }
23649       } else if (Op.getOpcode() == ISD::SUB) {
23650         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23651           Offset += -C->getZExtValue();
23652           Op = Op.getOperand(0);
23653           continue;
23654         }
23655       }
23656
23657       // Otherwise, this isn't something we can handle, reject it.
23658       return;
23659     }
23660
23661     const GlobalValue *GV = GA->getGlobal();
23662     // If we require an extra load to get this address, as in PIC mode, we
23663     // can't accept it.
23664     if (isGlobalStubReference(
23665             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23666       return;
23667
23668     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23669                                         GA->getValueType(0), Offset);
23670     break;
23671   }
23672   }
23673
23674   if (Result.getNode()) {
23675     Ops.push_back(Result);
23676     return;
23677   }
23678   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23679 }
23680
23681 std::pair<unsigned, const TargetRegisterClass*>
23682 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23683                                                 MVT VT) const {
23684   // First, see if this is a constraint that directly corresponds to an LLVM
23685   // register class.
23686   if (Constraint.size() == 1) {
23687     // GCC Constraint Letters
23688     switch (Constraint[0]) {
23689     default: break;
23690       // TODO: Slight differences here in allocation order and leaving
23691       // RIP in the class. Do they matter any more here than they do
23692       // in the normal allocation?
23693     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23694       if (Subtarget->is64Bit()) {
23695         if (VT == MVT::i32 || VT == MVT::f32)
23696           return std::make_pair(0U, &X86::GR32RegClass);
23697         if (VT == MVT::i16)
23698           return std::make_pair(0U, &X86::GR16RegClass);
23699         if (VT == MVT::i8 || VT == MVT::i1)
23700           return std::make_pair(0U, &X86::GR8RegClass);
23701         if (VT == MVT::i64 || VT == MVT::f64)
23702           return std::make_pair(0U, &X86::GR64RegClass);
23703         break;
23704       }
23705       // 32-bit fallthrough
23706     case 'Q':   // Q_REGS
23707       if (VT == MVT::i32 || VT == MVT::f32)
23708         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23709       if (VT == MVT::i16)
23710         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23711       if (VT == MVT::i8 || VT == MVT::i1)
23712         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23713       if (VT == MVT::i64)
23714         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23715       break;
23716     case 'r':   // GENERAL_REGS
23717     case 'l':   // INDEX_REGS
23718       if (VT == MVT::i8 || VT == MVT::i1)
23719         return std::make_pair(0U, &X86::GR8RegClass);
23720       if (VT == MVT::i16)
23721         return std::make_pair(0U, &X86::GR16RegClass);
23722       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23723         return std::make_pair(0U, &X86::GR32RegClass);
23724       return std::make_pair(0U, &X86::GR64RegClass);
23725     case 'R':   // LEGACY_REGS
23726       if (VT == MVT::i8 || VT == MVT::i1)
23727         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23728       if (VT == MVT::i16)
23729         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23730       if (VT == MVT::i32 || !Subtarget->is64Bit())
23731         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23732       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23733     case 'f':  // FP Stack registers.
23734       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23735       // value to the correct fpstack register class.
23736       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23737         return std::make_pair(0U, &X86::RFP32RegClass);
23738       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23739         return std::make_pair(0U, &X86::RFP64RegClass);
23740       return std::make_pair(0U, &X86::RFP80RegClass);
23741     case 'y':   // MMX_REGS if MMX allowed.
23742       if (!Subtarget->hasMMX()) break;
23743       return std::make_pair(0U, &X86::VR64RegClass);
23744     case 'Y':   // SSE_REGS if SSE2 allowed
23745       if (!Subtarget->hasSSE2()) break;
23746       // FALL THROUGH.
23747     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23748       if (!Subtarget->hasSSE1()) break;
23749
23750       switch (VT.SimpleTy) {
23751       default: break;
23752       // Scalar SSE types.
23753       case MVT::f32:
23754       case MVT::i32:
23755         return std::make_pair(0U, &X86::FR32RegClass);
23756       case MVT::f64:
23757       case MVT::i64:
23758         return std::make_pair(0U, &X86::FR64RegClass);
23759       // Vector types.
23760       case MVT::v16i8:
23761       case MVT::v8i16:
23762       case MVT::v4i32:
23763       case MVT::v2i64:
23764       case MVT::v4f32:
23765       case MVT::v2f64:
23766         return std::make_pair(0U, &X86::VR128RegClass);
23767       // AVX types.
23768       case MVT::v32i8:
23769       case MVT::v16i16:
23770       case MVT::v8i32:
23771       case MVT::v4i64:
23772       case MVT::v8f32:
23773       case MVT::v4f64:
23774         return std::make_pair(0U, &X86::VR256RegClass);
23775       case MVT::v8f64:
23776       case MVT::v16f32:
23777       case MVT::v16i32:
23778       case MVT::v8i64:
23779         return std::make_pair(0U, &X86::VR512RegClass);
23780       }
23781       break;
23782     }
23783   }
23784
23785   // Use the default implementation in TargetLowering to convert the register
23786   // constraint into a member of a register class.
23787   std::pair<unsigned, const TargetRegisterClass*> Res;
23788   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23789
23790   // Not found as a standard register?
23791   if (!Res.second) {
23792     // Map st(0) -> st(7) -> ST0
23793     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23794         tolower(Constraint[1]) == 's' &&
23795         tolower(Constraint[2]) == 't' &&
23796         Constraint[3] == '(' &&
23797         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23798         Constraint[5] == ')' &&
23799         Constraint[6] == '}') {
23800
23801       Res.first = X86::FP0+Constraint[4]-'0';
23802       Res.second = &X86::RFP80RegClass;
23803       return Res;
23804     }
23805
23806     // GCC allows "st(0)" to be called just plain "st".
23807     if (StringRef("{st}").equals_lower(Constraint)) {
23808       Res.first = X86::FP0;
23809       Res.second = &X86::RFP80RegClass;
23810       return Res;
23811     }
23812
23813     // flags -> EFLAGS
23814     if (StringRef("{flags}").equals_lower(Constraint)) {
23815       Res.first = X86::EFLAGS;
23816       Res.second = &X86::CCRRegClass;
23817       return Res;
23818     }
23819
23820     // 'A' means EAX + EDX.
23821     if (Constraint == "A") {
23822       Res.first = X86::EAX;
23823       Res.second = &X86::GR32_ADRegClass;
23824       return Res;
23825     }
23826     return Res;
23827   }
23828
23829   // Otherwise, check to see if this is a register class of the wrong value
23830   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23831   // turn into {ax},{dx}.
23832   if (Res.second->hasType(VT))
23833     return Res;   // Correct type already, nothing to do.
23834
23835   // All of the single-register GCC register classes map their values onto
23836   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23837   // really want an 8-bit or 32-bit register, map to the appropriate register
23838   // class and return the appropriate register.
23839   if (Res.second == &X86::GR16RegClass) {
23840     if (VT == MVT::i8 || VT == MVT::i1) {
23841       unsigned DestReg = 0;
23842       switch (Res.first) {
23843       default: break;
23844       case X86::AX: DestReg = X86::AL; break;
23845       case X86::DX: DestReg = X86::DL; break;
23846       case X86::CX: DestReg = X86::CL; break;
23847       case X86::BX: DestReg = X86::BL; break;
23848       }
23849       if (DestReg) {
23850         Res.first = DestReg;
23851         Res.second = &X86::GR8RegClass;
23852       }
23853     } else if (VT == MVT::i32 || VT == MVT::f32) {
23854       unsigned DestReg = 0;
23855       switch (Res.first) {
23856       default: break;
23857       case X86::AX: DestReg = X86::EAX; break;
23858       case X86::DX: DestReg = X86::EDX; break;
23859       case X86::CX: DestReg = X86::ECX; break;
23860       case X86::BX: DestReg = X86::EBX; break;
23861       case X86::SI: DestReg = X86::ESI; break;
23862       case X86::DI: DestReg = X86::EDI; break;
23863       case X86::BP: DestReg = X86::EBP; break;
23864       case X86::SP: DestReg = X86::ESP; break;
23865       }
23866       if (DestReg) {
23867         Res.first = DestReg;
23868         Res.second = &X86::GR32RegClass;
23869       }
23870     } else if (VT == MVT::i64 || VT == MVT::f64) {
23871       unsigned DestReg = 0;
23872       switch (Res.first) {
23873       default: break;
23874       case X86::AX: DestReg = X86::RAX; break;
23875       case X86::DX: DestReg = X86::RDX; break;
23876       case X86::CX: DestReg = X86::RCX; break;
23877       case X86::BX: DestReg = X86::RBX; break;
23878       case X86::SI: DestReg = X86::RSI; break;
23879       case X86::DI: DestReg = X86::RDI; break;
23880       case X86::BP: DestReg = X86::RBP; break;
23881       case X86::SP: DestReg = X86::RSP; break;
23882       }
23883       if (DestReg) {
23884         Res.first = DestReg;
23885         Res.second = &X86::GR64RegClass;
23886       }
23887     }
23888   } else if (Res.second == &X86::FR32RegClass ||
23889              Res.second == &X86::FR64RegClass ||
23890              Res.second == &X86::VR128RegClass ||
23891              Res.second == &X86::VR256RegClass ||
23892              Res.second == &X86::FR32XRegClass ||
23893              Res.second == &X86::FR64XRegClass ||
23894              Res.second == &X86::VR128XRegClass ||
23895              Res.second == &X86::VR256XRegClass ||
23896              Res.second == &X86::VR512RegClass) {
23897     // Handle references to XMM physical registers that got mapped into the
23898     // wrong class.  This can happen with constraints like {xmm0} where the
23899     // target independent register mapper will just pick the first match it can
23900     // find, ignoring the required type.
23901
23902     if (VT == MVT::f32 || VT == MVT::i32)
23903       Res.second = &X86::FR32RegClass;
23904     else if (VT == MVT::f64 || VT == MVT::i64)
23905       Res.second = &X86::FR64RegClass;
23906     else if (X86::VR128RegClass.hasType(VT))
23907       Res.second = &X86::VR128RegClass;
23908     else if (X86::VR256RegClass.hasType(VT))
23909       Res.second = &X86::VR256RegClass;
23910     else if (X86::VR512RegClass.hasType(VT))
23911       Res.second = &X86::VR512RegClass;
23912   }
23913
23914   return Res;
23915 }
23916
23917 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23918                                             Type *Ty) const {
23919   // Scaling factors are not free at all.
23920   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23921   // will take 2 allocations in the out of order engine instead of 1
23922   // for plain addressing mode, i.e. inst (reg1).
23923   // E.g.,
23924   // vaddps (%rsi,%drx), %ymm0, %ymm1
23925   // Requires two allocations (one for the load, one for the computation)
23926   // whereas:
23927   // vaddps (%rsi), %ymm0, %ymm1
23928   // Requires just 1 allocation, i.e., freeing allocations for other operations
23929   // and having less micro operations to execute.
23930   //
23931   // For some X86 architectures, this is even worse because for instance for
23932   // stores, the complex addressing mode forces the instruction to use the
23933   // "load" ports instead of the dedicated "store" port.
23934   // E.g., on Haswell:
23935   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23936   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23937   if (isLegalAddressingMode(AM, Ty))
23938     // Scale represents reg2 * scale, thus account for 1
23939     // as soon as we use a second register.
23940     return AM.Scale != 0;
23941   return -1;
23942 }
23943
23944 bool X86TargetLowering::isTargetFTOL() const {
23945   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23946 }