ab87d172297434c83c9037c5524375fe8cae6abf
[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, Subtarget->is64Bit() ?
663                      MVT::i64 : MVT::i32, Custom);
664
665   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666     // f32 and f64 use SSE.
667     // Set up the FP register classes.
668     addRegisterClass(MVT::f32, &X86::FR32RegClass);
669     addRegisterClass(MVT::f64, &X86::FR64RegClass);
670
671     // Use ANDPD to simulate FABS.
672     setOperationAction(ISD::FABS , MVT::f64, Custom);
673     setOperationAction(ISD::FABS , MVT::f32, Custom);
674
675     // Use XORP to simulate FNEG.
676     setOperationAction(ISD::FNEG , MVT::f64, Custom);
677     setOperationAction(ISD::FNEG , MVT::f32, Custom);
678
679     // Use ANDPD and ORPD to simulate FCOPYSIGN.
680     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
682
683     // Lower this to FGETSIGNx86 plus an AND.
684     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
686
687     // We don't support sin/cos/fmod
688     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
689     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
690     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
692     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
693     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
694
695     // Expand FP immediates into loads from the stack, except for the special
696     // cases we handle.
697     addLegalFPImmediate(APFloat(+0.0)); // xorpd
698     addLegalFPImmediate(APFloat(+0.0f)); // xorps
699   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700     // Use SSE for f32, x87 for f64.
701     // Set up the FP register classes.
702     addRegisterClass(MVT::f32, &X86::FR32RegClass);
703     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
704
705     // Use ANDPS to simulate FABS.
706     setOperationAction(ISD::FABS , MVT::f32, Custom);
707
708     // Use XORP to simulate FNEG.
709     setOperationAction(ISD::FNEG , MVT::f32, Custom);
710
711     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
712
713     // Use ANDPS and ORPS to simulate FCOPYSIGN.
714     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
716
717     // We don't support sin/cos/fmod
718     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
719     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
720     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
721
722     // Special cases we handle for FP constants.
723     addLegalFPImmediate(APFloat(+0.0f)); // xorps
724     addLegalFPImmediate(APFloat(+0.0)); // FLD0
725     addLegalFPImmediate(APFloat(+1.0)); // FLD1
726     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
728
729     if (!TM.Options.UnsafeFPMath) {
730       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
732       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733     }
734   } else if (!TM.Options.UseSoftFloat) {
735     // f32 and f64 in x87.
736     // Set up the FP register classes.
737     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
739
740     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
741     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
744
745     if (!TM.Options.UnsafeFPMath) {
746       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
747       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
749       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
752     }
753     addLegalFPImmediate(APFloat(+0.0)); // FLD0
754     addLegalFPImmediate(APFloat(+1.0)); // FLD1
755     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
761   }
762
763   // We don't support FMA.
764   setOperationAction(ISD::FMA, MVT::f64, Expand);
765   setOperationAction(ISD::FMA, MVT::f32, Expand);
766
767   // Long double always uses X87.
768   if (!TM.Options.UseSoftFloat) {
769     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
771     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
772     {
773       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774       addLegalFPImmediate(TmpFlt);  // FLD0
775       TmpFlt.changeSign();
776       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
777
778       bool ignored;
779       APFloat TmpFlt2(+1.0);
780       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
781                       &ignored);
782       addLegalFPImmediate(TmpFlt2);  // FLD1
783       TmpFlt2.changeSign();
784       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
785     }
786
787     if (!TM.Options.UnsafeFPMath) {
788       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
789       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
790       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
791     }
792
793     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
795     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
797     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798     setOperationAction(ISD::FMA, MVT::f80, Expand);
799   }
800
801   // Always use a library call for pow.
802   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
804   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
805
806   setOperationAction(ISD::FLOG, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP, MVT::f80, Expand);
810   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
811
812   // First set operation action for all vector types to either promote
813   // (for widening) or expand (for scalarization). Then we will selectively
814   // turn on ones that can be effectively codegen'd.
815   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817     MVT VT = (MVT::SimpleValueType)i;
818     setOperationAction(ISD::ADD , VT, Expand);
819     setOperationAction(ISD::SUB , VT, Expand);
820     setOperationAction(ISD::FADD, VT, Expand);
821     setOperationAction(ISD::FNEG, VT, Expand);
822     setOperationAction(ISD::FSUB, VT, Expand);
823     setOperationAction(ISD::MUL , VT, Expand);
824     setOperationAction(ISD::FMUL, VT, Expand);
825     setOperationAction(ISD::SDIV, VT, Expand);
826     setOperationAction(ISD::UDIV, VT, Expand);
827     setOperationAction(ISD::FDIV, VT, Expand);
828     setOperationAction(ISD::SREM, VT, Expand);
829     setOperationAction(ISD::UREM, VT, Expand);
830     setOperationAction(ISD::LOAD, VT, Expand);
831     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836     setOperationAction(ISD::FABS, VT, Expand);
837     setOperationAction(ISD::FSIN, VT, Expand);
838     setOperationAction(ISD::FSINCOS, VT, Expand);
839     setOperationAction(ISD::FCOS, VT, Expand);
840     setOperationAction(ISD::FSINCOS, VT, Expand);
841     setOperationAction(ISD::FREM, VT, Expand);
842     setOperationAction(ISD::FMA,  VT, Expand);
843     setOperationAction(ISD::FPOWI, VT, Expand);
844     setOperationAction(ISD::FSQRT, VT, Expand);
845     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846     setOperationAction(ISD::FFLOOR, VT, Expand);
847     setOperationAction(ISD::FCEIL, VT, Expand);
848     setOperationAction(ISD::FTRUNC, VT, Expand);
849     setOperationAction(ISD::FRINT, VT, Expand);
850     setOperationAction(ISD::FNEARBYINT, VT, Expand);
851     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852     setOperationAction(ISD::MULHS, VT, Expand);
853     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854     setOperationAction(ISD::MULHU, VT, Expand);
855     setOperationAction(ISD::SDIVREM, VT, Expand);
856     setOperationAction(ISD::UDIVREM, VT, Expand);
857     setOperationAction(ISD::FPOW, VT, Expand);
858     setOperationAction(ISD::CTPOP, VT, Expand);
859     setOperationAction(ISD::CTTZ, VT, Expand);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861     setOperationAction(ISD::CTLZ, VT, Expand);
862     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863     setOperationAction(ISD::SHL, VT, Expand);
864     setOperationAction(ISD::SRA, VT, Expand);
865     setOperationAction(ISD::SRL, VT, Expand);
866     setOperationAction(ISD::ROTL, VT, Expand);
867     setOperationAction(ISD::ROTR, VT, Expand);
868     setOperationAction(ISD::BSWAP, VT, Expand);
869     setOperationAction(ISD::SETCC, VT, Expand);
870     setOperationAction(ISD::FLOG, VT, Expand);
871     setOperationAction(ISD::FLOG2, VT, Expand);
872     setOperationAction(ISD::FLOG10, VT, Expand);
873     setOperationAction(ISD::FEXP, VT, Expand);
874     setOperationAction(ISD::FEXP2, VT, Expand);
875     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880     setOperationAction(ISD::TRUNCATE, VT, Expand);
881     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884     setOperationAction(ISD::VSELECT, VT, Expand);
885     setOperationAction(ISD::SELECT_CC, VT, Expand);
886     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888       setTruncStoreAction(VT,
889                           (MVT::SimpleValueType)InnerVT, Expand);
890     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
892
893     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894     // we have to deal with them whether we ask for Expansion or not. Setting
895     // Expand causes its own optimisation problems though, so leave them legal.
896     if (VT.getVectorElementType() == MVT::i1)
897       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
898   }
899
900   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901   // with -msoft-float, disable use of MMX as well.
902   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904     // No operations on x86mmx supported, everything uses intrinsics.
905   }
906
907   // MMX-sized vectors (other than x86mmx) are expected to be expanded
908   // into smaller operations.
909   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
910   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
912   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
913   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
914   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
915   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
916   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
917   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
918   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
919   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
920   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
921   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
922   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
923   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
924   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
928   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
929   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
930   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
931   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
933   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
937   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
938
939   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
941
942     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
946     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
947     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
948     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
949     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
950     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
951     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
952     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
954   }
955
956   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
958
959     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
960     // registers cannot be used even for integer operations.
961     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
965
966     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
967     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
968     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
969     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
970     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
971     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
972     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
974     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
975     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
976     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
977     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
978     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
979     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
980     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
981     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
985     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
986     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
987     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
988
989     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
992     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
993
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
995     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002       MVT VT = (MVT::SimpleValueType)i;
1003       // Do not attempt to custom lower non-power-of-2 vectors
1004       if (!isPowerOf2_32(VT.getVectorNumElements()))
1005         continue;
1006       // Do not attempt to custom lower non-128-bit vectors
1007       if (!VT.is128BitVector())
1008         continue;
1009       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1010       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012     }
1013
1014     // We support custom legalizing of sext and anyext loads for specific
1015     // memory vector types which we can load as a scalar (or sequence of
1016     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1017     // loads these must work with a single scalar load.
1018     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1019     if (Subtarget->is64Bit()) {
1020       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1021       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1022     }
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1028     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1029
1030     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1031     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1032     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1033     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1034     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1035     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1036
1037     if (Subtarget->is64Bit()) {
1038       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1039       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1040     }
1041
1042     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1043     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1044       MVT VT = (MVT::SimpleValueType)i;
1045
1046       // Do not attempt to promote non-128-bit vectors
1047       if (!VT.is128BitVector())
1048         continue;
1049
1050       setOperationAction(ISD::AND,    VT, Promote);
1051       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1052       setOperationAction(ISD::OR,     VT, Promote);
1053       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1054       setOperationAction(ISD::XOR,    VT, Promote);
1055       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1056       setOperationAction(ISD::LOAD,   VT, Promote);
1057       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1058       setOperationAction(ISD::SELECT, VT, Promote);
1059       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1060     }
1061
1062     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1063
1064     // Custom lower v2i64 and v2f64 selects.
1065     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1066     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1067     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1068     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1069
1070     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1071     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1072
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1074     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1075     // As there is no 64-bit GPR available, we need build a special custom
1076     // sequence to convert from v2i32 to v2f32.
1077     if (!Subtarget->is64Bit())
1078       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1079
1080     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1081     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1082
1083     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1084
1085     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1086     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1087     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1088   }
1089
1090   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1091     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1092     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1093     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1094     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1095     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1096     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1097     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1098     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1099     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1100     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1101
1102     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1103     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1104     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1105     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1106     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1107     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1108     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1109     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1110     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1111     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1112
1113     // FIXME: Do we need to handle scalar-to-vector here?
1114     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1115
1116     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1119     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1120     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1121     // There is no BLENDI for byte vectors. We don't need to custom lower
1122     // some vselects for now.
1123     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1124
1125     // SSE41 brings specific instructions for doing vector sign extend even in
1126     // cases where we don't have SRA.
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1128     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1129     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1130
1131     // i8 and i16 vectors are custom , because the source register and source
1132     // source memory operand types are not the same width.  f32 vectors are
1133     // custom since the immediate controlling the insert encodes additional
1134     // information.
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1138     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1139
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1143     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1144
1145     // FIXME: these should be Legal but thats only for the case where
1146     // the index is constant.  For now custom expand to deal with that.
1147     if (Subtarget->is64Bit()) {
1148       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1149       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1150     }
1151   }
1152
1153   if (Subtarget->hasSSE2()) {
1154     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1155     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1156
1157     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1158     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1159
1160     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1161     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1162
1163     // In the customized shift lowering, the legal cases in AVX2 will be
1164     // recognized.
1165     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1166     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1167
1168     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1169     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1170
1171     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1172   }
1173
1174   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1175     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1176     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1177     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1179     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1180     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1181
1182     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1183     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1184     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1185
1186     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1190     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1191     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1192     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1193     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1194     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1195     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1196     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1197     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1198
1199     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1203     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1204     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1205     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1206     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1207     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1208     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1209     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1210     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1211
1212     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1213     // even though v8i16 is a legal type.
1214     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1215     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1216     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1217
1218     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1219     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1220     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1221
1222     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1223     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1224
1225     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1226
1227     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1228     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1229
1230     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1231     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1232
1233     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1234     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1235
1236     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1238     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1239     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1240
1241     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1242     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1243     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1244
1245     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1247     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1248     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1249
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1251     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1252     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1254     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1255     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1257     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1258     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1260     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1261     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1262
1263     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1264       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1266       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1267       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1268       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1269       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1270     }
1271
1272     if (Subtarget->hasInt256()) {
1273       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1275       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1276       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1277
1278       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1280       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1281       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1282
1283       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1284       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1285       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1286       // Don't lower v32i8 because there is no 128-bit byte mul
1287
1288       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1289       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1290       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1291       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1292
1293       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1294       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1295     } else {
1296       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1298       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1299       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1300
1301       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1303       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1304       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1305
1306       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1307       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1308       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1309       // Don't lower v32i8 because there is no 128-bit byte mul
1310     }
1311
1312     // In the customized shift lowering, the legal cases in AVX2 will be
1313     // recognized.
1314     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1315     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1316
1317     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1318     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1319
1320     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1321
1322     // Custom lower several nodes for 256-bit types.
1323     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1324              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1325       MVT VT = (MVT::SimpleValueType)i;
1326
1327       // Extract subvector is special because the value type
1328       // (result) is 128-bit but the source is 256-bit wide.
1329       if (VT.is128BitVector())
1330         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1331
1332       // Do not attempt to custom lower other non-256-bit vectors
1333       if (!VT.is256BitVector())
1334         continue;
1335
1336       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1337       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1338       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1339       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1340       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1341       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1342       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1343     }
1344
1345     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1346     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1347       MVT VT = (MVT::SimpleValueType)i;
1348
1349       // Do not attempt to promote non-256-bit vectors
1350       if (!VT.is256BitVector())
1351         continue;
1352
1353       setOperationAction(ISD::AND,    VT, Promote);
1354       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1355       setOperationAction(ISD::OR,     VT, Promote);
1356       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1357       setOperationAction(ISD::XOR,    VT, Promote);
1358       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1359       setOperationAction(ISD::LOAD,   VT, Promote);
1360       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1361       setOperationAction(ISD::SELECT, VT, Promote);
1362       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1363     }
1364   }
1365
1366   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1367     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1368     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1369     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1370     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1371
1372     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1373     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1374     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1375
1376     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1377     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1378     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1379     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1380     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1381     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1385     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1386     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1387
1388     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1391     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1392     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1393     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1394
1395     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1398     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1399     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1400     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1401     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1402     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1403
1404     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1405     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1406     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1407     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1408     if (Subtarget->is64Bit()) {
1409       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1410       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1411       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1412       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1413     }
1414     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1416     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1417     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1418     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1421     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1422     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1423     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1424
1425     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1438
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1445
1446     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1447     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1448
1449     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1450
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1454     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1456     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1460
1461     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1462     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1463
1464     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1465     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1466
1467     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1468
1469     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1470     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1471
1472     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1473     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1474
1475     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1476     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1477
1478     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1479     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1480     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1481     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1482     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1483     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1484
1485     if (Subtarget->hasCDI()) {
1486       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1487       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1488     }
1489
1490     // Custom lower several nodes.
1491     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1492              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1493       MVT VT = (MVT::SimpleValueType)i;
1494
1495       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1496       // Extract subvector is special because the value type
1497       // (result) is 256/128-bit but the source is 512-bit wide.
1498       if (VT.is128BitVector() || VT.is256BitVector())
1499         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1500
1501       if (VT.getVectorElementType() == MVT::i1)
1502         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1503
1504       // Do not attempt to custom lower other non-512-bit vectors
1505       if (!VT.is512BitVector())
1506         continue;
1507
1508       if ( EltSize >= 32) {
1509         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1510         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1511         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1512         setOperationAction(ISD::VSELECT,             VT, Legal);
1513         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1514         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1515         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1516       }
1517     }
1518     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1519       MVT VT = (MVT::SimpleValueType)i;
1520
1521       // Do not attempt to promote non-256-bit vectors
1522       if (!VT.is512BitVector())
1523         continue;
1524
1525       setOperationAction(ISD::SELECT, VT, Promote);
1526       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1527     }
1528   }// has  AVX-512
1529
1530   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1531     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1532     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1533   }
1534
1535   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1536   // of this type with custom code.
1537   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1538            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1539     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1540                        Custom);
1541   }
1542
1543   // We want to custom lower some of our intrinsics.
1544   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1545   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1546   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1547   if (!Subtarget->is64Bit())
1548     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1549
1550   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1551   // handle type legalization for these operations here.
1552   //
1553   // FIXME: We really should do custom legalization for addition and
1554   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1555   // than generic legalization for 64-bit multiplication-with-overflow, though.
1556   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1557     // Add/Sub/Mul with overflow operations are custom lowered.
1558     MVT VT = IntVTs[i];
1559     setOperationAction(ISD::SADDO, VT, Custom);
1560     setOperationAction(ISD::UADDO, VT, Custom);
1561     setOperationAction(ISD::SSUBO, VT, Custom);
1562     setOperationAction(ISD::USUBO, VT, Custom);
1563     setOperationAction(ISD::SMULO, VT, Custom);
1564     setOperationAction(ISD::UMULO, VT, Custom);
1565   }
1566
1567   // There are no 8-bit 3-address imul/mul instructions
1568   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1569   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1570
1571   if (!Subtarget->is64Bit()) {
1572     // These libcalls are not available in 32-bit.
1573     setLibcallName(RTLIB::SHL_I128, nullptr);
1574     setLibcallName(RTLIB::SRL_I128, nullptr);
1575     setLibcallName(RTLIB::SRA_I128, nullptr);
1576   }
1577
1578   // Combine sin / cos into one node or libcall if possible.
1579   if (Subtarget->hasSinCos()) {
1580     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1581     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1582     if (Subtarget->isTargetDarwin()) {
1583       // For MacOSX, we don't want to the normal expansion of a libcall to
1584       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1585       // traffic.
1586       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1587       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1588     }
1589   }
1590
1591   if (Subtarget->isTargetWin64()) {
1592     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1593     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1594     setOperationAction(ISD::SREM, MVT::i128, Custom);
1595     setOperationAction(ISD::UREM, MVT::i128, Custom);
1596     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1597     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1598   }
1599
1600   // We have target-specific dag combine patterns for the following nodes:
1601   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1602   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1603   setTargetDAGCombine(ISD::VSELECT);
1604   setTargetDAGCombine(ISD::SELECT);
1605   setTargetDAGCombine(ISD::SHL);
1606   setTargetDAGCombine(ISD::SRA);
1607   setTargetDAGCombine(ISD::SRL);
1608   setTargetDAGCombine(ISD::OR);
1609   setTargetDAGCombine(ISD::AND);
1610   setTargetDAGCombine(ISD::ADD);
1611   setTargetDAGCombine(ISD::FADD);
1612   setTargetDAGCombine(ISD::FSUB);
1613   setTargetDAGCombine(ISD::FMA);
1614   setTargetDAGCombine(ISD::SUB);
1615   setTargetDAGCombine(ISD::LOAD);
1616   setTargetDAGCombine(ISD::STORE);
1617   setTargetDAGCombine(ISD::ZERO_EXTEND);
1618   setTargetDAGCombine(ISD::ANY_EXTEND);
1619   setTargetDAGCombine(ISD::SIGN_EXTEND);
1620   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1621   setTargetDAGCombine(ISD::TRUNCATE);
1622   setTargetDAGCombine(ISD::SINT_TO_FP);
1623   setTargetDAGCombine(ISD::SETCC);
1624   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1625   setTargetDAGCombine(ISD::BUILD_VECTOR);
1626   if (Subtarget->is64Bit())
1627     setTargetDAGCombine(ISD::MUL);
1628   setTargetDAGCombine(ISD::XOR);
1629
1630   computeRegisterProperties();
1631
1632   // On Darwin, -Os means optimize for size without hurting performance,
1633   // do not reduce the limit.
1634   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1635   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1636   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1637   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1638   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1639   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1640   setPrefLoopAlignment(4); // 2^4 bytes.
1641
1642   // Predictable cmov don't hurt on atom because it's in-order.
1643   PredictableSelectIsExpensive = !Subtarget->isAtom();
1644
1645   setPrefFunctionAlignment(4); // 2^4 bytes.
1646 }
1647
1648 // This has so far only been implemented for 64-bit MachO.
1649 bool X86TargetLowering::useLoadStackGuardNode() const {
1650   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1651          Subtarget->is64Bit();
1652 }
1653
1654 TargetLoweringBase::LegalizeTypeAction
1655 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1656   if (ExperimentalVectorWideningLegalization &&
1657       VT.getVectorNumElements() != 1 &&
1658       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1659     return TypeWidenVector;
1660
1661   return TargetLoweringBase::getPreferredVectorAction(VT);
1662 }
1663
1664 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1665   if (!VT.isVector())
1666     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1667
1668   if (Subtarget->hasAVX512())
1669     switch(VT.getVectorNumElements()) {
1670     case  8: return MVT::v8i1;
1671     case 16: return MVT::v16i1;
1672   }
1673
1674   return VT.changeVectorElementTypeToInteger();
1675 }
1676
1677 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1678 /// the desired ByVal argument alignment.
1679 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1680   if (MaxAlign == 16)
1681     return;
1682   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1683     if (VTy->getBitWidth() == 128)
1684       MaxAlign = 16;
1685   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1686     unsigned EltAlign = 0;
1687     getMaxByValAlign(ATy->getElementType(), EltAlign);
1688     if (EltAlign > MaxAlign)
1689       MaxAlign = EltAlign;
1690   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1691     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1692       unsigned EltAlign = 0;
1693       getMaxByValAlign(STy->getElementType(i), EltAlign);
1694       if (EltAlign > MaxAlign)
1695         MaxAlign = EltAlign;
1696       if (MaxAlign == 16)
1697         break;
1698     }
1699   }
1700 }
1701
1702 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1703 /// function arguments in the caller parameter area. For X86, aggregates
1704 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1705 /// are at 4-byte boundaries.
1706 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1707   if (Subtarget->is64Bit()) {
1708     // Max of 8 and alignment of type.
1709     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1710     if (TyAlign > 8)
1711       return TyAlign;
1712     return 8;
1713   }
1714
1715   unsigned Align = 4;
1716   if (Subtarget->hasSSE1())
1717     getMaxByValAlign(Ty, Align);
1718   return Align;
1719 }
1720
1721 /// getOptimalMemOpType - Returns the target specific optimal type for load
1722 /// and store operations as a result of memset, memcpy, and memmove
1723 /// lowering. If DstAlign is zero that means it's safe to destination
1724 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1725 /// means there isn't a need to check it against alignment requirement,
1726 /// probably because the source does not need to be loaded. If 'IsMemset' is
1727 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1728 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1729 /// source is constant so it does not need to be loaded.
1730 /// It returns EVT::Other if the type should be determined using generic
1731 /// target-independent logic.
1732 EVT
1733 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1734                                        unsigned DstAlign, unsigned SrcAlign,
1735                                        bool IsMemset, bool ZeroMemset,
1736                                        bool MemcpyStrSrc,
1737                                        MachineFunction &MF) const {
1738   const Function *F = MF.getFunction();
1739   if ((!IsMemset || ZeroMemset) &&
1740       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1741                                        Attribute::NoImplicitFloat)) {
1742     if (Size >= 16 &&
1743         (Subtarget->isUnalignedMemAccessFast() ||
1744          ((DstAlign == 0 || DstAlign >= 16) &&
1745           (SrcAlign == 0 || SrcAlign >= 16)))) {
1746       if (Size >= 32) {
1747         if (Subtarget->hasInt256())
1748           return MVT::v8i32;
1749         if (Subtarget->hasFp256())
1750           return MVT::v8f32;
1751       }
1752       if (Subtarget->hasSSE2())
1753         return MVT::v4i32;
1754       if (Subtarget->hasSSE1())
1755         return MVT::v4f32;
1756     } else if (!MemcpyStrSrc && Size >= 8 &&
1757                !Subtarget->is64Bit() &&
1758                Subtarget->hasSSE2()) {
1759       // Do not use f64 to lower memcpy if source is string constant. It's
1760       // better to use i32 to avoid the loads.
1761       return MVT::f64;
1762     }
1763   }
1764   if (Subtarget->is64Bit() && Size >= 8)
1765     return MVT::i64;
1766   return MVT::i32;
1767 }
1768
1769 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1770   if (VT == MVT::f32)
1771     return X86ScalarSSEf32;
1772   else if (VT == MVT::f64)
1773     return X86ScalarSSEf64;
1774   return true;
1775 }
1776
1777 bool
1778 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1779                                                   unsigned,
1780                                                   unsigned,
1781                                                   bool *Fast) const {
1782   if (Fast)
1783     *Fast = Subtarget->isUnalignedMemAccessFast();
1784   return true;
1785 }
1786
1787 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1788 /// current function.  The returned value is a member of the
1789 /// MachineJumpTableInfo::JTEntryKind enum.
1790 unsigned X86TargetLowering::getJumpTableEncoding() const {
1791   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1792   // symbol.
1793   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1794       Subtarget->isPICStyleGOT())
1795     return MachineJumpTableInfo::EK_Custom32;
1796
1797   // Otherwise, use the normal jump table encoding heuristics.
1798   return TargetLowering::getJumpTableEncoding();
1799 }
1800
1801 const MCExpr *
1802 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1803                                              const MachineBasicBlock *MBB,
1804                                              unsigned uid,MCContext &Ctx) const{
1805   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1806          Subtarget->isPICStyleGOT());
1807   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1808   // entries.
1809   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1810                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1811 }
1812
1813 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1814 /// jumptable.
1815 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1816                                                     SelectionDAG &DAG) const {
1817   if (!Subtarget->is64Bit())
1818     // This doesn't have SDLoc associated with it, but is not really the
1819     // same as a Register.
1820     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1821   return Table;
1822 }
1823
1824 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1825 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1826 /// MCExpr.
1827 const MCExpr *X86TargetLowering::
1828 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1829                              MCContext &Ctx) const {
1830   // X86-64 uses RIP relative addressing based on the jump table label.
1831   if (Subtarget->isPICStyleRIPRel())
1832     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1833
1834   // Otherwise, the reference is relative to the PIC base.
1835   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1836 }
1837
1838 // FIXME: Why this routine is here? Move to RegInfo!
1839 std::pair<const TargetRegisterClass*, uint8_t>
1840 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1841   const TargetRegisterClass *RRC = nullptr;
1842   uint8_t Cost = 1;
1843   switch (VT.SimpleTy) {
1844   default:
1845     return TargetLowering::findRepresentativeClass(VT);
1846   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1847     RRC = Subtarget->is64Bit() ?
1848       (const TargetRegisterClass*)&X86::GR64RegClass :
1849       (const TargetRegisterClass*)&X86::GR32RegClass;
1850     break;
1851   case MVT::x86mmx:
1852     RRC = &X86::VR64RegClass;
1853     break;
1854   case MVT::f32: case MVT::f64:
1855   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1856   case MVT::v4f32: case MVT::v2f64:
1857   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1858   case MVT::v4f64:
1859     RRC = &X86::VR128RegClass;
1860     break;
1861   }
1862   return std::make_pair(RRC, Cost);
1863 }
1864
1865 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1866                                                unsigned &Offset) const {
1867   if (!Subtarget->isTargetLinux())
1868     return false;
1869
1870   if (Subtarget->is64Bit()) {
1871     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1872     Offset = 0x28;
1873     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1874       AddressSpace = 256;
1875     else
1876       AddressSpace = 257;
1877   } else {
1878     // %gs:0x14 on i386
1879     Offset = 0x14;
1880     AddressSpace = 256;
1881   }
1882   return true;
1883 }
1884
1885 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1886                                             unsigned DestAS) const {
1887   assert(SrcAS != DestAS && "Expected different address spaces!");
1888
1889   return SrcAS < 256 && DestAS < 256;
1890 }
1891
1892 //===----------------------------------------------------------------------===//
1893 //               Return Value Calling Convention Implementation
1894 //===----------------------------------------------------------------------===//
1895
1896 #include "X86GenCallingConv.inc"
1897
1898 bool
1899 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1900                                   MachineFunction &MF, bool isVarArg,
1901                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1902                         LLVMContext &Context) const {
1903   SmallVector<CCValAssign, 16> RVLocs;
1904   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1905                  RVLocs, Context);
1906   return CCInfo.CheckReturn(Outs, RetCC_X86);
1907 }
1908
1909 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1910   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1911   return ScratchRegs;
1912 }
1913
1914 SDValue
1915 X86TargetLowering::LowerReturn(SDValue Chain,
1916                                CallingConv::ID CallConv, bool isVarArg,
1917                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1918                                const SmallVectorImpl<SDValue> &OutVals,
1919                                SDLoc dl, SelectionDAG &DAG) const {
1920   MachineFunction &MF = DAG.getMachineFunction();
1921   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1922
1923   SmallVector<CCValAssign, 16> RVLocs;
1924   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1925                  RVLocs, *DAG.getContext());
1926   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1927
1928   SDValue Flag;
1929   SmallVector<SDValue, 6> RetOps;
1930   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1931   // Operand #1 = Bytes To Pop
1932   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1933                    MVT::i16));
1934
1935   // Copy the result values into the output registers.
1936   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1937     CCValAssign &VA = RVLocs[i];
1938     assert(VA.isRegLoc() && "Can only return in registers!");
1939     SDValue ValToCopy = OutVals[i];
1940     EVT ValVT = ValToCopy.getValueType();
1941
1942     // Promote values to the appropriate types
1943     if (VA.getLocInfo() == CCValAssign::SExt)
1944       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1945     else if (VA.getLocInfo() == CCValAssign::ZExt)
1946       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947     else if (VA.getLocInfo() == CCValAssign::AExt)
1948       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1949     else if (VA.getLocInfo() == CCValAssign::BCvt)
1950       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1951
1952     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1953            "Unexpected FP-extend for return value.");  
1954
1955     // If this is x86-64, and we disabled SSE, we can't return FP values,
1956     // or SSE or MMX vectors.
1957     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1958          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1959           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1960       report_fatal_error("SSE register return with SSE disabled");
1961     }
1962     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1963     // llvm-gcc has never done it right and no one has noticed, so this
1964     // should be OK for now.
1965     if (ValVT == MVT::f64 &&
1966         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1967       report_fatal_error("SSE2 register return with SSE2 disabled");
1968
1969     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1970     // the RET instruction and handled by the FP Stackifier.
1971     if (VA.getLocReg() == X86::FP0 ||
1972         VA.getLocReg() == X86::FP1) {
1973       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1974       // change the value to the FP stack register class.
1975       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1976         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1977       RetOps.push_back(ValToCopy);
1978       // Don't emit a copytoreg.
1979       continue;
1980     }
1981
1982     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1983     // which is returned in RAX / RDX.
1984     if (Subtarget->is64Bit()) {
1985       if (ValVT == MVT::x86mmx) {
1986         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1987           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1988           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1989                                   ValToCopy);
1990           // If we don't have SSE2 available, convert to v4f32 so the generated
1991           // register is legal.
1992           if (!Subtarget->hasSSE2())
1993             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1994         }
1995       }
1996     }
1997
1998     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1999     Flag = Chain.getValue(1);
2000     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2001   }
2002
2003   // The x86-64 ABIs require that for returning structs by value we copy
2004   // the sret argument into %rax/%eax (depending on ABI) for the return.
2005   // Win32 requires us to put the sret argument to %eax as well.
2006   // We saved the argument into a virtual register in the entry block,
2007   // so now we copy the value out and into %rax/%eax.
2008   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2009       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2010     MachineFunction &MF = DAG.getMachineFunction();
2011     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2012     unsigned Reg = FuncInfo->getSRetReturnReg();
2013     assert(Reg &&
2014            "SRetReturnReg should have been set in LowerFormalArguments().");
2015     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2016
2017     unsigned RetValReg
2018         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2019           X86::RAX : X86::EAX;
2020     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2021     Flag = Chain.getValue(1);
2022
2023     // RAX/EAX now acts like a return value.
2024     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2025   }
2026
2027   RetOps[0] = Chain;  // Update chain.
2028
2029   // Add the flag if we have it.
2030   if (Flag.getNode())
2031     RetOps.push_back(Flag);
2032
2033   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2034 }
2035
2036 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2037   if (N->getNumValues() != 1)
2038     return false;
2039   if (!N->hasNUsesOfValue(1, 0))
2040     return false;
2041
2042   SDValue TCChain = Chain;
2043   SDNode *Copy = *N->use_begin();
2044   if (Copy->getOpcode() == ISD::CopyToReg) {
2045     // If the copy has a glue operand, we conservatively assume it isn't safe to
2046     // perform a tail call.
2047     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2048       return false;
2049     TCChain = Copy->getOperand(0);
2050   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2051     return false;
2052
2053   bool HasRet = false;
2054   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2055        UI != UE; ++UI) {
2056     if (UI->getOpcode() != X86ISD::RET_FLAG)
2057       return false;
2058     HasRet = true;
2059   }
2060
2061   if (!HasRet)
2062     return false;
2063
2064   Chain = TCChain;
2065   return true;
2066 }
2067
2068 MVT
2069 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2070                                             ISD::NodeType ExtendKind) const {
2071   MVT ReturnMVT;
2072   // TODO: Is this also valid on 32-bit?
2073   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2074     ReturnMVT = MVT::i8;
2075   else
2076     ReturnMVT = MVT::i32;
2077
2078   MVT MinVT = getRegisterType(ReturnMVT);
2079   return VT.bitsLT(MinVT) ? MinVT : VT;
2080 }
2081
2082 /// LowerCallResult - Lower the result values of a call into the
2083 /// appropriate copies out of appropriate physical registers.
2084 ///
2085 SDValue
2086 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2087                                    CallingConv::ID CallConv, bool isVarArg,
2088                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2089                                    SDLoc dl, SelectionDAG &DAG,
2090                                    SmallVectorImpl<SDValue> &InVals) const {
2091
2092   // Assign locations to each value returned by this call.
2093   SmallVector<CCValAssign, 16> RVLocs;
2094   bool Is64Bit = Subtarget->is64Bit();
2095   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2096                  DAG.getTarget(), RVLocs, *DAG.getContext());
2097   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2098
2099   // Copy all of the result registers out of their specified physreg.
2100   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2101     CCValAssign &VA = RVLocs[i];
2102     EVT CopyVT = VA.getValVT();
2103
2104     // If this is x86-64, and we disabled SSE, we can't return FP values
2105     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2106         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2107       report_fatal_error("SSE register return with SSE disabled");
2108     }
2109
2110     // If we prefer to use the value in xmm registers, copy it out as f80 and
2111     // use a truncate to move it from fp stack reg to xmm reg.
2112     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2113         isScalarFPTypeInSSEReg(VA.getValVT()))
2114       CopyVT = MVT::f80;
2115
2116     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2117                                CopyVT, InFlag).getValue(1);
2118     SDValue Val = Chain.getValue(0);
2119
2120     if (CopyVT != VA.getValVT())
2121       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2122                         // This truncation won't change the value.
2123                         DAG.getIntPtrConstant(1));
2124
2125     InFlag = Chain.getValue(2);
2126     InVals.push_back(Val);
2127   }
2128
2129   return Chain;
2130 }
2131
2132 //===----------------------------------------------------------------------===//
2133 //                C & StdCall & Fast Calling Convention implementation
2134 //===----------------------------------------------------------------------===//
2135 //  StdCall calling convention seems to be standard for many Windows' API
2136 //  routines and around. It differs from C calling convention just a little:
2137 //  callee should clean up the stack, not caller. Symbols should be also
2138 //  decorated in some fancy way :) It doesn't support any vector arguments.
2139 //  For info on fast calling convention see Fast Calling Convention (tail call)
2140 //  implementation LowerX86_32FastCCCallTo.
2141
2142 /// CallIsStructReturn - Determines whether a call uses struct return
2143 /// semantics.
2144 enum StructReturnType {
2145   NotStructReturn,
2146   RegStructReturn,
2147   StackStructReturn
2148 };
2149 static StructReturnType
2150 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2151   if (Outs.empty())
2152     return NotStructReturn;
2153
2154   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2155   if (!Flags.isSRet())
2156     return NotStructReturn;
2157   if (Flags.isInReg())
2158     return RegStructReturn;
2159   return StackStructReturn;
2160 }
2161
2162 /// ArgsAreStructReturn - Determines whether a function uses struct
2163 /// return semantics.
2164 static StructReturnType
2165 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2166   if (Ins.empty())
2167     return NotStructReturn;
2168
2169   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2170   if (!Flags.isSRet())
2171     return NotStructReturn;
2172   if (Flags.isInReg())
2173     return RegStructReturn;
2174   return StackStructReturn;
2175 }
2176
2177 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2178 /// by "Src" to address "Dst" with size and alignment information specified by
2179 /// the specific parameter attribute. The copy will be passed as a byval
2180 /// function parameter.
2181 static SDValue
2182 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2183                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2184                           SDLoc dl) {
2185   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2186
2187   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2188                        /*isVolatile*/false, /*AlwaysInline=*/true,
2189                        MachinePointerInfo(), MachinePointerInfo());
2190 }
2191
2192 /// IsTailCallConvention - Return true if the calling convention is one that
2193 /// supports tail call optimization.
2194 static bool IsTailCallConvention(CallingConv::ID CC) {
2195   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2196           CC == CallingConv::HiPE);
2197 }
2198
2199 /// \brief Return true if the calling convention is a C calling convention.
2200 static bool IsCCallConvention(CallingConv::ID CC) {
2201   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2202           CC == CallingConv::X86_64_SysV);
2203 }
2204
2205 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2206   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2207     return false;
2208
2209   CallSite CS(CI);
2210   CallingConv::ID CalleeCC = CS.getCallingConv();
2211   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2212     return false;
2213
2214   return true;
2215 }
2216
2217 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2218 /// a tailcall target by changing its ABI.
2219 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2220                                    bool GuaranteedTailCallOpt) {
2221   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2222 }
2223
2224 SDValue
2225 X86TargetLowering::LowerMemArgument(SDValue Chain,
2226                                     CallingConv::ID CallConv,
2227                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2228                                     SDLoc dl, SelectionDAG &DAG,
2229                                     const CCValAssign &VA,
2230                                     MachineFrameInfo *MFI,
2231                                     unsigned i) const {
2232   // Create the nodes corresponding to a load from this parameter slot.
2233   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2234   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2235       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2236   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2237   EVT ValVT;
2238
2239   // If value is passed by pointer we have address passed instead of the value
2240   // itself.
2241   if (VA.getLocInfo() == CCValAssign::Indirect)
2242     ValVT = VA.getLocVT();
2243   else
2244     ValVT = VA.getValVT();
2245
2246   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2247   // changed with more analysis.
2248   // In case of tail call optimization mark all arguments mutable. Since they
2249   // could be overwritten by lowering of arguments in case of a tail call.
2250   if (Flags.isByVal()) {
2251     unsigned Bytes = Flags.getByValSize();
2252     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2253     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2254     return DAG.getFrameIndex(FI, getPointerTy());
2255   } else {
2256     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2257                                     VA.getLocMemOffset(), isImmutable);
2258     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2259     return DAG.getLoad(ValVT, dl, Chain, FIN,
2260                        MachinePointerInfo::getFixedStack(FI),
2261                        false, false, false, 0);
2262   }
2263 }
2264
2265 SDValue
2266 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2267                                         CallingConv::ID CallConv,
2268                                         bool isVarArg,
2269                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2270                                         SDLoc dl,
2271                                         SelectionDAG &DAG,
2272                                         SmallVectorImpl<SDValue> &InVals)
2273                                           const {
2274   MachineFunction &MF = DAG.getMachineFunction();
2275   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2276
2277   const Function* Fn = MF.getFunction();
2278   if (Fn->hasExternalLinkage() &&
2279       Subtarget->isTargetCygMing() &&
2280       Fn->getName() == "main")
2281     FuncInfo->setForceFramePointer(true);
2282
2283   MachineFrameInfo *MFI = MF.getFrameInfo();
2284   bool Is64Bit = Subtarget->is64Bit();
2285   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2286
2287   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2288          "Var args not supported with calling convention fastcc, ghc or hipe");
2289
2290   // Assign locations to all of the incoming arguments.
2291   SmallVector<CCValAssign, 16> ArgLocs;
2292   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2293                  ArgLocs, *DAG.getContext());
2294
2295   // Allocate shadow area for Win64
2296   if (IsWin64)
2297     CCInfo.AllocateStack(32, 8);
2298
2299   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2300
2301   unsigned LastVal = ~0U;
2302   SDValue ArgValue;
2303   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2304     CCValAssign &VA = ArgLocs[i];
2305     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2306     // places.
2307     assert(VA.getValNo() != LastVal &&
2308            "Don't support value assigned to multiple locs yet");
2309     (void)LastVal;
2310     LastVal = VA.getValNo();
2311
2312     if (VA.isRegLoc()) {
2313       EVT RegVT = VA.getLocVT();
2314       const TargetRegisterClass *RC;
2315       if (RegVT == MVT::i32)
2316         RC = &X86::GR32RegClass;
2317       else if (Is64Bit && RegVT == MVT::i64)
2318         RC = &X86::GR64RegClass;
2319       else if (RegVT == MVT::f32)
2320         RC = &X86::FR32RegClass;
2321       else if (RegVT == MVT::f64)
2322         RC = &X86::FR64RegClass;
2323       else if (RegVT.is512BitVector())
2324         RC = &X86::VR512RegClass;
2325       else if (RegVT.is256BitVector())
2326         RC = &X86::VR256RegClass;
2327       else if (RegVT.is128BitVector())
2328         RC = &X86::VR128RegClass;
2329       else if (RegVT == MVT::x86mmx)
2330         RC = &X86::VR64RegClass;
2331       else if (RegVT == MVT::i1)
2332         RC = &X86::VK1RegClass;
2333       else if (RegVT == MVT::v8i1)
2334         RC = &X86::VK8RegClass;
2335       else if (RegVT == MVT::v16i1)
2336         RC = &X86::VK16RegClass;
2337       else if (RegVT == MVT::v32i1)
2338         RC = &X86::VK32RegClass;
2339       else if (RegVT == MVT::v64i1)
2340         RC = &X86::VK64RegClass;
2341       else
2342         llvm_unreachable("Unknown argument type!");
2343
2344       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2345       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2346
2347       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2348       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2349       // right size.
2350       if (VA.getLocInfo() == CCValAssign::SExt)
2351         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2352                                DAG.getValueType(VA.getValVT()));
2353       else if (VA.getLocInfo() == CCValAssign::ZExt)
2354         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2355                                DAG.getValueType(VA.getValVT()));
2356       else if (VA.getLocInfo() == CCValAssign::BCvt)
2357         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2358
2359       if (VA.isExtInLoc()) {
2360         // Handle MMX values passed in XMM regs.
2361         if (RegVT.isVector())
2362           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2363         else
2364           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2365       }
2366     } else {
2367       assert(VA.isMemLoc());
2368       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2369     }
2370
2371     // If value is passed via pointer - do a load.
2372     if (VA.getLocInfo() == CCValAssign::Indirect)
2373       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2374                              MachinePointerInfo(), false, false, false, 0);
2375
2376     InVals.push_back(ArgValue);
2377   }
2378
2379   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2380     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2381       // The x86-64 ABIs require that for returning structs by value we copy
2382       // the sret argument into %rax/%eax (depending on ABI) for the return.
2383       // Win32 requires us to put the sret argument to %eax as well.
2384       // Save the argument into a virtual register so that we can access it
2385       // from the return points.
2386       if (Ins[i].Flags.isSRet()) {
2387         unsigned Reg = FuncInfo->getSRetReturnReg();
2388         if (!Reg) {
2389           MVT PtrTy = getPointerTy();
2390           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2391           FuncInfo->setSRetReturnReg(Reg);
2392         }
2393         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2394         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2395         break;
2396       }
2397     }
2398   }
2399
2400   unsigned StackSize = CCInfo.getNextStackOffset();
2401   // Align stack specially for tail calls.
2402   if (FuncIsMadeTailCallSafe(CallConv,
2403                              MF.getTarget().Options.GuaranteedTailCallOpt))
2404     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2405
2406   // If the function takes variable number of arguments, make a frame index for
2407   // the start of the first vararg value... for expansion of llvm.va_start.
2408   if (isVarArg) {
2409     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2410                     CallConv != CallingConv::X86_ThisCall)) {
2411       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2412     }
2413     if (Is64Bit) {
2414       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2415
2416       // FIXME: We should really autogenerate these arrays
2417       static const MCPhysReg GPR64ArgRegsWin64[] = {
2418         X86::RCX, X86::RDX, X86::R8,  X86::R9
2419       };
2420       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2421         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2422       };
2423       static const MCPhysReg XMMArgRegs64Bit[] = {
2424         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2425         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2426       };
2427       const MCPhysReg *GPR64ArgRegs;
2428       unsigned NumXMMRegs = 0;
2429
2430       if (IsWin64) {
2431         // The XMM registers which might contain var arg parameters are shadowed
2432         // in their paired GPR.  So we only need to save the GPR to their home
2433         // slots.
2434         TotalNumIntRegs = 4;
2435         GPR64ArgRegs = GPR64ArgRegsWin64;
2436       } else {
2437         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2438         GPR64ArgRegs = GPR64ArgRegs64Bit;
2439
2440         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2441                                                 TotalNumXMMRegs);
2442       }
2443       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2444                                                        TotalNumIntRegs);
2445
2446       bool NoImplicitFloatOps = Fn->getAttributes().
2447         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2448       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2449              "SSE register cannot be used when SSE is disabled!");
2450       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2451                NoImplicitFloatOps) &&
2452              "SSE register cannot be used when SSE is disabled!");
2453       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2454           !Subtarget->hasSSE1())
2455         // Kernel mode asks for SSE to be disabled, so don't push them
2456         // on the stack.
2457         TotalNumXMMRegs = 0;
2458
2459       if (IsWin64) {
2460         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2461         // Get to the caller-allocated home save location.  Add 8 to account
2462         // for the return address.
2463         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2464         FuncInfo->setRegSaveFrameIndex(
2465           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2466         // Fixup to set vararg frame on shadow area (4 x i64).
2467         if (NumIntRegs < 4)
2468           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2469       } else {
2470         // For X86-64, if there are vararg parameters that are passed via
2471         // registers, then we must store them to their spots on the stack so
2472         // they may be loaded by deferencing the result of va_next.
2473         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2474         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2475         FuncInfo->setRegSaveFrameIndex(
2476           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2477                                false));
2478       }
2479
2480       // Store the integer parameter registers.
2481       SmallVector<SDValue, 8> MemOps;
2482       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2483                                         getPointerTy());
2484       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2485       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2486         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2487                                   DAG.getIntPtrConstant(Offset));
2488         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2489                                      &X86::GR64RegClass);
2490         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2491         SDValue Store =
2492           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2493                        MachinePointerInfo::getFixedStack(
2494                          FuncInfo->getRegSaveFrameIndex(), Offset),
2495                        false, false, 0);
2496         MemOps.push_back(Store);
2497         Offset += 8;
2498       }
2499
2500       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2501         // Now store the XMM (fp + vector) parameter registers.
2502         SmallVector<SDValue, 11> SaveXMMOps;
2503         SaveXMMOps.push_back(Chain);
2504
2505         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2506         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2507         SaveXMMOps.push_back(ALVal);
2508
2509         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2510                                FuncInfo->getRegSaveFrameIndex()));
2511         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2512                                FuncInfo->getVarArgsFPOffset()));
2513
2514         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2515           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2516                                        &X86::VR128RegClass);
2517           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2518           SaveXMMOps.push_back(Val);
2519         }
2520         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2521                                      MVT::Other, SaveXMMOps));
2522       }
2523
2524       if (!MemOps.empty())
2525         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2526     }
2527   }
2528
2529   // Some CCs need callee pop.
2530   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2531                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2532     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2533   } else {
2534     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2535     // If this is an sret function, the return should pop the hidden pointer.
2536     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2537         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2538         argsAreStructReturn(Ins) == StackStructReturn)
2539       FuncInfo->setBytesToPopOnReturn(4);
2540   }
2541
2542   if (!Is64Bit) {
2543     // RegSaveFrameIndex is X86-64 only.
2544     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2545     if (CallConv == CallingConv::X86_FastCall ||
2546         CallConv == CallingConv::X86_ThisCall)
2547       // fastcc functions can't have varargs.
2548       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2549   }
2550
2551   FuncInfo->setArgumentStackSize(StackSize);
2552
2553   return Chain;
2554 }
2555
2556 SDValue
2557 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2558                                     SDValue StackPtr, SDValue Arg,
2559                                     SDLoc dl, SelectionDAG &DAG,
2560                                     const CCValAssign &VA,
2561                                     ISD::ArgFlagsTy Flags) const {
2562   unsigned LocMemOffset = VA.getLocMemOffset();
2563   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2564   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2565   if (Flags.isByVal())
2566     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2567
2568   return DAG.getStore(Chain, dl, Arg, PtrOff,
2569                       MachinePointerInfo::getStack(LocMemOffset),
2570                       false, false, 0);
2571 }
2572
2573 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2574 /// optimization is performed and it is required.
2575 SDValue
2576 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2577                                            SDValue &OutRetAddr, SDValue Chain,
2578                                            bool IsTailCall, bool Is64Bit,
2579                                            int FPDiff, SDLoc dl) const {
2580   // Adjust the Return address stack slot.
2581   EVT VT = getPointerTy();
2582   OutRetAddr = getReturnAddressFrameIndex(DAG);
2583
2584   // Load the "old" Return address.
2585   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2586                            false, false, false, 0);
2587   return SDValue(OutRetAddr.getNode(), 1);
2588 }
2589
2590 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2591 /// optimization is performed and it is required (FPDiff!=0).
2592 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2593                                         SDValue Chain, SDValue RetAddrFrIdx,
2594                                         EVT PtrVT, unsigned SlotSize,
2595                                         int FPDiff, SDLoc dl) {
2596   // Store the return address to the appropriate stack slot.
2597   if (!FPDiff) return Chain;
2598   // Calculate the new stack slot for the return address.
2599   int NewReturnAddrFI =
2600     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2601                                          false);
2602   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2603   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2604                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2605                        false, false, 0);
2606   return Chain;
2607 }
2608
2609 SDValue
2610 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2611                              SmallVectorImpl<SDValue> &InVals) const {
2612   SelectionDAG &DAG                     = CLI.DAG;
2613   SDLoc &dl                             = CLI.DL;
2614   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2615   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2616   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2617   SDValue Chain                         = CLI.Chain;
2618   SDValue Callee                        = CLI.Callee;
2619   CallingConv::ID CallConv              = CLI.CallConv;
2620   bool &isTailCall                      = CLI.IsTailCall;
2621   bool isVarArg                         = CLI.IsVarArg;
2622
2623   MachineFunction &MF = DAG.getMachineFunction();
2624   bool Is64Bit        = Subtarget->is64Bit();
2625   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2626   StructReturnType SR = callIsStructReturn(Outs);
2627   bool IsSibcall      = false;
2628
2629   if (MF.getTarget().Options.DisableTailCalls)
2630     isTailCall = false;
2631
2632   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2633   if (IsMustTail) {
2634     // Force this to be a tail call.  The verifier rules are enough to ensure
2635     // that we can lower this successfully without moving the return address
2636     // around.
2637     isTailCall = true;
2638   } else if (isTailCall) {
2639     // Check if it's really possible to do a tail call.
2640     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2641                     isVarArg, SR != NotStructReturn,
2642                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2643                     Outs, OutVals, Ins, DAG);
2644
2645     // Sibcalls are automatically detected tailcalls which do not require
2646     // ABI changes.
2647     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2648       IsSibcall = true;
2649
2650     if (isTailCall)
2651       ++NumTailCalls;
2652   }
2653
2654   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2655          "Var args not supported with calling convention fastcc, ghc or hipe");
2656
2657   // Analyze operands of the call, assigning locations to each operand.
2658   SmallVector<CCValAssign, 16> ArgLocs;
2659   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2660                  ArgLocs, *DAG.getContext());
2661
2662   // Allocate shadow area for Win64
2663   if (IsWin64)
2664     CCInfo.AllocateStack(32, 8);
2665
2666   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2667
2668   // Get a count of how many bytes are to be pushed on the stack.
2669   unsigned NumBytes = CCInfo.getNextStackOffset();
2670   if (IsSibcall)
2671     // This is a sibcall. The memory operands are available in caller's
2672     // own caller's stack.
2673     NumBytes = 0;
2674   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2675            IsTailCallConvention(CallConv))
2676     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2677
2678   int FPDiff = 0;
2679   if (isTailCall && !IsSibcall && !IsMustTail) {
2680     // Lower arguments at fp - stackoffset + fpdiff.
2681     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2682     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2683
2684     FPDiff = NumBytesCallerPushed - NumBytes;
2685
2686     // Set the delta of movement of the returnaddr stackslot.
2687     // But only set if delta is greater than previous delta.
2688     if (FPDiff < X86Info->getTCReturnAddrDelta())
2689       X86Info->setTCReturnAddrDelta(FPDiff);
2690   }
2691
2692   unsigned NumBytesToPush = NumBytes;
2693   unsigned NumBytesToPop = NumBytes;
2694
2695   // If we have an inalloca argument, all stack space has already been allocated
2696   // for us and be right at the top of the stack.  We don't support multiple
2697   // arguments passed in memory when using inalloca.
2698   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2699     NumBytesToPush = 0;
2700     if (!ArgLocs.back().isMemLoc())
2701       report_fatal_error("cannot use inalloca attribute on a register "
2702                          "parameter");
2703     if (ArgLocs.back().getLocMemOffset() != 0)
2704       report_fatal_error("any parameter with the inalloca attribute must be "
2705                          "the only memory argument");
2706   }
2707
2708   if (!IsSibcall)
2709     Chain = DAG.getCALLSEQ_START(
2710         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2711
2712   SDValue RetAddrFrIdx;
2713   // Load return address for tail calls.
2714   if (isTailCall && FPDiff)
2715     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2716                                     Is64Bit, FPDiff, dl);
2717
2718   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2719   SmallVector<SDValue, 8> MemOpChains;
2720   SDValue StackPtr;
2721
2722   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2723   // of tail call optimization arguments are handle later.
2724   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2725       DAG.getSubtarget().getRegisterInfo());
2726   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2727     // Skip inalloca arguments, they have already been written.
2728     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2729     if (Flags.isInAlloca())
2730       continue;
2731
2732     CCValAssign &VA = ArgLocs[i];
2733     EVT RegVT = VA.getLocVT();
2734     SDValue Arg = OutVals[i];
2735     bool isByVal = Flags.isByVal();
2736
2737     // Promote the value if needed.
2738     switch (VA.getLocInfo()) {
2739     default: llvm_unreachable("Unknown loc info!");
2740     case CCValAssign::Full: break;
2741     case CCValAssign::SExt:
2742       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2743       break;
2744     case CCValAssign::ZExt:
2745       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2746       break;
2747     case CCValAssign::AExt:
2748       if (RegVT.is128BitVector()) {
2749         // Special case: passing MMX values in XMM registers.
2750         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2751         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2752         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2753       } else
2754         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2755       break;
2756     case CCValAssign::BCvt:
2757       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2758       break;
2759     case CCValAssign::Indirect: {
2760       // Store the argument.
2761       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2762       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2763       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2764                            MachinePointerInfo::getFixedStack(FI),
2765                            false, false, 0);
2766       Arg = SpillSlot;
2767       break;
2768     }
2769     }
2770
2771     if (VA.isRegLoc()) {
2772       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2773       if (isVarArg && IsWin64) {
2774         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2775         // shadow reg if callee is a varargs function.
2776         unsigned ShadowReg = 0;
2777         switch (VA.getLocReg()) {
2778         case X86::XMM0: ShadowReg = X86::RCX; break;
2779         case X86::XMM1: ShadowReg = X86::RDX; break;
2780         case X86::XMM2: ShadowReg = X86::R8; break;
2781         case X86::XMM3: ShadowReg = X86::R9; break;
2782         }
2783         if (ShadowReg)
2784           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2785       }
2786     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2787       assert(VA.isMemLoc());
2788       if (!StackPtr.getNode())
2789         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2790                                       getPointerTy());
2791       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2792                                              dl, DAG, VA, Flags));
2793     }
2794   }
2795
2796   if (!MemOpChains.empty())
2797     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2798
2799   if (Subtarget->isPICStyleGOT()) {
2800     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2801     // GOT pointer.
2802     if (!isTailCall) {
2803       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2804                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2805     } else {
2806       // If we are tail calling and generating PIC/GOT style code load the
2807       // address of the callee into ECX. The value in ecx is used as target of
2808       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2809       // for tail calls on PIC/GOT architectures. Normally we would just put the
2810       // address of GOT into ebx and then call target@PLT. But for tail calls
2811       // ebx would be restored (since ebx is callee saved) before jumping to the
2812       // target@PLT.
2813
2814       // Note: The actual moving to ECX is done further down.
2815       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2816       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2817           !G->getGlobal()->hasProtectedVisibility())
2818         Callee = LowerGlobalAddress(Callee, DAG);
2819       else if (isa<ExternalSymbolSDNode>(Callee))
2820         Callee = LowerExternalSymbol(Callee, DAG);
2821     }
2822   }
2823
2824   if (Is64Bit && isVarArg && !IsWin64) {
2825     // From AMD64 ABI document:
2826     // For calls that may call functions that use varargs or stdargs
2827     // (prototype-less calls or calls to functions containing ellipsis (...) in
2828     // the declaration) %al is used as hidden argument to specify the number
2829     // of SSE registers used. The contents of %al do not need to match exactly
2830     // the number of registers, but must be an ubound on the number of SSE
2831     // registers used and is in the range 0 - 8 inclusive.
2832
2833     // Count the number of XMM registers allocated.
2834     static const MCPhysReg XMMArgRegs[] = {
2835       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2836       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2837     };
2838     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2839     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2840            && "SSE registers cannot be used when SSE is disabled");
2841
2842     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2843                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2844   }
2845
2846   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2847   // don't need this because the eligibility check rejects calls that require
2848   // shuffling arguments passed in memory.
2849   if (!IsSibcall && isTailCall) {
2850     // Force all the incoming stack arguments to be loaded from the stack
2851     // before any new outgoing arguments are stored to the stack, because the
2852     // outgoing stack slots may alias the incoming argument stack slots, and
2853     // the alias isn't otherwise explicit. This is slightly more conservative
2854     // than necessary, because it means that each store effectively depends
2855     // on every argument instead of just those arguments it would clobber.
2856     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2857
2858     SmallVector<SDValue, 8> MemOpChains2;
2859     SDValue FIN;
2860     int FI = 0;
2861     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2862       CCValAssign &VA = ArgLocs[i];
2863       if (VA.isRegLoc())
2864         continue;
2865       assert(VA.isMemLoc());
2866       SDValue Arg = OutVals[i];
2867       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2868       // Skip inalloca arguments.  They don't require any work.
2869       if (Flags.isInAlloca())
2870         continue;
2871       // Create frame index.
2872       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2873       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2874       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2875       FIN = DAG.getFrameIndex(FI, getPointerTy());
2876
2877       if (Flags.isByVal()) {
2878         // Copy relative to framepointer.
2879         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2880         if (!StackPtr.getNode())
2881           StackPtr = DAG.getCopyFromReg(Chain, dl,
2882                                         RegInfo->getStackRegister(),
2883                                         getPointerTy());
2884         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2885
2886         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2887                                                          ArgChain,
2888                                                          Flags, DAG, dl));
2889       } else {
2890         // Store relative to framepointer.
2891         MemOpChains2.push_back(
2892           DAG.getStore(ArgChain, dl, Arg, FIN,
2893                        MachinePointerInfo::getFixedStack(FI),
2894                        false, false, 0));
2895       }
2896     }
2897
2898     if (!MemOpChains2.empty())
2899       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2900
2901     // Store the return address to the appropriate stack slot.
2902     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2903                                      getPointerTy(), RegInfo->getSlotSize(),
2904                                      FPDiff, dl);
2905   }
2906
2907   // Build a sequence of copy-to-reg nodes chained together with token chain
2908   // and flag operands which copy the outgoing args into registers.
2909   SDValue InFlag;
2910   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2911     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2912                              RegsToPass[i].second, InFlag);
2913     InFlag = Chain.getValue(1);
2914   }
2915
2916   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2917     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2918     // In the 64-bit large code model, we have to make all calls
2919     // through a register, since the call instruction's 32-bit
2920     // pc-relative offset may not be large enough to hold the whole
2921     // address.
2922   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2923     // If the callee is a GlobalAddress node (quite common, every direct call
2924     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2925     // it.
2926
2927     // We should use extra load for direct calls to dllimported functions in
2928     // non-JIT mode.
2929     const GlobalValue *GV = G->getGlobal();
2930     if (!GV->hasDLLImportStorageClass()) {
2931       unsigned char OpFlags = 0;
2932       bool ExtraLoad = false;
2933       unsigned WrapperKind = ISD::DELETED_NODE;
2934
2935       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2936       // external symbols most go through the PLT in PIC mode.  If the symbol
2937       // has hidden or protected visibility, or if it is static or local, then
2938       // we don't need to use the PLT - we can directly call it.
2939       if (Subtarget->isTargetELF() &&
2940           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2941           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2942         OpFlags = X86II::MO_PLT;
2943       } else if (Subtarget->isPICStyleStubAny() &&
2944                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2945                  (!Subtarget->getTargetTriple().isMacOSX() ||
2946                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2947         // PC-relative references to external symbols should go through $stub,
2948         // unless we're building with the leopard linker or later, which
2949         // automatically synthesizes these stubs.
2950         OpFlags = X86II::MO_DARWIN_STUB;
2951       } else if (Subtarget->isPICStyleRIPRel() &&
2952                  isa<Function>(GV) &&
2953                  cast<Function>(GV)->getAttributes().
2954                    hasAttribute(AttributeSet::FunctionIndex,
2955                                 Attribute::NonLazyBind)) {
2956         // If the function is marked as non-lazy, generate an indirect call
2957         // which loads from the GOT directly. This avoids runtime overhead
2958         // at the cost of eager binding (and one extra byte of encoding).
2959         OpFlags = X86II::MO_GOTPCREL;
2960         WrapperKind = X86ISD::WrapperRIP;
2961         ExtraLoad = true;
2962       }
2963
2964       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2965                                           G->getOffset(), OpFlags);
2966
2967       // Add a wrapper if needed.
2968       if (WrapperKind != ISD::DELETED_NODE)
2969         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2970       // Add extra indirection if needed.
2971       if (ExtraLoad)
2972         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2973                              MachinePointerInfo::getGOT(),
2974                              false, false, false, 0);
2975     }
2976   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2977     unsigned char OpFlags = 0;
2978
2979     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2980     // external symbols should go through the PLT.
2981     if (Subtarget->isTargetELF() &&
2982         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2983       OpFlags = X86II::MO_PLT;
2984     } else if (Subtarget->isPICStyleStubAny() &&
2985                (!Subtarget->getTargetTriple().isMacOSX() ||
2986                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2987       // PC-relative references to external symbols should go through $stub,
2988       // unless we're building with the leopard linker or later, which
2989       // automatically synthesizes these stubs.
2990       OpFlags = X86II::MO_DARWIN_STUB;
2991     }
2992
2993     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2994                                          OpFlags);
2995   }
2996
2997   // Returns a chain & a flag for retval copy to use.
2998   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2999   SmallVector<SDValue, 8> Ops;
3000
3001   if (!IsSibcall && isTailCall) {
3002     Chain = DAG.getCALLSEQ_END(Chain,
3003                                DAG.getIntPtrConstant(NumBytesToPop, true),
3004                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3005     InFlag = Chain.getValue(1);
3006   }
3007
3008   Ops.push_back(Chain);
3009   Ops.push_back(Callee);
3010
3011   if (isTailCall)
3012     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3013
3014   // Add argument registers to the end of the list so that they are known live
3015   // into the call.
3016   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3017     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3018                                   RegsToPass[i].second.getValueType()));
3019
3020   // Add a register mask operand representing the call-preserved registers.
3021   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3022   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3023   assert(Mask && "Missing call preserved mask for calling convention");
3024   Ops.push_back(DAG.getRegisterMask(Mask));
3025
3026   if (InFlag.getNode())
3027     Ops.push_back(InFlag);
3028
3029   if (isTailCall) {
3030     // We used to do:
3031     //// If this is the first return lowered for this function, add the regs
3032     //// to the liveout set for the function.
3033     // This isn't right, although it's probably harmless on x86; liveouts
3034     // should be computed from returns not tail calls.  Consider a void
3035     // function making a tail call to a function returning int.
3036     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3037   }
3038
3039   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3040   InFlag = Chain.getValue(1);
3041
3042   // Create the CALLSEQ_END node.
3043   unsigned NumBytesForCalleeToPop;
3044   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3045                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3046     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3047   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3048            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3049            SR == StackStructReturn)
3050     // If this is a call to a struct-return function, the callee
3051     // pops the hidden struct pointer, so we have to push it back.
3052     // This is common for Darwin/X86, Linux & Mingw32 targets.
3053     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3054     NumBytesForCalleeToPop = 4;
3055   else
3056     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3057
3058   // Returns a flag for retval copy to use.
3059   if (!IsSibcall) {
3060     Chain = DAG.getCALLSEQ_END(Chain,
3061                                DAG.getIntPtrConstant(NumBytesToPop, true),
3062                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3063                                                      true),
3064                                InFlag, dl);
3065     InFlag = Chain.getValue(1);
3066   }
3067
3068   // Handle result values, copying them out of physregs into vregs that we
3069   // return.
3070   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3071                          Ins, dl, DAG, InVals);
3072 }
3073
3074 //===----------------------------------------------------------------------===//
3075 //                Fast Calling Convention (tail call) implementation
3076 //===----------------------------------------------------------------------===//
3077
3078 //  Like std call, callee cleans arguments, convention except that ECX is
3079 //  reserved for storing the tail called function address. Only 2 registers are
3080 //  free for argument passing (inreg). Tail call optimization is performed
3081 //  provided:
3082 //                * tailcallopt is enabled
3083 //                * caller/callee are fastcc
3084 //  On X86_64 architecture with GOT-style position independent code only local
3085 //  (within module) calls are supported at the moment.
3086 //  To keep the stack aligned according to platform abi the function
3087 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3088 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3089 //  If a tail called function callee has more arguments than the caller the
3090 //  caller needs to make sure that there is room to move the RETADDR to. This is
3091 //  achieved by reserving an area the size of the argument delta right after the
3092 //  original RETADDR, but before the saved framepointer or the spilled registers
3093 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3094 //  stack layout:
3095 //    arg1
3096 //    arg2
3097 //    RETADDR
3098 //    [ new RETADDR
3099 //      move area ]
3100 //    (possible EBP)
3101 //    ESI
3102 //    EDI
3103 //    local1 ..
3104
3105 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3106 /// for a 16 byte align requirement.
3107 unsigned
3108 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3109                                                SelectionDAG& DAG) const {
3110   MachineFunction &MF = DAG.getMachineFunction();
3111   const TargetMachine &TM = MF.getTarget();
3112   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3113       TM.getSubtargetImpl()->getRegisterInfo());
3114   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3115   unsigned StackAlignment = TFI.getStackAlignment();
3116   uint64_t AlignMask = StackAlignment - 1;
3117   int64_t Offset = StackSize;
3118   unsigned SlotSize = RegInfo->getSlotSize();
3119   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3120     // Number smaller than 12 so just add the difference.
3121     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3122   } else {
3123     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3124     Offset = ((~AlignMask) & Offset) + StackAlignment +
3125       (StackAlignment-SlotSize);
3126   }
3127   return Offset;
3128 }
3129
3130 /// MatchingStackOffset - Return true if the given stack call argument is
3131 /// already available in the same position (relatively) of the caller's
3132 /// incoming argument stack.
3133 static
3134 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3135                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3136                          const X86InstrInfo *TII) {
3137   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3138   int FI = INT_MAX;
3139   if (Arg.getOpcode() == ISD::CopyFromReg) {
3140     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3141     if (!TargetRegisterInfo::isVirtualRegister(VR))
3142       return false;
3143     MachineInstr *Def = MRI->getVRegDef(VR);
3144     if (!Def)
3145       return false;
3146     if (!Flags.isByVal()) {
3147       if (!TII->isLoadFromStackSlot(Def, FI))
3148         return false;
3149     } else {
3150       unsigned Opcode = Def->getOpcode();
3151       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3152           Def->getOperand(1).isFI()) {
3153         FI = Def->getOperand(1).getIndex();
3154         Bytes = Flags.getByValSize();
3155       } else
3156         return false;
3157     }
3158   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3159     if (Flags.isByVal())
3160       // ByVal argument is passed in as a pointer but it's now being
3161       // dereferenced. e.g.
3162       // define @foo(%struct.X* %A) {
3163       //   tail call @bar(%struct.X* byval %A)
3164       // }
3165       return false;
3166     SDValue Ptr = Ld->getBasePtr();
3167     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3168     if (!FINode)
3169       return false;
3170     FI = FINode->getIndex();
3171   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3172     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3173     FI = FINode->getIndex();
3174     Bytes = Flags.getByValSize();
3175   } else
3176     return false;
3177
3178   assert(FI != INT_MAX);
3179   if (!MFI->isFixedObjectIndex(FI))
3180     return false;
3181   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3182 }
3183
3184 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3185 /// for tail call optimization. Targets which want to do tail call
3186 /// optimization should implement this function.
3187 bool
3188 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3189                                                      CallingConv::ID CalleeCC,
3190                                                      bool isVarArg,
3191                                                      bool isCalleeStructRet,
3192                                                      bool isCallerStructRet,
3193                                                      Type *RetTy,
3194                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3195                                     const SmallVectorImpl<SDValue> &OutVals,
3196                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3197                                                      SelectionDAG &DAG) const {
3198   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3199     return false;
3200
3201   // If -tailcallopt is specified, make fastcc functions tail-callable.
3202   const MachineFunction &MF = DAG.getMachineFunction();
3203   const Function *CallerF = MF.getFunction();
3204
3205   // If the function return type is x86_fp80 and the callee return type is not,
3206   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3207   // perform a tailcall optimization here.
3208   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3209     return false;
3210
3211   CallingConv::ID CallerCC = CallerF->getCallingConv();
3212   bool CCMatch = CallerCC == CalleeCC;
3213   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3214   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3215
3216   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3217     if (IsTailCallConvention(CalleeCC) && CCMatch)
3218       return true;
3219     return false;
3220   }
3221
3222   // Look for obvious safe cases to perform tail call optimization that do not
3223   // require ABI changes. This is what gcc calls sibcall.
3224
3225   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3226   // emit a special epilogue.
3227   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3228       DAG.getSubtarget().getRegisterInfo());
3229   if (RegInfo->needsStackRealignment(MF))
3230     return false;
3231
3232   // Also avoid sibcall optimization if either caller or callee uses struct
3233   // return semantics.
3234   if (isCalleeStructRet || isCallerStructRet)
3235     return false;
3236
3237   // An stdcall/thiscall caller is expected to clean up its arguments; the
3238   // callee isn't going to do that.
3239   // FIXME: this is more restrictive than needed. We could produce a tailcall
3240   // when the stack adjustment matches. For example, with a thiscall that takes
3241   // only one argument.
3242   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3243                    CallerCC == CallingConv::X86_ThisCall))
3244     return false;
3245
3246   // Do not sibcall optimize vararg calls unless all arguments are passed via
3247   // registers.
3248   if (isVarArg && !Outs.empty()) {
3249
3250     // Optimizing for varargs on Win64 is unlikely to be safe without
3251     // additional testing.
3252     if (IsCalleeWin64 || IsCallerWin64)
3253       return false;
3254
3255     SmallVector<CCValAssign, 16> ArgLocs;
3256     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3257                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3258
3259     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3260     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3261       if (!ArgLocs[i].isRegLoc())
3262         return false;
3263   }
3264
3265   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3266   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3267   // this into a sibcall.
3268   bool Unused = false;
3269   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3270     if (!Ins[i].Used) {
3271       Unused = true;
3272       break;
3273     }
3274   }
3275   if (Unused) {
3276     SmallVector<CCValAssign, 16> RVLocs;
3277     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3278                    DAG.getTarget(), RVLocs, *DAG.getContext());
3279     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3280     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3281       CCValAssign &VA = RVLocs[i];
3282       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3283         return false;
3284     }
3285   }
3286
3287   // If the calling conventions do not match, then we'd better make sure the
3288   // results are returned in the same way as what the caller expects.
3289   if (!CCMatch) {
3290     SmallVector<CCValAssign, 16> RVLocs1;
3291     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3292                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3293     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3294
3295     SmallVector<CCValAssign, 16> RVLocs2;
3296     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3297                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3298     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3299
3300     if (RVLocs1.size() != RVLocs2.size())
3301       return false;
3302     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3303       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3304         return false;
3305       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3306         return false;
3307       if (RVLocs1[i].isRegLoc()) {
3308         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3309           return false;
3310       } else {
3311         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3312           return false;
3313       }
3314     }
3315   }
3316
3317   // If the callee takes no arguments then go on to check the results of the
3318   // call.
3319   if (!Outs.empty()) {
3320     // Check if stack adjustment is needed. For now, do not do this if any
3321     // argument is passed on the stack.
3322     SmallVector<CCValAssign, 16> ArgLocs;
3323     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3324                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3325
3326     // Allocate shadow area for Win64
3327     if (IsCalleeWin64)
3328       CCInfo.AllocateStack(32, 8);
3329
3330     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3331     if (CCInfo.getNextStackOffset()) {
3332       MachineFunction &MF = DAG.getMachineFunction();
3333       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3334         return false;
3335
3336       // Check if the arguments are already laid out in the right way as
3337       // the caller's fixed stack objects.
3338       MachineFrameInfo *MFI = MF.getFrameInfo();
3339       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3340       const X86InstrInfo *TII =
3341           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3342       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3343         CCValAssign &VA = ArgLocs[i];
3344         SDValue Arg = OutVals[i];
3345         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3346         if (VA.getLocInfo() == CCValAssign::Indirect)
3347           return false;
3348         if (!VA.isRegLoc()) {
3349           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3350                                    MFI, MRI, TII))
3351             return false;
3352         }
3353       }
3354     }
3355
3356     // If the tailcall address may be in a register, then make sure it's
3357     // possible to register allocate for it. In 32-bit, the call address can
3358     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3359     // callee-saved registers are restored. These happen to be the same
3360     // registers used to pass 'inreg' arguments so watch out for those.
3361     if (!Subtarget->is64Bit() &&
3362         ((!isa<GlobalAddressSDNode>(Callee) &&
3363           !isa<ExternalSymbolSDNode>(Callee)) ||
3364          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3365       unsigned NumInRegs = 0;
3366       // In PIC we need an extra register to formulate the address computation
3367       // for the callee.
3368       unsigned MaxInRegs =
3369         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3370
3371       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3372         CCValAssign &VA = ArgLocs[i];
3373         if (!VA.isRegLoc())
3374           continue;
3375         unsigned Reg = VA.getLocReg();
3376         switch (Reg) {
3377         default: break;
3378         case X86::EAX: case X86::EDX: case X86::ECX:
3379           if (++NumInRegs == MaxInRegs)
3380             return false;
3381           break;
3382         }
3383       }
3384     }
3385   }
3386
3387   return true;
3388 }
3389
3390 FastISel *
3391 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3392                                   const TargetLibraryInfo *libInfo) const {
3393   return X86::createFastISel(funcInfo, libInfo);
3394 }
3395
3396 //===----------------------------------------------------------------------===//
3397 //                           Other Lowering Hooks
3398 //===----------------------------------------------------------------------===//
3399
3400 static bool MayFoldLoad(SDValue Op) {
3401   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3402 }
3403
3404 static bool MayFoldIntoStore(SDValue Op) {
3405   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3406 }
3407
3408 static bool isTargetShuffle(unsigned Opcode) {
3409   switch(Opcode) {
3410   default: return false;
3411   case X86ISD::PSHUFB:
3412   case X86ISD::PSHUFD:
3413   case X86ISD::PSHUFHW:
3414   case X86ISD::PSHUFLW:
3415   case X86ISD::SHUFP:
3416   case X86ISD::PALIGNR:
3417   case X86ISD::MOVLHPS:
3418   case X86ISD::MOVLHPD:
3419   case X86ISD::MOVHLPS:
3420   case X86ISD::MOVLPS:
3421   case X86ISD::MOVLPD:
3422   case X86ISD::MOVSHDUP:
3423   case X86ISD::MOVSLDUP:
3424   case X86ISD::MOVDDUP:
3425   case X86ISD::MOVSS:
3426   case X86ISD::MOVSD:
3427   case X86ISD::UNPCKL:
3428   case X86ISD::UNPCKH:
3429   case X86ISD::VPERMILP:
3430   case X86ISD::VPERM2X128:
3431   case X86ISD::VPERMI:
3432     return true;
3433   }
3434 }
3435
3436 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3437                                     SDValue V1, SelectionDAG &DAG) {
3438   switch(Opc) {
3439   default: llvm_unreachable("Unknown x86 shuffle node");
3440   case X86ISD::MOVSHDUP:
3441   case X86ISD::MOVSLDUP:
3442   case X86ISD::MOVDDUP:
3443     return DAG.getNode(Opc, dl, VT, V1);
3444   }
3445 }
3446
3447 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3448                                     SDValue V1, unsigned TargetMask,
3449                                     SelectionDAG &DAG) {
3450   switch(Opc) {
3451   default: llvm_unreachable("Unknown x86 shuffle node");
3452   case X86ISD::PSHUFD:
3453   case X86ISD::PSHUFHW:
3454   case X86ISD::PSHUFLW:
3455   case X86ISD::VPERMILP:
3456   case X86ISD::VPERMI:
3457     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3458   }
3459 }
3460
3461 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3462                                     SDValue V1, SDValue V2, unsigned TargetMask,
3463                                     SelectionDAG &DAG) {
3464   switch(Opc) {
3465   default: llvm_unreachable("Unknown x86 shuffle node");
3466   case X86ISD::PALIGNR:
3467   case X86ISD::VALIGN:
3468   case X86ISD::SHUFP:
3469   case X86ISD::VPERM2X128:
3470     return DAG.getNode(Opc, dl, VT, V1, V2,
3471                        DAG.getConstant(TargetMask, MVT::i8));
3472   }
3473 }
3474
3475 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3476                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3477   switch(Opc) {
3478   default: llvm_unreachable("Unknown x86 shuffle node");
3479   case X86ISD::MOVLHPS:
3480   case X86ISD::MOVLHPD:
3481   case X86ISD::MOVHLPS:
3482   case X86ISD::MOVLPS:
3483   case X86ISD::MOVLPD:
3484   case X86ISD::MOVSS:
3485   case X86ISD::MOVSD:
3486   case X86ISD::UNPCKL:
3487   case X86ISD::UNPCKH:
3488     return DAG.getNode(Opc, dl, VT, V1, V2);
3489   }
3490 }
3491
3492 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3493   MachineFunction &MF = DAG.getMachineFunction();
3494   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3495       DAG.getSubtarget().getRegisterInfo());
3496   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3497   int ReturnAddrIndex = FuncInfo->getRAIndex();
3498
3499   if (ReturnAddrIndex == 0) {
3500     // Set up a frame object for the return address.
3501     unsigned SlotSize = RegInfo->getSlotSize();
3502     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3503                                                            -(int64_t)SlotSize,
3504                                                            false);
3505     FuncInfo->setRAIndex(ReturnAddrIndex);
3506   }
3507
3508   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3509 }
3510
3511 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3512                                        bool hasSymbolicDisplacement) {
3513   // Offset should fit into 32 bit immediate field.
3514   if (!isInt<32>(Offset))
3515     return false;
3516
3517   // If we don't have a symbolic displacement - we don't have any extra
3518   // restrictions.
3519   if (!hasSymbolicDisplacement)
3520     return true;
3521
3522   // FIXME: Some tweaks might be needed for medium code model.
3523   if (M != CodeModel::Small && M != CodeModel::Kernel)
3524     return false;
3525
3526   // For small code model we assume that latest object is 16MB before end of 31
3527   // bits boundary. We may also accept pretty large negative constants knowing
3528   // that all objects are in the positive half of address space.
3529   if (M == CodeModel::Small && Offset < 16*1024*1024)
3530     return true;
3531
3532   // For kernel code model we know that all object resist in the negative half
3533   // of 32bits address space. We may not accept negative offsets, since they may
3534   // be just off and we may accept pretty large positive ones.
3535   if (M == CodeModel::Kernel && Offset > 0)
3536     return true;
3537
3538   return false;
3539 }
3540
3541 /// isCalleePop - Determines whether the callee is required to pop its
3542 /// own arguments. Callee pop is necessary to support tail calls.
3543 bool X86::isCalleePop(CallingConv::ID CallingConv,
3544                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3545   if (IsVarArg)
3546     return false;
3547
3548   switch (CallingConv) {
3549   default:
3550     return false;
3551   case CallingConv::X86_StdCall:
3552     return !is64Bit;
3553   case CallingConv::X86_FastCall:
3554     return !is64Bit;
3555   case CallingConv::X86_ThisCall:
3556     return !is64Bit;
3557   case CallingConv::Fast:
3558     return TailCallOpt;
3559   case CallingConv::GHC:
3560     return TailCallOpt;
3561   case CallingConv::HiPE:
3562     return TailCallOpt;
3563   }
3564 }
3565
3566 /// \brief Return true if the condition is an unsigned comparison operation.
3567 static bool isX86CCUnsigned(unsigned X86CC) {
3568   switch (X86CC) {
3569   default: llvm_unreachable("Invalid integer condition!");
3570   case X86::COND_E:     return true;
3571   case X86::COND_G:     return false;
3572   case X86::COND_GE:    return false;
3573   case X86::COND_L:     return false;
3574   case X86::COND_LE:    return false;
3575   case X86::COND_NE:    return true;
3576   case X86::COND_B:     return true;
3577   case X86::COND_A:     return true;
3578   case X86::COND_BE:    return true;
3579   case X86::COND_AE:    return true;
3580   }
3581   llvm_unreachable("covered switch fell through?!");
3582 }
3583
3584 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3585 /// specific condition code, returning the condition code and the LHS/RHS of the
3586 /// comparison to make.
3587 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3588                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3589   if (!isFP) {
3590     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3591       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3592         // X > -1   -> X == 0, jump !sign.
3593         RHS = DAG.getConstant(0, RHS.getValueType());
3594         return X86::COND_NS;
3595       }
3596       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3597         // X < 0   -> X == 0, jump on sign.
3598         return X86::COND_S;
3599       }
3600       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3601         // X < 1   -> X <= 0
3602         RHS = DAG.getConstant(0, RHS.getValueType());
3603         return X86::COND_LE;
3604       }
3605     }
3606
3607     switch (SetCCOpcode) {
3608     default: llvm_unreachable("Invalid integer condition!");
3609     case ISD::SETEQ:  return X86::COND_E;
3610     case ISD::SETGT:  return X86::COND_G;
3611     case ISD::SETGE:  return X86::COND_GE;
3612     case ISD::SETLT:  return X86::COND_L;
3613     case ISD::SETLE:  return X86::COND_LE;
3614     case ISD::SETNE:  return X86::COND_NE;
3615     case ISD::SETULT: return X86::COND_B;
3616     case ISD::SETUGT: return X86::COND_A;
3617     case ISD::SETULE: return X86::COND_BE;
3618     case ISD::SETUGE: return X86::COND_AE;
3619     }
3620   }
3621
3622   // First determine if it is required or is profitable to flip the operands.
3623
3624   // If LHS is a foldable load, but RHS is not, flip the condition.
3625   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3626       !ISD::isNON_EXTLoad(RHS.getNode())) {
3627     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3628     std::swap(LHS, RHS);
3629   }
3630
3631   switch (SetCCOpcode) {
3632   default: break;
3633   case ISD::SETOLT:
3634   case ISD::SETOLE:
3635   case ISD::SETUGT:
3636   case ISD::SETUGE:
3637     std::swap(LHS, RHS);
3638     break;
3639   }
3640
3641   // On a floating point condition, the flags are set as follows:
3642   // ZF  PF  CF   op
3643   //  0 | 0 | 0 | X > Y
3644   //  0 | 0 | 1 | X < Y
3645   //  1 | 0 | 0 | X == Y
3646   //  1 | 1 | 1 | unordered
3647   switch (SetCCOpcode) {
3648   default: llvm_unreachable("Condcode should be pre-legalized away");
3649   case ISD::SETUEQ:
3650   case ISD::SETEQ:   return X86::COND_E;
3651   case ISD::SETOLT:              // flipped
3652   case ISD::SETOGT:
3653   case ISD::SETGT:   return X86::COND_A;
3654   case ISD::SETOLE:              // flipped
3655   case ISD::SETOGE:
3656   case ISD::SETGE:   return X86::COND_AE;
3657   case ISD::SETUGT:              // flipped
3658   case ISD::SETULT:
3659   case ISD::SETLT:   return X86::COND_B;
3660   case ISD::SETUGE:              // flipped
3661   case ISD::SETULE:
3662   case ISD::SETLE:   return X86::COND_BE;
3663   case ISD::SETONE:
3664   case ISD::SETNE:   return X86::COND_NE;
3665   case ISD::SETUO:   return X86::COND_P;
3666   case ISD::SETO:    return X86::COND_NP;
3667   case ISD::SETOEQ:
3668   case ISD::SETUNE:  return X86::COND_INVALID;
3669   }
3670 }
3671
3672 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3673 /// code. Current x86 isa includes the following FP cmov instructions:
3674 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3675 static bool hasFPCMov(unsigned X86CC) {
3676   switch (X86CC) {
3677   default:
3678     return false;
3679   case X86::COND_B:
3680   case X86::COND_BE:
3681   case X86::COND_E:
3682   case X86::COND_P:
3683   case X86::COND_A:
3684   case X86::COND_AE:
3685   case X86::COND_NE:
3686   case X86::COND_NP:
3687     return true;
3688   }
3689 }
3690
3691 /// isFPImmLegal - Returns true if the target can instruction select the
3692 /// specified FP immediate natively. If false, the legalizer will
3693 /// materialize the FP immediate as a load from a constant pool.
3694 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3695   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3696     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3697       return true;
3698   }
3699   return false;
3700 }
3701
3702 /// \brief Returns true if it is beneficial to convert a load of a constant
3703 /// to just the constant itself.
3704 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3705                                                           Type *Ty) const {
3706   assert(Ty->isIntegerTy());
3707
3708   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3709   if (BitSize == 0 || BitSize > 64)
3710     return false;
3711   return true;
3712 }
3713
3714 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3715 /// the specified range (L, H].
3716 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3717   return (Val < 0) || (Val >= Low && Val < Hi);
3718 }
3719
3720 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3721 /// specified value.
3722 static bool isUndefOrEqual(int Val, int CmpVal) {
3723   return (Val < 0 || Val == CmpVal);
3724 }
3725
3726 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3727 /// from position Pos and ending in Pos+Size, falls within the specified
3728 /// sequential range (L, L+Pos]. or is undef.
3729 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3730                                        unsigned Pos, unsigned Size, int Low) {
3731   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3732     if (!isUndefOrEqual(Mask[i], Low))
3733       return false;
3734   return true;
3735 }
3736
3737 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3738 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3739 /// the second operand.
3740 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3741   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3742     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3743   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3744     return (Mask[0] < 2 && Mask[1] < 2);
3745   return false;
3746 }
3747
3748 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3749 /// is suitable for input to PSHUFHW.
3750 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3751   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3752     return false;
3753
3754   // Lower quadword copied in order or undef.
3755   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3756     return false;
3757
3758   // Upper quadword shuffled.
3759   for (unsigned i = 4; i != 8; ++i)
3760     if (!isUndefOrInRange(Mask[i], 4, 8))
3761       return false;
3762
3763   if (VT == MVT::v16i16) {
3764     // Lower quadword copied in order or undef.
3765     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3766       return false;
3767
3768     // Upper quadword shuffled.
3769     for (unsigned i = 12; i != 16; ++i)
3770       if (!isUndefOrInRange(Mask[i], 12, 16))
3771         return false;
3772   }
3773
3774   return true;
3775 }
3776
3777 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3778 /// is suitable for input to PSHUFLW.
3779 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3780   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3781     return false;
3782
3783   // Upper quadword copied in order.
3784   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3785     return false;
3786
3787   // Lower quadword shuffled.
3788   for (unsigned i = 0; i != 4; ++i)
3789     if (!isUndefOrInRange(Mask[i], 0, 4))
3790       return false;
3791
3792   if (VT == MVT::v16i16) {
3793     // Upper quadword copied in order.
3794     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3795       return false;
3796
3797     // Lower quadword shuffled.
3798     for (unsigned i = 8; i != 12; ++i)
3799       if (!isUndefOrInRange(Mask[i], 8, 12))
3800         return false;
3801   }
3802
3803   return true;
3804 }
3805
3806 /// \brief Return true if the mask specifies a shuffle of elements that is
3807 /// suitable for input to intralane (palignr) or interlane (valign) vector
3808 /// right-shift.
3809 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3810   unsigned NumElts = VT.getVectorNumElements();
3811   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3812   unsigned NumLaneElts = NumElts/NumLanes;
3813
3814   // Do not handle 64-bit element shuffles with palignr.
3815   if (NumLaneElts == 2)
3816     return false;
3817
3818   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3819     unsigned i;
3820     for (i = 0; i != NumLaneElts; ++i) {
3821       if (Mask[i+l] >= 0)
3822         break;
3823     }
3824
3825     // Lane is all undef, go to next lane
3826     if (i == NumLaneElts)
3827       continue;
3828
3829     int Start = Mask[i+l];
3830
3831     // Make sure its in this lane in one of the sources
3832     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3833         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3834       return false;
3835
3836     // If not lane 0, then we must match lane 0
3837     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3838       return false;
3839
3840     // Correct second source to be contiguous with first source
3841     if (Start >= (int)NumElts)
3842       Start -= NumElts - NumLaneElts;
3843
3844     // Make sure we're shifting in the right direction.
3845     if (Start <= (int)(i+l))
3846       return false;
3847
3848     Start -= i;
3849
3850     // Check the rest of the elements to see if they are consecutive.
3851     for (++i; i != NumLaneElts; ++i) {
3852       int Idx = Mask[i+l];
3853
3854       // Make sure its in this lane
3855       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3856           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3857         return false;
3858
3859       // If not lane 0, then we must match lane 0
3860       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3861         return false;
3862
3863       if (Idx >= (int)NumElts)
3864         Idx -= NumElts - NumLaneElts;
3865
3866       if (!isUndefOrEqual(Idx, Start+i))
3867         return false;
3868
3869     }
3870   }
3871
3872   return true;
3873 }
3874
3875 /// \brief Return true if the node specifies a shuffle of elements that is
3876 /// suitable for input to PALIGNR.
3877 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3878                           const X86Subtarget *Subtarget) {
3879   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3880       (VT.is256BitVector() && !Subtarget->hasInt256()))
3881     // FIXME: Add AVX512BW.
3882     return false;
3883
3884   return isAlignrMask(Mask, VT, false);
3885 }
3886
3887 /// \brief Return true if the node specifies a shuffle of elements that is
3888 /// suitable for input to VALIGN.
3889 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
3890                           const X86Subtarget *Subtarget) {
3891   // FIXME: Add AVX512VL.
3892   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
3893     return false;
3894   return isAlignrMask(Mask, VT, true);
3895 }
3896
3897 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3898 /// the two vector operands have swapped position.
3899 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3900                                      unsigned NumElems) {
3901   for (unsigned i = 0; i != NumElems; ++i) {
3902     int idx = Mask[i];
3903     if (idx < 0)
3904       continue;
3905     else if (idx < (int)NumElems)
3906       Mask[i] = idx + NumElems;
3907     else
3908       Mask[i] = idx - NumElems;
3909   }
3910 }
3911
3912 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3913 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3914 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3915 /// reverse of what x86 shuffles want.
3916 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3917
3918   unsigned NumElems = VT.getVectorNumElements();
3919   unsigned NumLanes = VT.getSizeInBits()/128;
3920   unsigned NumLaneElems = NumElems/NumLanes;
3921
3922   if (NumLaneElems != 2 && NumLaneElems != 4)
3923     return false;
3924
3925   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3926   bool symetricMaskRequired =
3927     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3928
3929   // VSHUFPSY divides the resulting vector into 4 chunks.
3930   // The sources are also splitted into 4 chunks, and each destination
3931   // chunk must come from a different source chunk.
3932   //
3933   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3934   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3935   //
3936   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3937   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3938   //
3939   // VSHUFPDY divides the resulting vector into 4 chunks.
3940   // The sources are also splitted into 4 chunks, and each destination
3941   // chunk must come from a different source chunk.
3942   //
3943   //  SRC1 =>      X3       X2       X1       X0
3944   //  SRC2 =>      Y3       Y2       Y1       Y0
3945   //
3946   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3947   //
3948   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3949   unsigned HalfLaneElems = NumLaneElems/2;
3950   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3951     for (unsigned i = 0; i != NumLaneElems; ++i) {
3952       int Idx = Mask[i+l];
3953       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3954       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3955         return false;
3956       // For VSHUFPSY, the mask of the second half must be the same as the
3957       // first but with the appropriate offsets. This works in the same way as
3958       // VPERMILPS works with masks.
3959       if (!symetricMaskRequired || Idx < 0)
3960         continue;
3961       if (MaskVal[i] < 0) {
3962         MaskVal[i] = Idx - l;
3963         continue;
3964       }
3965       if ((signed)(Idx - l) != MaskVal[i])
3966         return false;
3967     }
3968   }
3969
3970   return true;
3971 }
3972
3973 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3974 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3975 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3976   if (!VT.is128BitVector())
3977     return false;
3978
3979   unsigned NumElems = VT.getVectorNumElements();
3980
3981   if (NumElems != 4)
3982     return false;
3983
3984   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3985   return isUndefOrEqual(Mask[0], 6) &&
3986          isUndefOrEqual(Mask[1], 7) &&
3987          isUndefOrEqual(Mask[2], 2) &&
3988          isUndefOrEqual(Mask[3], 3);
3989 }
3990
3991 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3992 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3993 /// <2, 3, 2, 3>
3994 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3995   if (!VT.is128BitVector())
3996     return false;
3997
3998   unsigned NumElems = VT.getVectorNumElements();
3999
4000   if (NumElems != 4)
4001     return false;
4002
4003   return isUndefOrEqual(Mask[0], 2) &&
4004          isUndefOrEqual(Mask[1], 3) &&
4005          isUndefOrEqual(Mask[2], 2) &&
4006          isUndefOrEqual(Mask[3], 3);
4007 }
4008
4009 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4010 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4011 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4012   if (!VT.is128BitVector())
4013     return false;
4014
4015   unsigned NumElems = VT.getVectorNumElements();
4016
4017   if (NumElems != 2 && NumElems != 4)
4018     return false;
4019
4020   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4021     if (!isUndefOrEqual(Mask[i], i + NumElems))
4022       return false;
4023
4024   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4025     if (!isUndefOrEqual(Mask[i], i))
4026       return false;
4027
4028   return true;
4029 }
4030
4031 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4032 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4033 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4034   if (!VT.is128BitVector())
4035     return false;
4036
4037   unsigned NumElems = VT.getVectorNumElements();
4038
4039   if (NumElems != 2 && NumElems != 4)
4040     return false;
4041
4042   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4043     if (!isUndefOrEqual(Mask[i], i))
4044       return false;
4045
4046   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4047     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4048       return false;
4049
4050   return true;
4051 }
4052
4053 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4054 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4055 /// i. e: If all but one element come from the same vector.
4056 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4057   // TODO: Deal with AVX's VINSERTPS
4058   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4059     return false;
4060
4061   unsigned CorrectPosV1 = 0;
4062   unsigned CorrectPosV2 = 0;
4063   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4064     if (Mask[i] == -1) {
4065       ++CorrectPosV1;
4066       ++CorrectPosV2;
4067       continue;
4068     }
4069
4070     if (Mask[i] == i)
4071       ++CorrectPosV1;
4072     else if (Mask[i] == i + 4)
4073       ++CorrectPosV2;
4074   }
4075
4076   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4077     // We have 3 elements (undefs count as elements from any vector) from one
4078     // vector, and one from another.
4079     return true;
4080
4081   return false;
4082 }
4083
4084 //
4085 // Some special combinations that can be optimized.
4086 //
4087 static
4088 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4089                                SelectionDAG &DAG) {
4090   MVT VT = SVOp->getSimpleValueType(0);
4091   SDLoc dl(SVOp);
4092
4093   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4094     return SDValue();
4095
4096   ArrayRef<int> Mask = SVOp->getMask();
4097
4098   // These are the special masks that may be optimized.
4099   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4100   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4101   bool MatchEvenMask = true;
4102   bool MatchOddMask  = true;
4103   for (int i=0; i<8; ++i) {
4104     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4105       MatchEvenMask = false;
4106     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4107       MatchOddMask = false;
4108   }
4109
4110   if (!MatchEvenMask && !MatchOddMask)
4111     return SDValue();
4112
4113   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4114
4115   SDValue Op0 = SVOp->getOperand(0);
4116   SDValue Op1 = SVOp->getOperand(1);
4117
4118   if (MatchEvenMask) {
4119     // Shift the second operand right to 32 bits.
4120     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4121     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4122   } else {
4123     // Shift the first operand left to 32 bits.
4124     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4125     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4126   }
4127   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4128   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4129 }
4130
4131 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4132 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4133 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4134                          bool HasInt256, bool V2IsSplat = false) {
4135
4136   assert(VT.getSizeInBits() >= 128 &&
4137          "Unsupported vector type for unpckl");
4138
4139   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4140   unsigned NumLanes;
4141   unsigned NumOf256BitLanes;
4142   unsigned NumElts = VT.getVectorNumElements();
4143   if (VT.is256BitVector()) {
4144     if (NumElts != 4 && NumElts != 8 &&
4145         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4146     return false;
4147     NumLanes = 2;
4148     NumOf256BitLanes = 1;
4149   } else if (VT.is512BitVector()) {
4150     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4151            "Unsupported vector type for unpckh");
4152     NumLanes = 2;
4153     NumOf256BitLanes = 2;
4154   } else {
4155     NumLanes = 1;
4156     NumOf256BitLanes = 1;
4157   }
4158
4159   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4160   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4161
4162   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4163     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4164       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4165         int BitI  = Mask[l256*NumEltsInStride+l+i];
4166         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4167         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4168           return false;
4169         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4170           return false;
4171         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4172           return false;
4173       }
4174     }
4175   }
4176   return true;
4177 }
4178
4179 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4180 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4181 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4182                          bool HasInt256, bool V2IsSplat = false) {
4183   assert(VT.getSizeInBits() >= 128 &&
4184          "Unsupported vector type for unpckh");
4185
4186   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4187   unsigned NumLanes;
4188   unsigned NumOf256BitLanes;
4189   unsigned NumElts = VT.getVectorNumElements();
4190   if (VT.is256BitVector()) {
4191     if (NumElts != 4 && NumElts != 8 &&
4192         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4193     return false;
4194     NumLanes = 2;
4195     NumOf256BitLanes = 1;
4196   } else if (VT.is512BitVector()) {
4197     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4198            "Unsupported vector type for unpckh");
4199     NumLanes = 2;
4200     NumOf256BitLanes = 2;
4201   } else {
4202     NumLanes = 1;
4203     NumOf256BitLanes = 1;
4204   }
4205
4206   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4207   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4208
4209   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4210     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4211       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4212         int BitI  = Mask[l256*NumEltsInStride+l+i];
4213         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4214         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4215           return false;
4216         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4217           return false;
4218         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4219           return false;
4220       }
4221     }
4222   }
4223   return true;
4224 }
4225
4226 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4227 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4228 /// <0, 0, 1, 1>
4229 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4230   unsigned NumElts = VT.getVectorNumElements();
4231   bool Is256BitVec = VT.is256BitVector();
4232
4233   if (VT.is512BitVector())
4234     return false;
4235   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4236          "Unsupported vector type for unpckh");
4237
4238   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4239       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4240     return false;
4241
4242   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4243   // FIXME: Need a better way to get rid of this, there's no latency difference
4244   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4245   // the former later. We should also remove the "_undef" special mask.
4246   if (NumElts == 4 && Is256BitVec)
4247     return false;
4248
4249   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4250   // independently on 128-bit lanes.
4251   unsigned NumLanes = VT.getSizeInBits()/128;
4252   unsigned NumLaneElts = NumElts/NumLanes;
4253
4254   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4255     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4256       int BitI  = Mask[l+i];
4257       int BitI1 = Mask[l+i+1];
4258
4259       if (!isUndefOrEqual(BitI, j))
4260         return false;
4261       if (!isUndefOrEqual(BitI1, j))
4262         return false;
4263     }
4264   }
4265
4266   return true;
4267 }
4268
4269 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4270 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4271 /// <2, 2, 3, 3>
4272 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4273   unsigned NumElts = VT.getVectorNumElements();
4274
4275   if (VT.is512BitVector())
4276     return false;
4277
4278   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4279          "Unsupported vector type for unpckh");
4280
4281   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4282       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4283     return false;
4284
4285   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4286   // independently on 128-bit lanes.
4287   unsigned NumLanes = VT.getSizeInBits()/128;
4288   unsigned NumLaneElts = NumElts/NumLanes;
4289
4290   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4291     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4292       int BitI  = Mask[l+i];
4293       int BitI1 = Mask[l+i+1];
4294       if (!isUndefOrEqual(BitI, j))
4295         return false;
4296       if (!isUndefOrEqual(BitI1, j))
4297         return false;
4298     }
4299   }
4300   return true;
4301 }
4302
4303 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4304 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4305 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4306   if (!VT.is512BitVector())
4307     return false;
4308
4309   unsigned NumElts = VT.getVectorNumElements();
4310   unsigned HalfSize = NumElts/2;
4311   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4312     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4313       *Imm = 1;
4314       return true;
4315     }
4316   }
4317   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4318     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4319       *Imm = 0;
4320       return true;
4321     }
4322   }
4323   return false;
4324 }
4325
4326 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4327 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4328 /// MOVSD, and MOVD, i.e. setting the lowest element.
4329 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4330   if (VT.getVectorElementType().getSizeInBits() < 32)
4331     return false;
4332   if (!VT.is128BitVector())
4333     return false;
4334
4335   unsigned NumElts = VT.getVectorNumElements();
4336
4337   if (!isUndefOrEqual(Mask[0], NumElts))
4338     return false;
4339
4340   for (unsigned i = 1; i != NumElts; ++i)
4341     if (!isUndefOrEqual(Mask[i], i))
4342       return false;
4343
4344   return true;
4345 }
4346
4347 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4348 /// as permutations between 128-bit chunks or halves. As an example: this
4349 /// shuffle bellow:
4350 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4351 /// The first half comes from the second half of V1 and the second half from the
4352 /// the second half of V2.
4353 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4354   if (!HasFp256 || !VT.is256BitVector())
4355     return false;
4356
4357   // The shuffle result is divided into half A and half B. In total the two
4358   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4359   // B must come from C, D, E or F.
4360   unsigned HalfSize = VT.getVectorNumElements()/2;
4361   bool MatchA = false, MatchB = false;
4362
4363   // Check if A comes from one of C, D, E, F.
4364   for (unsigned Half = 0; Half != 4; ++Half) {
4365     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4366       MatchA = true;
4367       break;
4368     }
4369   }
4370
4371   // Check if B comes from one of C, D, E, F.
4372   for (unsigned Half = 0; Half != 4; ++Half) {
4373     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4374       MatchB = true;
4375       break;
4376     }
4377   }
4378
4379   return MatchA && MatchB;
4380 }
4381
4382 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4383 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4384 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4385   MVT VT = SVOp->getSimpleValueType(0);
4386
4387   unsigned HalfSize = VT.getVectorNumElements()/2;
4388
4389   unsigned FstHalf = 0, SndHalf = 0;
4390   for (unsigned i = 0; i < HalfSize; ++i) {
4391     if (SVOp->getMaskElt(i) > 0) {
4392       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4393       break;
4394     }
4395   }
4396   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4397     if (SVOp->getMaskElt(i) > 0) {
4398       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4399       break;
4400     }
4401   }
4402
4403   return (FstHalf | (SndHalf << 4));
4404 }
4405
4406 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4407 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4408   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4409   if (EltSize < 32)
4410     return false;
4411
4412   unsigned NumElts = VT.getVectorNumElements();
4413   Imm8 = 0;
4414   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4415     for (unsigned i = 0; i != NumElts; ++i) {
4416       if (Mask[i] < 0)
4417         continue;
4418       Imm8 |= Mask[i] << (i*2);
4419     }
4420     return true;
4421   }
4422
4423   unsigned LaneSize = 4;
4424   SmallVector<int, 4> MaskVal(LaneSize, -1);
4425
4426   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4427     for (unsigned i = 0; i != LaneSize; ++i) {
4428       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4429         return false;
4430       if (Mask[i+l] < 0)
4431         continue;
4432       if (MaskVal[i] < 0) {
4433         MaskVal[i] = Mask[i+l] - l;
4434         Imm8 |= MaskVal[i] << (i*2);
4435         continue;
4436       }
4437       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4438         return false;
4439     }
4440   }
4441   return true;
4442 }
4443
4444 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4445 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4446 /// Note that VPERMIL mask matching is different depending whether theunderlying
4447 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4448 /// to the same elements of the low, but to the higher half of the source.
4449 /// In VPERMILPD the two lanes could be shuffled independently of each other
4450 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4451 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4452   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4453   if (VT.getSizeInBits() < 256 || EltSize < 32)
4454     return false;
4455   bool symetricMaskRequired = (EltSize == 32);
4456   unsigned NumElts = VT.getVectorNumElements();
4457
4458   unsigned NumLanes = VT.getSizeInBits()/128;
4459   unsigned LaneSize = NumElts/NumLanes;
4460   // 2 or 4 elements in one lane
4461
4462   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4463   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4464     for (unsigned i = 0; i != LaneSize; ++i) {
4465       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4466         return false;
4467       if (symetricMaskRequired) {
4468         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4469           ExpectedMaskVal[i] = Mask[i+l] - l;
4470           continue;
4471         }
4472         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4473           return false;
4474       }
4475     }
4476   }
4477   return true;
4478 }
4479
4480 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4481 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4482 /// element of vector 2 and the other elements to come from vector 1 in order.
4483 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4484                                bool V2IsSplat = false, bool V2IsUndef = false) {
4485   if (!VT.is128BitVector())
4486     return false;
4487
4488   unsigned NumOps = VT.getVectorNumElements();
4489   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4490     return false;
4491
4492   if (!isUndefOrEqual(Mask[0], 0))
4493     return false;
4494
4495   for (unsigned i = 1; i != NumOps; ++i)
4496     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4497           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4498           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4499       return false;
4500
4501   return true;
4502 }
4503
4504 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4505 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4506 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4507 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4508                            const X86Subtarget *Subtarget) {
4509   if (!Subtarget->hasSSE3())
4510     return false;
4511
4512   unsigned NumElems = VT.getVectorNumElements();
4513
4514   if ((VT.is128BitVector() && NumElems != 4) ||
4515       (VT.is256BitVector() && NumElems != 8) ||
4516       (VT.is512BitVector() && NumElems != 16))
4517     return false;
4518
4519   // "i+1" is the value the indexed mask element must have
4520   for (unsigned i = 0; i != NumElems; i += 2)
4521     if (!isUndefOrEqual(Mask[i], i+1) ||
4522         !isUndefOrEqual(Mask[i+1], i+1))
4523       return false;
4524
4525   return true;
4526 }
4527
4528 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4529 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4530 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4531 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4532                            const X86Subtarget *Subtarget) {
4533   if (!Subtarget->hasSSE3())
4534     return false;
4535
4536   unsigned NumElems = VT.getVectorNumElements();
4537
4538   if ((VT.is128BitVector() && NumElems != 4) ||
4539       (VT.is256BitVector() && NumElems != 8) ||
4540       (VT.is512BitVector() && NumElems != 16))
4541     return false;
4542
4543   // "i" is the value the indexed mask element must have
4544   for (unsigned i = 0; i != NumElems; i += 2)
4545     if (!isUndefOrEqual(Mask[i], i) ||
4546         !isUndefOrEqual(Mask[i+1], i))
4547       return false;
4548
4549   return true;
4550 }
4551
4552 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4553 /// specifies a shuffle of elements that is suitable for input to 256-bit
4554 /// version of MOVDDUP.
4555 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4556   if (!HasFp256 || !VT.is256BitVector())
4557     return false;
4558
4559   unsigned NumElts = VT.getVectorNumElements();
4560   if (NumElts != 4)
4561     return false;
4562
4563   for (unsigned i = 0; i != NumElts/2; ++i)
4564     if (!isUndefOrEqual(Mask[i], 0))
4565       return false;
4566   for (unsigned i = NumElts/2; i != NumElts; ++i)
4567     if (!isUndefOrEqual(Mask[i], NumElts/2))
4568       return false;
4569   return true;
4570 }
4571
4572 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4573 /// specifies a shuffle of elements that is suitable for input to 128-bit
4574 /// version of MOVDDUP.
4575 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4576   if (!VT.is128BitVector())
4577     return false;
4578
4579   unsigned e = VT.getVectorNumElements() / 2;
4580   for (unsigned i = 0; i != e; ++i)
4581     if (!isUndefOrEqual(Mask[i], i))
4582       return false;
4583   for (unsigned i = 0; i != e; ++i)
4584     if (!isUndefOrEqual(Mask[e+i], i))
4585       return false;
4586   return true;
4587 }
4588
4589 /// isVEXTRACTIndex - Return true if the specified
4590 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4591 /// suitable for instruction that extract 128 or 256 bit vectors
4592 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4593   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4594   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4595     return false;
4596
4597   // The index should be aligned on a vecWidth-bit boundary.
4598   uint64_t Index =
4599     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4600
4601   MVT VT = N->getSimpleValueType(0);
4602   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4603   bool Result = (Index * ElSize) % vecWidth == 0;
4604
4605   return Result;
4606 }
4607
4608 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4609 /// operand specifies a subvector insert that is suitable for input to
4610 /// insertion of 128 or 256-bit subvectors
4611 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4612   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4613   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4614     return false;
4615   // The index should be aligned on a vecWidth-bit boundary.
4616   uint64_t Index =
4617     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4618
4619   MVT VT = N->getSimpleValueType(0);
4620   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4621   bool Result = (Index * ElSize) % vecWidth == 0;
4622
4623   return Result;
4624 }
4625
4626 bool X86::isVINSERT128Index(SDNode *N) {
4627   return isVINSERTIndex(N, 128);
4628 }
4629
4630 bool X86::isVINSERT256Index(SDNode *N) {
4631   return isVINSERTIndex(N, 256);
4632 }
4633
4634 bool X86::isVEXTRACT128Index(SDNode *N) {
4635   return isVEXTRACTIndex(N, 128);
4636 }
4637
4638 bool X86::isVEXTRACT256Index(SDNode *N) {
4639   return isVEXTRACTIndex(N, 256);
4640 }
4641
4642 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4643 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4644 /// Handles 128-bit and 256-bit.
4645 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4646   MVT VT = N->getSimpleValueType(0);
4647
4648   assert((VT.getSizeInBits() >= 128) &&
4649          "Unsupported vector type for PSHUF/SHUFP");
4650
4651   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4652   // independently on 128-bit lanes.
4653   unsigned NumElts = VT.getVectorNumElements();
4654   unsigned NumLanes = VT.getSizeInBits()/128;
4655   unsigned NumLaneElts = NumElts/NumLanes;
4656
4657   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4658          "Only supports 2, 4 or 8 elements per lane");
4659
4660   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4661   unsigned Mask = 0;
4662   for (unsigned i = 0; i != NumElts; ++i) {
4663     int Elt = N->getMaskElt(i);
4664     if (Elt < 0) continue;
4665     Elt &= NumLaneElts - 1;
4666     unsigned ShAmt = (i << Shift) % 8;
4667     Mask |= Elt << ShAmt;
4668   }
4669
4670   return Mask;
4671 }
4672
4673 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4674 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4675 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4676   MVT VT = N->getSimpleValueType(0);
4677
4678   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4679          "Unsupported vector type for PSHUFHW");
4680
4681   unsigned NumElts = VT.getVectorNumElements();
4682
4683   unsigned Mask = 0;
4684   for (unsigned l = 0; l != NumElts; l += 8) {
4685     // 8 nodes per lane, but we only care about the last 4.
4686     for (unsigned i = 0; i < 4; ++i) {
4687       int Elt = N->getMaskElt(l+i+4);
4688       if (Elt < 0) continue;
4689       Elt &= 0x3; // only 2-bits.
4690       Mask |= Elt << (i * 2);
4691     }
4692   }
4693
4694   return Mask;
4695 }
4696
4697 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4698 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4699 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4700   MVT VT = N->getSimpleValueType(0);
4701
4702   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4703          "Unsupported vector type for PSHUFHW");
4704
4705   unsigned NumElts = VT.getVectorNumElements();
4706
4707   unsigned Mask = 0;
4708   for (unsigned l = 0; l != NumElts; l += 8) {
4709     // 8 nodes per lane, but we only care about the first 4.
4710     for (unsigned i = 0; i < 4; ++i) {
4711       int Elt = N->getMaskElt(l+i);
4712       if (Elt < 0) continue;
4713       Elt &= 0x3; // only 2-bits
4714       Mask |= Elt << (i * 2);
4715     }
4716   }
4717
4718   return Mask;
4719 }
4720
4721 /// \brief Return the appropriate immediate to shuffle the specified
4722 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4723 /// VALIGN (if Interlane is true) instructions.
4724 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4725                                            bool InterLane) {
4726   MVT VT = SVOp->getSimpleValueType(0);
4727   unsigned EltSize = InterLane ? 1 :
4728     VT.getVectorElementType().getSizeInBits() >> 3;
4729
4730   unsigned NumElts = VT.getVectorNumElements();
4731   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4732   unsigned NumLaneElts = NumElts/NumLanes;
4733
4734   int Val = 0;
4735   unsigned i;
4736   for (i = 0; i != NumElts; ++i) {
4737     Val = SVOp->getMaskElt(i);
4738     if (Val >= 0)
4739       break;
4740   }
4741   if (Val >= (int)NumElts)
4742     Val -= NumElts - NumLaneElts;
4743
4744   assert(Val - i > 0 && "PALIGNR imm should be positive");
4745   return (Val - i) * EltSize;
4746 }
4747
4748 /// \brief Return the appropriate immediate to shuffle the specified
4749 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4750 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4751   return getShuffleAlignrImmediate(SVOp, false);
4752 }
4753
4754 /// \brief Return the appropriate immediate to shuffle the specified
4755 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4756 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4757   return getShuffleAlignrImmediate(SVOp, true);
4758 }
4759
4760
4761 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4762   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4763   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4764     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4765
4766   uint64_t Index =
4767     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4768
4769   MVT VecVT = N->getOperand(0).getSimpleValueType();
4770   MVT ElVT = VecVT.getVectorElementType();
4771
4772   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4773   return Index / NumElemsPerChunk;
4774 }
4775
4776 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4777   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4778   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4779     llvm_unreachable("Illegal insert subvector for VINSERT");
4780
4781   uint64_t Index =
4782     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4783
4784   MVT VecVT = N->getSimpleValueType(0);
4785   MVT ElVT = VecVT.getVectorElementType();
4786
4787   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4788   return Index / NumElemsPerChunk;
4789 }
4790
4791 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4792 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4793 /// and VINSERTI128 instructions.
4794 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4795   return getExtractVEXTRACTImmediate(N, 128);
4796 }
4797
4798 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4799 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4800 /// and VINSERTI64x4 instructions.
4801 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4802   return getExtractVEXTRACTImmediate(N, 256);
4803 }
4804
4805 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4806 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4807 /// and VINSERTI128 instructions.
4808 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4809   return getInsertVINSERTImmediate(N, 128);
4810 }
4811
4812 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4813 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4814 /// and VINSERTI64x4 instructions.
4815 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4816   return getInsertVINSERTImmediate(N, 256);
4817 }
4818
4819 /// isZero - Returns true if Elt is a constant integer zero
4820 static bool isZero(SDValue V) {
4821   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4822   return C && C->isNullValue();
4823 }
4824
4825 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4826 /// constant +0.0.
4827 bool X86::isZeroNode(SDValue Elt) {
4828   if (isZero(Elt))
4829     return true;
4830   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4831     return CFP->getValueAPF().isPosZero();
4832   return false;
4833 }
4834
4835 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4836 /// match movhlps. The lower half elements should come from upper half of
4837 /// V1 (and in order), and the upper half elements should come from the upper
4838 /// half of V2 (and in order).
4839 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4840   if (!VT.is128BitVector())
4841     return false;
4842   if (VT.getVectorNumElements() != 4)
4843     return false;
4844   for (unsigned i = 0, e = 2; i != e; ++i)
4845     if (!isUndefOrEqual(Mask[i], i+2))
4846       return false;
4847   for (unsigned i = 2; i != 4; ++i)
4848     if (!isUndefOrEqual(Mask[i], i+4))
4849       return false;
4850   return true;
4851 }
4852
4853 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4854 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4855 /// required.
4856 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4857   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4858     return false;
4859   N = N->getOperand(0).getNode();
4860   if (!ISD::isNON_EXTLoad(N))
4861     return false;
4862   if (LD)
4863     *LD = cast<LoadSDNode>(N);
4864   return true;
4865 }
4866
4867 // Test whether the given value is a vector value which will be legalized
4868 // into a load.
4869 static bool WillBeConstantPoolLoad(SDNode *N) {
4870   if (N->getOpcode() != ISD::BUILD_VECTOR)
4871     return false;
4872
4873   // Check for any non-constant elements.
4874   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4875     switch (N->getOperand(i).getNode()->getOpcode()) {
4876     case ISD::UNDEF:
4877     case ISD::ConstantFP:
4878     case ISD::Constant:
4879       break;
4880     default:
4881       return false;
4882     }
4883
4884   // Vectors of all-zeros and all-ones are materialized with special
4885   // instructions rather than being loaded.
4886   return !ISD::isBuildVectorAllZeros(N) &&
4887          !ISD::isBuildVectorAllOnes(N);
4888 }
4889
4890 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4891 /// match movlp{s|d}. The lower half elements should come from lower half of
4892 /// V1 (and in order), and the upper half elements should come from the upper
4893 /// half of V2 (and in order). And since V1 will become the source of the
4894 /// MOVLP, it must be either a vector load or a scalar load to vector.
4895 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4896                                ArrayRef<int> Mask, MVT VT) {
4897   if (!VT.is128BitVector())
4898     return false;
4899
4900   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4901     return false;
4902   // Is V2 is a vector load, don't do this transformation. We will try to use
4903   // load folding shufps op.
4904   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4905     return false;
4906
4907   unsigned NumElems = VT.getVectorNumElements();
4908
4909   if (NumElems != 2 && NumElems != 4)
4910     return false;
4911   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4912     if (!isUndefOrEqual(Mask[i], i))
4913       return false;
4914   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4915     if (!isUndefOrEqual(Mask[i], i+NumElems))
4916       return false;
4917   return true;
4918 }
4919
4920 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4921 /// to an zero vector.
4922 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4923 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4924   SDValue V1 = N->getOperand(0);
4925   SDValue V2 = N->getOperand(1);
4926   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4927   for (unsigned i = 0; i != NumElems; ++i) {
4928     int Idx = N->getMaskElt(i);
4929     if (Idx >= (int)NumElems) {
4930       unsigned Opc = V2.getOpcode();
4931       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4932         continue;
4933       if (Opc != ISD::BUILD_VECTOR ||
4934           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4935         return false;
4936     } else if (Idx >= 0) {
4937       unsigned Opc = V1.getOpcode();
4938       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4939         continue;
4940       if (Opc != ISD::BUILD_VECTOR ||
4941           !X86::isZeroNode(V1.getOperand(Idx)))
4942         return false;
4943     }
4944   }
4945   return true;
4946 }
4947
4948 /// getZeroVector - Returns a vector of specified type with all zero elements.
4949 ///
4950 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4951                              SelectionDAG &DAG, SDLoc dl) {
4952   assert(VT.isVector() && "Expected a vector type");
4953
4954   // Always build SSE zero vectors as <4 x i32> bitcasted
4955   // to their dest type. This ensures they get CSE'd.
4956   SDValue Vec;
4957   if (VT.is128BitVector()) {  // SSE
4958     if (Subtarget->hasSSE2()) {  // SSE2
4959       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4960       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4961     } else { // SSE1
4962       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4963       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4964     }
4965   } else if (VT.is256BitVector()) { // AVX
4966     if (Subtarget->hasInt256()) { // AVX2
4967       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4968       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4969       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4970     } else {
4971       // 256-bit logic and arithmetic instructions in AVX are all
4972       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4973       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4974       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4975       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4976     }
4977   } else if (VT.is512BitVector()) { // AVX-512
4978       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4979       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4980                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4981       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4982   } else if (VT.getScalarType() == MVT::i1) {
4983     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4984     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4985     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4986     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4987   } else
4988     llvm_unreachable("Unexpected vector type");
4989
4990   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4991 }
4992
4993 /// getOnesVector - Returns a vector of specified type with all bits set.
4994 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4995 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4996 /// Then bitcast to their original type, ensuring they get CSE'd.
4997 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4998                              SDLoc dl) {
4999   assert(VT.isVector() && "Expected a vector type");
5000
5001   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5002   SDValue Vec;
5003   if (VT.is256BitVector()) {
5004     if (HasInt256) { // AVX2
5005       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5006       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5007     } else { // AVX
5008       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5009       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5010     }
5011   } else if (VT.is128BitVector()) {
5012     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5013   } else
5014     llvm_unreachable("Unexpected vector type");
5015
5016   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5017 }
5018
5019 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5020 /// that point to V2 points to its first element.
5021 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5022   for (unsigned i = 0; i != NumElems; ++i) {
5023     if (Mask[i] > (int)NumElems) {
5024       Mask[i] = NumElems;
5025     }
5026   }
5027 }
5028
5029 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5030 /// operation of specified width.
5031 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5032                        SDValue V2) {
5033   unsigned NumElems = VT.getVectorNumElements();
5034   SmallVector<int, 8> Mask;
5035   Mask.push_back(NumElems);
5036   for (unsigned i = 1; i != NumElems; ++i)
5037     Mask.push_back(i);
5038   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5039 }
5040
5041 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5042 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5043                           SDValue V2) {
5044   unsigned NumElems = VT.getVectorNumElements();
5045   SmallVector<int, 8> Mask;
5046   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5047     Mask.push_back(i);
5048     Mask.push_back(i + NumElems);
5049   }
5050   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5051 }
5052
5053 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5054 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5055                           SDValue V2) {
5056   unsigned NumElems = VT.getVectorNumElements();
5057   SmallVector<int, 8> Mask;
5058   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5059     Mask.push_back(i + Half);
5060     Mask.push_back(i + NumElems + Half);
5061   }
5062   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5063 }
5064
5065 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5066 // a generic shuffle instruction because the target has no such instructions.
5067 // Generate shuffles which repeat i16 and i8 several times until they can be
5068 // represented by v4f32 and then be manipulated by target suported shuffles.
5069 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5070   MVT VT = V.getSimpleValueType();
5071   int NumElems = VT.getVectorNumElements();
5072   SDLoc dl(V);
5073
5074   while (NumElems > 4) {
5075     if (EltNo < NumElems/2) {
5076       V = getUnpackl(DAG, dl, VT, V, V);
5077     } else {
5078       V = getUnpackh(DAG, dl, VT, V, V);
5079       EltNo -= NumElems/2;
5080     }
5081     NumElems >>= 1;
5082   }
5083   return V;
5084 }
5085
5086 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5087 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5088   MVT VT = V.getSimpleValueType();
5089   SDLoc dl(V);
5090
5091   if (VT.is128BitVector()) {
5092     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5093     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5094     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5095                              &SplatMask[0]);
5096   } else if (VT.is256BitVector()) {
5097     // To use VPERMILPS to splat scalars, the second half of indicies must
5098     // refer to the higher part, which is a duplication of the lower one,
5099     // because VPERMILPS can only handle in-lane permutations.
5100     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5101                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5102
5103     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5104     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5105                              &SplatMask[0]);
5106   } else
5107     llvm_unreachable("Vector size not supported");
5108
5109   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5110 }
5111
5112 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5113 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5114   MVT SrcVT = SV->getSimpleValueType(0);
5115   SDValue V1 = SV->getOperand(0);
5116   SDLoc dl(SV);
5117
5118   int EltNo = SV->getSplatIndex();
5119   int NumElems = SrcVT.getVectorNumElements();
5120   bool Is256BitVec = SrcVT.is256BitVector();
5121
5122   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5123          "Unknown how to promote splat for type");
5124
5125   // Extract the 128-bit part containing the splat element and update
5126   // the splat element index when it refers to the higher register.
5127   if (Is256BitVec) {
5128     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5129     if (EltNo >= NumElems/2)
5130       EltNo -= NumElems/2;
5131   }
5132
5133   // All i16 and i8 vector types can't be used directly by a generic shuffle
5134   // instruction because the target has no such instruction. Generate shuffles
5135   // which repeat i16 and i8 several times until they fit in i32, and then can
5136   // be manipulated by target suported shuffles.
5137   MVT EltVT = SrcVT.getVectorElementType();
5138   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5139     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5140
5141   // Recreate the 256-bit vector and place the same 128-bit vector
5142   // into the low and high part. This is necessary because we want
5143   // to use VPERM* to shuffle the vectors
5144   if (Is256BitVec) {
5145     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5146   }
5147
5148   return getLegalSplat(DAG, V1, EltNo);
5149 }
5150
5151 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5152 /// vector of zero or undef vector.  This produces a shuffle where the low
5153 /// element of V2 is swizzled into the zero/undef vector, landing at element
5154 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5155 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5156                                            bool IsZero,
5157                                            const X86Subtarget *Subtarget,
5158                                            SelectionDAG &DAG) {
5159   MVT VT = V2.getSimpleValueType();
5160   SDValue V1 = IsZero
5161     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5162   unsigned NumElems = VT.getVectorNumElements();
5163   SmallVector<int, 16> MaskVec;
5164   for (unsigned i = 0; i != NumElems; ++i)
5165     // If this is the insertion idx, put the low elt of V2 here.
5166     MaskVec.push_back(i == Idx ? NumElems : i);
5167   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5168 }
5169
5170 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5171 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5172 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5173 /// shuffles which use a single input multiple times, and in those cases it will
5174 /// adjust the mask to only have indices within that single input.
5175 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5176                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5177   unsigned NumElems = VT.getVectorNumElements();
5178   SDValue ImmN;
5179
5180   IsUnary = false;
5181   bool IsFakeUnary = false;
5182   switch(N->getOpcode()) {
5183   case X86ISD::SHUFP:
5184     ImmN = N->getOperand(N->getNumOperands()-1);
5185     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5186     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5187     break;
5188   case X86ISD::UNPCKH:
5189     DecodeUNPCKHMask(VT, Mask);
5190     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5191     break;
5192   case X86ISD::UNPCKL:
5193     DecodeUNPCKLMask(VT, Mask);
5194     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5195     break;
5196   case X86ISD::MOVHLPS:
5197     DecodeMOVHLPSMask(NumElems, Mask);
5198     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5199     break;
5200   case X86ISD::MOVLHPS:
5201     DecodeMOVLHPSMask(NumElems, Mask);
5202     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5203     break;
5204   case X86ISD::PALIGNR:
5205     ImmN = N->getOperand(N->getNumOperands()-1);
5206     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5207     break;
5208   case X86ISD::PSHUFD:
5209   case X86ISD::VPERMILP:
5210     ImmN = N->getOperand(N->getNumOperands()-1);
5211     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5212     IsUnary = true;
5213     break;
5214   case X86ISD::PSHUFHW:
5215     ImmN = N->getOperand(N->getNumOperands()-1);
5216     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5217     IsUnary = true;
5218     break;
5219   case X86ISD::PSHUFLW:
5220     ImmN = N->getOperand(N->getNumOperands()-1);
5221     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5222     IsUnary = true;
5223     break;
5224   case X86ISD::PSHUFB: {
5225     IsUnary = true;
5226     SDValue MaskNode = N->getOperand(1);
5227     while (MaskNode->getOpcode() == ISD::BITCAST)
5228       MaskNode = MaskNode->getOperand(0);
5229
5230     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5231       // If we have a build-vector, then things are easy.
5232       EVT VT = MaskNode.getValueType();
5233       assert(VT.isVector() &&
5234              "Can't produce a non-vector with a build_vector!");
5235       if (!VT.isInteger())
5236         return false;
5237
5238       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5239
5240       SmallVector<uint64_t, 32> RawMask;
5241       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5242         auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5243         if (!CN)
5244           return false;
5245         APInt MaskElement = CN->getAPIntValue();
5246
5247         // We now have to decode the element which could be any integer size and
5248         // extract each byte of it.
5249         for (int j = 0; j < NumBytesPerElement; ++j) {
5250           // Note that this is x86 and so always little endian: the low byte is
5251           // the first byte of the mask.
5252           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5253           MaskElement = MaskElement.lshr(8);
5254         }
5255       }
5256       DecodePSHUFBMask(RawMask, Mask);
5257       break;
5258     }
5259
5260     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5261     if (!MaskLoad)
5262       return false;
5263
5264     SDValue Ptr = MaskLoad->getBasePtr();
5265     if (Ptr->getOpcode() == X86ISD::Wrapper)
5266       Ptr = Ptr->getOperand(0);
5267
5268     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5269     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5270       return false;
5271
5272     if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5273       // FIXME: Support AVX-512 here.
5274       if (!C->getType()->isVectorTy() ||
5275           (C->getNumElements() != 16 && C->getNumElements() != 32))
5276         return false;
5277
5278       assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5279       DecodePSHUFBMask(C, Mask);
5280       break;
5281     }
5282
5283     return false;
5284   }
5285   case X86ISD::VPERMI:
5286     ImmN = N->getOperand(N->getNumOperands()-1);
5287     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5288     IsUnary = true;
5289     break;
5290   case X86ISD::MOVSS:
5291   case X86ISD::MOVSD: {
5292     // The index 0 always comes from the first element of the second source,
5293     // this is why MOVSS and MOVSD are used in the first place. The other
5294     // elements come from the other positions of the first source vector
5295     Mask.push_back(NumElems);
5296     for (unsigned i = 1; i != NumElems; ++i) {
5297       Mask.push_back(i);
5298     }
5299     break;
5300   }
5301   case X86ISD::VPERM2X128:
5302     ImmN = N->getOperand(N->getNumOperands()-1);
5303     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5304     if (Mask.empty()) return false;
5305     break;
5306   case X86ISD::MOVDDUP:
5307   case X86ISD::MOVLHPD:
5308   case X86ISD::MOVLPD:
5309   case X86ISD::MOVLPS:
5310   case X86ISD::MOVSHDUP:
5311   case X86ISD::MOVSLDUP:
5312     // Not yet implemented
5313     return false;
5314   default: llvm_unreachable("unknown target shuffle node");
5315   }
5316
5317   // If we have a fake unary shuffle, the shuffle mask is spread across two
5318   // inputs that are actually the same node. Re-map the mask to always point
5319   // into the first input.
5320   if (IsFakeUnary)
5321     for (int &M : Mask)
5322       if (M >= (int)Mask.size())
5323         M -= Mask.size();
5324
5325   return true;
5326 }
5327
5328 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5329 /// element of the result of the vector shuffle.
5330 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5331                                    unsigned Depth) {
5332   if (Depth == 6)
5333     return SDValue();  // Limit search depth.
5334
5335   SDValue V = SDValue(N, 0);
5336   EVT VT = V.getValueType();
5337   unsigned Opcode = V.getOpcode();
5338
5339   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5340   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5341     int Elt = SV->getMaskElt(Index);
5342
5343     if (Elt < 0)
5344       return DAG.getUNDEF(VT.getVectorElementType());
5345
5346     unsigned NumElems = VT.getVectorNumElements();
5347     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5348                                          : SV->getOperand(1);
5349     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5350   }
5351
5352   // Recurse into target specific vector shuffles to find scalars.
5353   if (isTargetShuffle(Opcode)) {
5354     MVT ShufVT = V.getSimpleValueType();
5355     unsigned NumElems = ShufVT.getVectorNumElements();
5356     SmallVector<int, 16> ShuffleMask;
5357     bool IsUnary;
5358
5359     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5360       return SDValue();
5361
5362     int Elt = ShuffleMask[Index];
5363     if (Elt < 0)
5364       return DAG.getUNDEF(ShufVT.getVectorElementType());
5365
5366     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5367                                          : N->getOperand(1);
5368     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5369                                Depth+1);
5370   }
5371
5372   // Actual nodes that may contain scalar elements
5373   if (Opcode == ISD::BITCAST) {
5374     V = V.getOperand(0);
5375     EVT SrcVT = V.getValueType();
5376     unsigned NumElems = VT.getVectorNumElements();
5377
5378     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5379       return SDValue();
5380   }
5381
5382   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5383     return (Index == 0) ? V.getOperand(0)
5384                         : DAG.getUNDEF(VT.getVectorElementType());
5385
5386   if (V.getOpcode() == ISD::BUILD_VECTOR)
5387     return V.getOperand(Index);
5388
5389   return SDValue();
5390 }
5391
5392 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5393 /// shuffle operation which come from a consecutively from a zero. The
5394 /// search can start in two different directions, from left or right.
5395 /// We count undefs as zeros until PreferredNum is reached.
5396 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5397                                          unsigned NumElems, bool ZerosFromLeft,
5398                                          SelectionDAG &DAG,
5399                                          unsigned PreferredNum = -1U) {
5400   unsigned NumZeros = 0;
5401   for (unsigned i = 0; i != NumElems; ++i) {
5402     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5403     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5404     if (!Elt.getNode())
5405       break;
5406
5407     if (X86::isZeroNode(Elt))
5408       ++NumZeros;
5409     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5410       NumZeros = std::min(NumZeros + 1, PreferredNum);
5411     else
5412       break;
5413   }
5414
5415   return NumZeros;
5416 }
5417
5418 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5419 /// correspond consecutively to elements from one of the vector operands,
5420 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5421 static
5422 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5423                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5424                               unsigned NumElems, unsigned &OpNum) {
5425   bool SeenV1 = false;
5426   bool SeenV2 = false;
5427
5428   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5429     int Idx = SVOp->getMaskElt(i);
5430     // Ignore undef indicies
5431     if (Idx < 0)
5432       continue;
5433
5434     if (Idx < (int)NumElems)
5435       SeenV1 = true;
5436     else
5437       SeenV2 = true;
5438
5439     // Only accept consecutive elements from the same vector
5440     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5441       return false;
5442   }
5443
5444   OpNum = SeenV1 ? 0 : 1;
5445   return true;
5446 }
5447
5448 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5449 /// logical left shift of a vector.
5450 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5451                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5452   unsigned NumElems =
5453     SVOp->getSimpleValueType(0).getVectorNumElements();
5454   unsigned NumZeros = getNumOfConsecutiveZeros(
5455       SVOp, NumElems, false /* check zeros from right */, DAG,
5456       SVOp->getMaskElt(0));
5457   unsigned OpSrc;
5458
5459   if (!NumZeros)
5460     return false;
5461
5462   // Considering the elements in the mask that are not consecutive zeros,
5463   // check if they consecutively come from only one of the source vectors.
5464   //
5465   //               V1 = {X, A, B, C}     0
5466   //                         \  \  \    /
5467   //   vector_shuffle V1, V2 <1, 2, 3, X>
5468   //
5469   if (!isShuffleMaskConsecutive(SVOp,
5470             0,                   // Mask Start Index
5471             NumElems-NumZeros,   // Mask End Index(exclusive)
5472             NumZeros,            // Where to start looking in the src vector
5473             NumElems,            // Number of elements in vector
5474             OpSrc))              // Which source operand ?
5475     return false;
5476
5477   isLeft = false;
5478   ShAmt = NumZeros;
5479   ShVal = SVOp->getOperand(OpSrc);
5480   return true;
5481 }
5482
5483 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5484 /// logical left shift of a vector.
5485 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5486                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5487   unsigned NumElems =
5488     SVOp->getSimpleValueType(0).getVectorNumElements();
5489   unsigned NumZeros = getNumOfConsecutiveZeros(
5490       SVOp, NumElems, true /* check zeros from left */, DAG,
5491       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5492   unsigned OpSrc;
5493
5494   if (!NumZeros)
5495     return false;
5496
5497   // Considering the elements in the mask that are not consecutive zeros,
5498   // check if they consecutively come from only one of the source vectors.
5499   //
5500   //                           0    { A, B, X, X } = V2
5501   //                          / \    /  /
5502   //   vector_shuffle V1, V2 <X, X, 4, 5>
5503   //
5504   if (!isShuffleMaskConsecutive(SVOp,
5505             NumZeros,     // Mask Start Index
5506             NumElems,     // Mask End Index(exclusive)
5507             0,            // Where to start looking in the src vector
5508             NumElems,     // Number of elements in vector
5509             OpSrc))       // Which source operand ?
5510     return false;
5511
5512   isLeft = true;
5513   ShAmt = NumZeros;
5514   ShVal = SVOp->getOperand(OpSrc);
5515   return true;
5516 }
5517
5518 /// isVectorShift - Returns true if the shuffle can be implemented as a
5519 /// logical left or right shift of a vector.
5520 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5521                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5522   // Although the logic below support any bitwidth size, there are no
5523   // shift instructions which handle more than 128-bit vectors.
5524   if (!SVOp->getSimpleValueType(0).is128BitVector())
5525     return false;
5526
5527   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5528       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5529     return true;
5530
5531   return false;
5532 }
5533
5534 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5535 ///
5536 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5537                                        unsigned NumNonZero, unsigned NumZero,
5538                                        SelectionDAG &DAG,
5539                                        const X86Subtarget* Subtarget,
5540                                        const TargetLowering &TLI) {
5541   if (NumNonZero > 8)
5542     return SDValue();
5543
5544   SDLoc dl(Op);
5545   SDValue V;
5546   bool First = true;
5547   for (unsigned i = 0; i < 16; ++i) {
5548     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5549     if (ThisIsNonZero && First) {
5550       if (NumZero)
5551         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5552       else
5553         V = DAG.getUNDEF(MVT::v8i16);
5554       First = false;
5555     }
5556
5557     if ((i & 1) != 0) {
5558       SDValue ThisElt, LastElt;
5559       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5560       if (LastIsNonZero) {
5561         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5562                               MVT::i16, Op.getOperand(i-1));
5563       }
5564       if (ThisIsNonZero) {
5565         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5566         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5567                               ThisElt, DAG.getConstant(8, MVT::i8));
5568         if (LastIsNonZero)
5569           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5570       } else
5571         ThisElt = LastElt;
5572
5573       if (ThisElt.getNode())
5574         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5575                         DAG.getIntPtrConstant(i/2));
5576     }
5577   }
5578
5579   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5580 }
5581
5582 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5583 ///
5584 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5585                                      unsigned NumNonZero, unsigned NumZero,
5586                                      SelectionDAG &DAG,
5587                                      const X86Subtarget* Subtarget,
5588                                      const TargetLowering &TLI) {
5589   if (NumNonZero > 4)
5590     return SDValue();
5591
5592   SDLoc dl(Op);
5593   SDValue V;
5594   bool First = true;
5595   for (unsigned i = 0; i < 8; ++i) {
5596     bool isNonZero = (NonZeros & (1 << i)) != 0;
5597     if (isNonZero) {
5598       if (First) {
5599         if (NumZero)
5600           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5601         else
5602           V = DAG.getUNDEF(MVT::v8i16);
5603         First = false;
5604       }
5605       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5606                       MVT::v8i16, V, Op.getOperand(i),
5607                       DAG.getIntPtrConstant(i));
5608     }
5609   }
5610
5611   return V;
5612 }
5613
5614 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5615 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5616                                      unsigned NonZeros, unsigned NumNonZero,
5617                                      unsigned NumZero, SelectionDAG &DAG,
5618                                      const X86Subtarget *Subtarget,
5619                                      const TargetLowering &TLI) {
5620   // We know there's at least one non-zero element
5621   unsigned FirstNonZeroIdx = 0;
5622   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5623   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5624          X86::isZeroNode(FirstNonZero)) {
5625     ++FirstNonZeroIdx;
5626     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5627   }
5628
5629   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5630       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5631     return SDValue();
5632
5633   SDValue V = FirstNonZero.getOperand(0);
5634   MVT VVT = V.getSimpleValueType();
5635   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5636     return SDValue();
5637
5638   unsigned FirstNonZeroDst =
5639       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5640   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5641   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5642   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5643
5644   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5645     SDValue Elem = Op.getOperand(Idx);
5646     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5647       continue;
5648
5649     // TODO: What else can be here? Deal with it.
5650     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5651       return SDValue();
5652
5653     // TODO: Some optimizations are still possible here
5654     // ex: Getting one element from a vector, and the rest from another.
5655     if (Elem.getOperand(0) != V)
5656       return SDValue();
5657
5658     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5659     if (Dst == Idx)
5660       ++CorrectIdx;
5661     else if (IncorrectIdx == -1U) {
5662       IncorrectIdx = Idx;
5663       IncorrectDst = Dst;
5664     } else
5665       // There was already one element with an incorrect index.
5666       // We can't optimize this case to an insertps.
5667       return SDValue();
5668   }
5669
5670   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5671     SDLoc dl(Op);
5672     EVT VT = Op.getSimpleValueType();
5673     unsigned ElementMoveMask = 0;
5674     if (IncorrectIdx == -1U)
5675       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5676     else
5677       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5678
5679     SDValue InsertpsMask =
5680         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5681     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5682   }
5683
5684   return SDValue();
5685 }
5686
5687 /// getVShift - Return a vector logical shift node.
5688 ///
5689 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5690                          unsigned NumBits, SelectionDAG &DAG,
5691                          const TargetLowering &TLI, SDLoc dl) {
5692   assert(VT.is128BitVector() && "Unknown type for VShift");
5693   EVT ShVT = MVT::v2i64;
5694   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5695   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5696   return DAG.getNode(ISD::BITCAST, dl, VT,
5697                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5698                              DAG.getConstant(NumBits,
5699                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5700 }
5701
5702 static SDValue
5703 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5704
5705   // Check if the scalar load can be widened into a vector load. And if
5706   // the address is "base + cst" see if the cst can be "absorbed" into
5707   // the shuffle mask.
5708   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5709     SDValue Ptr = LD->getBasePtr();
5710     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5711       return SDValue();
5712     EVT PVT = LD->getValueType(0);
5713     if (PVT != MVT::i32 && PVT != MVT::f32)
5714       return SDValue();
5715
5716     int FI = -1;
5717     int64_t Offset = 0;
5718     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5719       FI = FINode->getIndex();
5720       Offset = 0;
5721     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5722                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5723       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5724       Offset = Ptr.getConstantOperandVal(1);
5725       Ptr = Ptr.getOperand(0);
5726     } else {
5727       return SDValue();
5728     }
5729
5730     // FIXME: 256-bit vector instructions don't require a strict alignment,
5731     // improve this code to support it better.
5732     unsigned RequiredAlign = VT.getSizeInBits()/8;
5733     SDValue Chain = LD->getChain();
5734     // Make sure the stack object alignment is at least 16 or 32.
5735     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5736     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5737       if (MFI->isFixedObjectIndex(FI)) {
5738         // Can't change the alignment. FIXME: It's possible to compute
5739         // the exact stack offset and reference FI + adjust offset instead.
5740         // If someone *really* cares about this. That's the way to implement it.
5741         return SDValue();
5742       } else {
5743         MFI->setObjectAlignment(FI, RequiredAlign);
5744       }
5745     }
5746
5747     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5748     // Ptr + (Offset & ~15).
5749     if (Offset < 0)
5750       return SDValue();
5751     if ((Offset % RequiredAlign) & 3)
5752       return SDValue();
5753     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5754     if (StartOffset)
5755       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5756                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5757
5758     int EltNo = (Offset - StartOffset) >> 2;
5759     unsigned NumElems = VT.getVectorNumElements();
5760
5761     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5762     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5763                              LD->getPointerInfo().getWithOffset(StartOffset),
5764                              false, false, false, 0);
5765
5766     SmallVector<int, 8> Mask;
5767     for (unsigned i = 0; i != NumElems; ++i)
5768       Mask.push_back(EltNo);
5769
5770     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5771   }
5772
5773   return SDValue();
5774 }
5775
5776 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5777 /// vector of type 'VT', see if the elements can be replaced by a single large
5778 /// load which has the same value as a build_vector whose operands are 'elts'.
5779 ///
5780 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5781 ///
5782 /// FIXME: we'd also like to handle the case where the last elements are zero
5783 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5784 /// There's even a handy isZeroNode for that purpose.
5785 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5786                                         SDLoc &DL, SelectionDAG &DAG,
5787                                         bool isAfterLegalize) {
5788   EVT EltVT = VT.getVectorElementType();
5789   unsigned NumElems = Elts.size();
5790
5791   LoadSDNode *LDBase = nullptr;
5792   unsigned LastLoadedElt = -1U;
5793
5794   // For each element in the initializer, see if we've found a load or an undef.
5795   // If we don't find an initial load element, or later load elements are
5796   // non-consecutive, bail out.
5797   for (unsigned i = 0; i < NumElems; ++i) {
5798     SDValue Elt = Elts[i];
5799
5800     if (!Elt.getNode() ||
5801         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5802       return SDValue();
5803     if (!LDBase) {
5804       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5805         return SDValue();
5806       LDBase = cast<LoadSDNode>(Elt.getNode());
5807       LastLoadedElt = i;
5808       continue;
5809     }
5810     if (Elt.getOpcode() == ISD::UNDEF)
5811       continue;
5812
5813     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5814     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5815       return SDValue();
5816     LastLoadedElt = i;
5817   }
5818
5819   // If we have found an entire vector of loads and undefs, then return a large
5820   // load of the entire vector width starting at the base pointer.  If we found
5821   // consecutive loads for the low half, generate a vzext_load node.
5822   if (LastLoadedElt == NumElems - 1) {
5823
5824     if (isAfterLegalize &&
5825         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5826       return SDValue();
5827
5828     SDValue NewLd = SDValue();
5829
5830     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5831       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5832                           LDBase->getPointerInfo(),
5833                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5834                           LDBase->isInvariant(), 0);
5835     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5836                         LDBase->getPointerInfo(),
5837                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5838                         LDBase->isInvariant(), LDBase->getAlignment());
5839
5840     if (LDBase->hasAnyUseOfValue(1)) {
5841       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5842                                      SDValue(LDBase, 1),
5843                                      SDValue(NewLd.getNode(), 1));
5844       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5845       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5846                              SDValue(NewLd.getNode(), 1));
5847     }
5848
5849     return NewLd;
5850   }
5851   if (NumElems == 4 && LastLoadedElt == 1 &&
5852       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5853     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5854     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5855     SDValue ResNode =
5856         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5857                                 LDBase->getPointerInfo(),
5858                                 LDBase->getAlignment(),
5859                                 false/*isVolatile*/, true/*ReadMem*/,
5860                                 false/*WriteMem*/);
5861
5862     // Make sure the newly-created LOAD is in the same position as LDBase in
5863     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5864     // update uses of LDBase's output chain to use the TokenFactor.
5865     if (LDBase->hasAnyUseOfValue(1)) {
5866       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5867                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5868       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5869       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5870                              SDValue(ResNode.getNode(), 1));
5871     }
5872
5873     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5874   }
5875   return SDValue();
5876 }
5877
5878 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5879 /// to generate a splat value for the following cases:
5880 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5881 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5882 /// a scalar load, or a constant.
5883 /// The VBROADCAST node is returned when a pattern is found,
5884 /// or SDValue() otherwise.
5885 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5886                                     SelectionDAG &DAG) {
5887   if (!Subtarget->hasFp256())
5888     return SDValue();
5889
5890   MVT VT = Op.getSimpleValueType();
5891   SDLoc dl(Op);
5892
5893   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5894          "Unsupported vector type for broadcast.");
5895
5896   SDValue Ld;
5897   bool ConstSplatVal;
5898
5899   switch (Op.getOpcode()) {
5900     default:
5901       // Unknown pattern found.
5902       return SDValue();
5903
5904     case ISD::BUILD_VECTOR: {
5905       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5906       BitVector UndefElements;
5907       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5908
5909       // We need a splat of a single value to use broadcast, and it doesn't
5910       // make any sense if the value is only in one element of the vector.
5911       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5912         return SDValue();
5913
5914       Ld = Splat;
5915       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5916                        Ld.getOpcode() == ISD::ConstantFP);
5917
5918       // Make sure that all of the users of a non-constant load are from the
5919       // BUILD_VECTOR node.
5920       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5921         return SDValue();
5922       break;
5923     }
5924
5925     case ISD::VECTOR_SHUFFLE: {
5926       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5927
5928       // Shuffles must have a splat mask where the first element is
5929       // broadcasted.
5930       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5931         return SDValue();
5932
5933       SDValue Sc = Op.getOperand(0);
5934       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5935           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5936
5937         if (!Subtarget->hasInt256())
5938           return SDValue();
5939
5940         // Use the register form of the broadcast instruction available on AVX2.
5941         if (VT.getSizeInBits() >= 256)
5942           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5943         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5944       }
5945
5946       Ld = Sc.getOperand(0);
5947       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5948                        Ld.getOpcode() == ISD::ConstantFP);
5949
5950       // The scalar_to_vector node and the suspected
5951       // load node must have exactly one user.
5952       // Constants may have multiple users.
5953
5954       // AVX-512 has register version of the broadcast
5955       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5956         Ld.getValueType().getSizeInBits() >= 32;
5957       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5958           !hasRegVer))
5959         return SDValue();
5960       break;
5961     }
5962   }
5963
5964   bool IsGE256 = (VT.getSizeInBits() >= 256);
5965
5966   // Handle the broadcasting a single constant scalar from the constant pool
5967   // into a vector. On Sandybridge it is still better to load a constant vector
5968   // from the constant pool and not to broadcast it from a scalar.
5969   if (ConstSplatVal && Subtarget->hasInt256()) {
5970     EVT CVT = Ld.getValueType();
5971     assert(!CVT.isVector() && "Must not broadcast a vector type");
5972     unsigned ScalarSize = CVT.getSizeInBits();
5973
5974     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5975       const Constant *C = nullptr;
5976       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5977         C = CI->getConstantIntValue();
5978       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5979         C = CF->getConstantFPValue();
5980
5981       assert(C && "Invalid constant type");
5982
5983       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5984       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5985       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5986       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5987                        MachinePointerInfo::getConstantPool(),
5988                        false, false, false, Alignment);
5989
5990       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5991     }
5992   }
5993
5994   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5995   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5996
5997   // Handle AVX2 in-register broadcasts.
5998   if (!IsLoad && Subtarget->hasInt256() &&
5999       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6000     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6001
6002   // The scalar source must be a normal load.
6003   if (!IsLoad)
6004     return SDValue();
6005
6006   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6007     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6008
6009   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6010   // double since there is no vbroadcastsd xmm
6011   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6012     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6013       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6014   }
6015
6016   // Unsupported broadcast.
6017   return SDValue();
6018 }
6019
6020 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6021 /// underlying vector and index.
6022 ///
6023 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6024 /// index.
6025 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6026                                          SDValue ExtIdx) {
6027   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6028   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6029     return Idx;
6030
6031   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6032   // lowered this:
6033   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6034   // to:
6035   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6036   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6037   //                           undef)
6038   //                       Constant<0>)
6039   // In this case the vector is the extract_subvector expression and the index
6040   // is 2, as specified by the shuffle.
6041   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6042   SDValue ShuffleVec = SVOp->getOperand(0);
6043   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6044   assert(ShuffleVecVT.getVectorElementType() ==
6045          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6046
6047   int ShuffleIdx = SVOp->getMaskElt(Idx);
6048   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6049     ExtractedFromVec = ShuffleVec;
6050     return ShuffleIdx;
6051   }
6052   return Idx;
6053 }
6054
6055 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6056   MVT VT = Op.getSimpleValueType();
6057
6058   // Skip if insert_vec_elt is not supported.
6059   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6060   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6061     return SDValue();
6062
6063   SDLoc DL(Op);
6064   unsigned NumElems = Op.getNumOperands();
6065
6066   SDValue VecIn1;
6067   SDValue VecIn2;
6068   SmallVector<unsigned, 4> InsertIndices;
6069   SmallVector<int, 8> Mask(NumElems, -1);
6070
6071   for (unsigned i = 0; i != NumElems; ++i) {
6072     unsigned Opc = Op.getOperand(i).getOpcode();
6073
6074     if (Opc == ISD::UNDEF)
6075       continue;
6076
6077     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6078       // Quit if more than 1 elements need inserting.
6079       if (InsertIndices.size() > 1)
6080         return SDValue();
6081
6082       InsertIndices.push_back(i);
6083       continue;
6084     }
6085
6086     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6087     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6088     // Quit if non-constant index.
6089     if (!isa<ConstantSDNode>(ExtIdx))
6090       return SDValue();
6091     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6092
6093     // Quit if extracted from vector of different type.
6094     if (ExtractedFromVec.getValueType() != VT)
6095       return SDValue();
6096
6097     if (!VecIn1.getNode())
6098       VecIn1 = ExtractedFromVec;
6099     else if (VecIn1 != ExtractedFromVec) {
6100       if (!VecIn2.getNode())
6101         VecIn2 = ExtractedFromVec;
6102       else if (VecIn2 != ExtractedFromVec)
6103         // Quit if more than 2 vectors to shuffle
6104         return SDValue();
6105     }
6106
6107     if (ExtractedFromVec == VecIn1)
6108       Mask[i] = Idx;
6109     else if (ExtractedFromVec == VecIn2)
6110       Mask[i] = Idx + NumElems;
6111   }
6112
6113   if (!VecIn1.getNode())
6114     return SDValue();
6115
6116   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6117   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6118   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6119     unsigned Idx = InsertIndices[i];
6120     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6121                      DAG.getIntPtrConstant(Idx));
6122   }
6123
6124   return NV;
6125 }
6126
6127 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6128 SDValue
6129 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6130
6131   MVT VT = Op.getSimpleValueType();
6132   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6133          "Unexpected type in LowerBUILD_VECTORvXi1!");
6134
6135   SDLoc dl(Op);
6136   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6137     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6138     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6139     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6140   }
6141
6142   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6143     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6144     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6145     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6146   }
6147
6148   bool AllContants = true;
6149   uint64_t Immediate = 0;
6150   int NonConstIdx = -1;
6151   bool IsSplat = true;
6152   unsigned NumNonConsts = 0;
6153   unsigned NumConsts = 0;
6154   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6155     SDValue In = Op.getOperand(idx);
6156     if (In.getOpcode() == ISD::UNDEF)
6157       continue;
6158     if (!isa<ConstantSDNode>(In)) {
6159       AllContants = false;
6160       NonConstIdx = idx;
6161       NumNonConsts++;
6162     }
6163     else {
6164       NumConsts++;
6165       if (cast<ConstantSDNode>(In)->getZExtValue())
6166       Immediate |= (1ULL << idx);
6167     }
6168     if (In != Op.getOperand(0))
6169       IsSplat = false;
6170   }
6171
6172   if (AllContants) {
6173     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6174       DAG.getConstant(Immediate, MVT::i16));
6175     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6176                        DAG.getIntPtrConstant(0));
6177   }
6178
6179   if (NumNonConsts == 1 && NonConstIdx != 0) {
6180     SDValue DstVec;
6181     if (NumConsts) {
6182       SDValue VecAsImm = DAG.getConstant(Immediate,
6183                                          MVT::getIntegerVT(VT.getSizeInBits()));
6184       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6185     }
6186     else 
6187       DstVec = DAG.getUNDEF(VT);
6188     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6189                        Op.getOperand(NonConstIdx),
6190                        DAG.getIntPtrConstant(NonConstIdx));
6191   }
6192   if (!IsSplat && (NonConstIdx != 0))
6193     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6194   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6195   SDValue Select;
6196   if (IsSplat)
6197     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6198                           DAG.getConstant(-1, SelectVT),
6199                           DAG.getConstant(0, SelectVT));
6200   else
6201     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6202                          DAG.getConstant((Immediate | 1), SelectVT),
6203                          DAG.getConstant(Immediate, SelectVT));
6204   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6205 }
6206
6207 /// \brief Return true if \p N implements a horizontal binop and return the
6208 /// operands for the horizontal binop into V0 and V1.
6209 /// 
6210 /// This is a helper function of PerformBUILD_VECTORCombine.
6211 /// This function checks that the build_vector \p N in input implements a
6212 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6213 /// operation to match.
6214 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6215 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6216 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6217 /// arithmetic sub.
6218 ///
6219 /// This function only analyzes elements of \p N whose indices are
6220 /// in range [BaseIdx, LastIdx).
6221 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6222                               SelectionDAG &DAG,
6223                               unsigned BaseIdx, unsigned LastIdx,
6224                               SDValue &V0, SDValue &V1) {
6225   EVT VT = N->getValueType(0);
6226
6227   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6228   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6229          "Invalid Vector in input!");
6230   
6231   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6232   bool CanFold = true;
6233   unsigned ExpectedVExtractIdx = BaseIdx;
6234   unsigned NumElts = LastIdx - BaseIdx;
6235   V0 = DAG.getUNDEF(VT);
6236   V1 = DAG.getUNDEF(VT);
6237
6238   // Check if N implements a horizontal binop.
6239   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6240     SDValue Op = N->getOperand(i + BaseIdx);
6241
6242     // Skip UNDEFs.
6243     if (Op->getOpcode() == ISD::UNDEF) {
6244       // Update the expected vector extract index.
6245       if (i * 2 == NumElts)
6246         ExpectedVExtractIdx = BaseIdx;
6247       ExpectedVExtractIdx += 2;
6248       continue;
6249     }
6250
6251     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6252
6253     if (!CanFold)
6254       break;
6255
6256     SDValue Op0 = Op.getOperand(0);
6257     SDValue Op1 = Op.getOperand(1);
6258
6259     // Try to match the following pattern:
6260     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6261     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6262         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6263         Op0.getOperand(0) == Op1.getOperand(0) &&
6264         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6265         isa<ConstantSDNode>(Op1.getOperand(1)));
6266     if (!CanFold)
6267       break;
6268
6269     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6270     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6271
6272     if (i * 2 < NumElts) {
6273       if (V0.getOpcode() == ISD::UNDEF)
6274         V0 = Op0.getOperand(0);
6275     } else {
6276       if (V1.getOpcode() == ISD::UNDEF)
6277         V1 = Op0.getOperand(0);
6278       if (i * 2 == NumElts)
6279         ExpectedVExtractIdx = BaseIdx;
6280     }
6281
6282     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6283     if (I0 == ExpectedVExtractIdx)
6284       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6285     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6286       // Try to match the following dag sequence:
6287       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6288       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6289     } else
6290       CanFold = false;
6291
6292     ExpectedVExtractIdx += 2;
6293   }
6294
6295   return CanFold;
6296 }
6297
6298 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6299 /// a concat_vector. 
6300 ///
6301 /// This is a helper function of PerformBUILD_VECTORCombine.
6302 /// This function expects two 256-bit vectors called V0 and V1.
6303 /// At first, each vector is split into two separate 128-bit vectors.
6304 /// Then, the resulting 128-bit vectors are used to implement two
6305 /// horizontal binary operations. 
6306 ///
6307 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6308 ///
6309 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6310 /// the two new horizontal binop.
6311 /// When Mode is set, the first horizontal binop dag node would take as input
6312 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6313 /// horizontal binop dag node would take as input the lower 128-bit of V1
6314 /// and the upper 128-bit of V1.
6315 ///   Example:
6316 ///     HADD V0_LO, V0_HI
6317 ///     HADD V1_LO, V1_HI
6318 ///
6319 /// Otherwise, the first horizontal binop dag node takes as input the lower
6320 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6321 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6322 ///   Example:
6323 ///     HADD V0_LO, V1_LO
6324 ///     HADD V0_HI, V1_HI
6325 ///
6326 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6327 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6328 /// the upper 128-bits of the result.
6329 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6330                                      SDLoc DL, SelectionDAG &DAG,
6331                                      unsigned X86Opcode, bool Mode,
6332                                      bool isUndefLO, bool isUndefHI) {
6333   EVT VT = V0.getValueType();
6334   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6335          "Invalid nodes in input!");
6336
6337   unsigned NumElts = VT.getVectorNumElements();
6338   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6339   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6340   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6341   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6342   EVT NewVT = V0_LO.getValueType();
6343
6344   SDValue LO = DAG.getUNDEF(NewVT);
6345   SDValue HI = DAG.getUNDEF(NewVT);
6346
6347   if (Mode) {
6348     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6349     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6350       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6351     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6352       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6353   } else {
6354     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6355     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6356                        V1_LO->getOpcode() != ISD::UNDEF))
6357       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6358
6359     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6360                        V1_HI->getOpcode() != ISD::UNDEF))
6361       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6362   }
6363
6364   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6365 }
6366
6367 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6368 /// sequence of 'vadd + vsub + blendi'.
6369 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6370                            const X86Subtarget *Subtarget) {
6371   SDLoc DL(BV);
6372   EVT VT = BV->getValueType(0);
6373   unsigned NumElts = VT.getVectorNumElements();
6374   SDValue InVec0 = DAG.getUNDEF(VT);
6375   SDValue InVec1 = DAG.getUNDEF(VT);
6376
6377   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6378           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6379
6380   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6381   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6382   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6383     return SDValue();
6384
6385   // Odd-numbered elements in the input build vector are obtained from
6386   // adding two integer/float elements.
6387   // Even-numbered elements in the input build vector are obtained from
6388   // subtracting two integer/float elements.
6389   unsigned ExpectedOpcode = ISD::FSUB;
6390   unsigned NextExpectedOpcode = ISD::FADD;
6391   bool AddFound = false;
6392   bool SubFound = false;
6393
6394   for (unsigned i = 0, e = NumElts; i != e; i++) {
6395     SDValue Op = BV->getOperand(i);
6396       
6397     // Skip 'undef' values.
6398     unsigned Opcode = Op.getOpcode();
6399     if (Opcode == ISD::UNDEF) {
6400       std::swap(ExpectedOpcode, NextExpectedOpcode);
6401       continue;
6402     }
6403       
6404     // Early exit if we found an unexpected opcode.
6405     if (Opcode != ExpectedOpcode)
6406       return SDValue();
6407
6408     SDValue Op0 = Op.getOperand(0);
6409     SDValue Op1 = Op.getOperand(1);
6410
6411     // Try to match the following pattern:
6412     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6413     // Early exit if we cannot match that sequence.
6414     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6415         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6416         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6417         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6418         Op0.getOperand(1) != Op1.getOperand(1))
6419       return SDValue();
6420
6421     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6422     if (I0 != i)
6423       return SDValue();
6424
6425     // We found a valid add/sub node. Update the information accordingly.
6426     if (i & 1)
6427       AddFound = true;
6428     else
6429       SubFound = true;
6430
6431     // Update InVec0 and InVec1.
6432     if (InVec0.getOpcode() == ISD::UNDEF)
6433       InVec0 = Op0.getOperand(0);
6434     if (InVec1.getOpcode() == ISD::UNDEF)
6435       InVec1 = Op1.getOperand(0);
6436
6437     // Make sure that operands in input to each add/sub node always
6438     // come from a same pair of vectors.
6439     if (InVec0 != Op0.getOperand(0)) {
6440       if (ExpectedOpcode == ISD::FSUB)
6441         return SDValue();
6442
6443       // FADD is commutable. Try to commute the operands
6444       // and then test again.
6445       std::swap(Op0, Op1);
6446       if (InVec0 != Op0.getOperand(0))
6447         return SDValue();
6448     }
6449
6450     if (InVec1 != Op1.getOperand(0))
6451       return SDValue();
6452
6453     // Update the pair of expected opcodes.
6454     std::swap(ExpectedOpcode, NextExpectedOpcode);
6455   }
6456
6457   // Don't try to fold this build_vector into a VSELECT if it has
6458   // too many UNDEF operands.
6459   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6460       InVec1.getOpcode() != ISD::UNDEF) {
6461     // Emit a sequence of vector add and sub followed by a VSELECT.
6462     // The new VSELECT will be lowered into a BLENDI.
6463     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6464     // and emit a single ADDSUB instruction.
6465     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6466     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6467
6468     // Construct the VSELECT mask.
6469     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6470     EVT SVT = MaskVT.getVectorElementType();
6471     unsigned SVTBits = SVT.getSizeInBits();
6472     SmallVector<SDValue, 8> Ops;
6473
6474     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6475       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6476                             APInt::getAllOnesValue(SVTBits);
6477       SDValue Constant = DAG.getConstant(Value, SVT);
6478       Ops.push_back(Constant);
6479     }
6480
6481     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6482     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6483   }
6484   
6485   return SDValue();
6486 }
6487
6488 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6489                                           const X86Subtarget *Subtarget) {
6490   SDLoc DL(N);
6491   EVT VT = N->getValueType(0);
6492   unsigned NumElts = VT.getVectorNumElements();
6493   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6494   SDValue InVec0, InVec1;
6495
6496   // Try to match an ADDSUB.
6497   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6498       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6499     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6500     if (Value.getNode())
6501       return Value;
6502   }
6503
6504   // Try to match horizontal ADD/SUB.
6505   unsigned NumUndefsLO = 0;
6506   unsigned NumUndefsHI = 0;
6507   unsigned Half = NumElts/2;
6508
6509   // Count the number of UNDEF operands in the build_vector in input.
6510   for (unsigned i = 0, e = Half; i != e; ++i)
6511     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6512       NumUndefsLO++;
6513
6514   for (unsigned i = Half, e = NumElts; i != e; ++i)
6515     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6516       NumUndefsHI++;
6517
6518   // Early exit if this is either a build_vector of all UNDEFs or all the
6519   // operands but one are UNDEF.
6520   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6521     return SDValue();
6522
6523   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6524     // Try to match an SSE3 float HADD/HSUB.
6525     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6526       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6527     
6528     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6529       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6530   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6531     // Try to match an SSSE3 integer HADD/HSUB.
6532     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6533       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6534     
6535     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6536       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6537   }
6538   
6539   if (!Subtarget->hasAVX())
6540     return SDValue();
6541
6542   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6543     // Try to match an AVX horizontal add/sub of packed single/double
6544     // precision floating point values from 256-bit vectors.
6545     SDValue InVec2, InVec3;
6546     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6547         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6548         ((InVec0.getOpcode() == ISD::UNDEF ||
6549           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6550         ((InVec1.getOpcode() == ISD::UNDEF ||
6551           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6552       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6553
6554     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6555         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6556         ((InVec0.getOpcode() == ISD::UNDEF ||
6557           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6558         ((InVec1.getOpcode() == ISD::UNDEF ||
6559           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6560       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6561   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6562     // Try to match an AVX2 horizontal add/sub of signed integers.
6563     SDValue InVec2, InVec3;
6564     unsigned X86Opcode;
6565     bool CanFold = true;
6566
6567     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6568         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6569         ((InVec0.getOpcode() == ISD::UNDEF ||
6570           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6571         ((InVec1.getOpcode() == ISD::UNDEF ||
6572           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6573       X86Opcode = X86ISD::HADD;
6574     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6575         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6576         ((InVec0.getOpcode() == ISD::UNDEF ||
6577           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6578         ((InVec1.getOpcode() == ISD::UNDEF ||
6579           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6580       X86Opcode = X86ISD::HSUB;
6581     else
6582       CanFold = false;
6583
6584     if (CanFold) {
6585       // Fold this build_vector into a single horizontal add/sub.
6586       // Do this only if the target has AVX2.
6587       if (Subtarget->hasAVX2())
6588         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6589  
6590       // Do not try to expand this build_vector into a pair of horizontal
6591       // add/sub if we can emit a pair of scalar add/sub.
6592       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6593         return SDValue();
6594
6595       // Convert this build_vector into a pair of horizontal binop followed by
6596       // a concat vector.
6597       bool isUndefLO = NumUndefsLO == Half;
6598       bool isUndefHI = NumUndefsHI == Half;
6599       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6600                                    isUndefLO, isUndefHI);
6601     }
6602   }
6603
6604   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6605        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6606     unsigned X86Opcode;
6607     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6608       X86Opcode = X86ISD::HADD;
6609     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6610       X86Opcode = X86ISD::HSUB;
6611     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6612       X86Opcode = X86ISD::FHADD;
6613     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6614       X86Opcode = X86ISD::FHSUB;
6615     else
6616       return SDValue();
6617
6618     // Don't try to expand this build_vector into a pair of horizontal add/sub
6619     // if we can simply emit a pair of scalar add/sub.
6620     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6621       return SDValue();
6622
6623     // Convert this build_vector into two horizontal add/sub followed by
6624     // a concat vector.
6625     bool isUndefLO = NumUndefsLO == Half;
6626     bool isUndefHI = NumUndefsHI == Half;
6627     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6628                                  isUndefLO, isUndefHI);
6629   }
6630
6631   return SDValue();
6632 }
6633
6634 SDValue
6635 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6636   SDLoc dl(Op);
6637
6638   MVT VT = Op.getSimpleValueType();
6639   MVT ExtVT = VT.getVectorElementType();
6640   unsigned NumElems = Op.getNumOperands();
6641
6642   // Generate vectors for predicate vectors.
6643   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6644     return LowerBUILD_VECTORvXi1(Op, DAG);
6645
6646   // Vectors containing all zeros can be matched by pxor and xorps later
6647   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6648     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6649     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6650     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6651       return Op;
6652
6653     return getZeroVector(VT, Subtarget, DAG, dl);
6654   }
6655
6656   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6657   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6658   // vpcmpeqd on 256-bit vectors.
6659   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6660     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6661       return Op;
6662
6663     if (!VT.is512BitVector())
6664       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6665   }
6666
6667   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6668   if (Broadcast.getNode())
6669     return Broadcast;
6670
6671   unsigned EVTBits = ExtVT.getSizeInBits();
6672
6673   unsigned NumZero  = 0;
6674   unsigned NumNonZero = 0;
6675   unsigned NonZeros = 0;
6676   bool IsAllConstants = true;
6677   SmallSet<SDValue, 8> Values;
6678   for (unsigned i = 0; i < NumElems; ++i) {
6679     SDValue Elt = Op.getOperand(i);
6680     if (Elt.getOpcode() == ISD::UNDEF)
6681       continue;
6682     Values.insert(Elt);
6683     if (Elt.getOpcode() != ISD::Constant &&
6684         Elt.getOpcode() != ISD::ConstantFP)
6685       IsAllConstants = false;
6686     if (X86::isZeroNode(Elt))
6687       NumZero++;
6688     else {
6689       NonZeros |= (1 << i);
6690       NumNonZero++;
6691     }
6692   }
6693
6694   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6695   if (NumNonZero == 0)
6696     return DAG.getUNDEF(VT);
6697
6698   // Special case for single non-zero, non-undef, element.
6699   if (NumNonZero == 1) {
6700     unsigned Idx = countTrailingZeros(NonZeros);
6701     SDValue Item = Op.getOperand(Idx);
6702
6703     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6704     // the value are obviously zero, truncate the value to i32 and do the
6705     // insertion that way.  Only do this if the value is non-constant or if the
6706     // value is a constant being inserted into element 0.  It is cheaper to do
6707     // a constant pool load than it is to do a movd + shuffle.
6708     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6709         (!IsAllConstants || Idx == 0)) {
6710       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6711         // Handle SSE only.
6712         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6713         EVT VecVT = MVT::v4i32;
6714         unsigned VecElts = 4;
6715
6716         // Truncate the value (which may itself be a constant) to i32, and
6717         // convert it to a vector with movd (S2V+shuffle to zero extend).
6718         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6719         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6720         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6721
6722         // Now we have our 32-bit value zero extended in the low element of
6723         // a vector.  If Idx != 0, swizzle it into place.
6724         if (Idx != 0) {
6725           SmallVector<int, 4> Mask;
6726           Mask.push_back(Idx);
6727           for (unsigned i = 1; i != VecElts; ++i)
6728             Mask.push_back(i);
6729           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6730                                       &Mask[0]);
6731         }
6732         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6733       }
6734     }
6735
6736     // If we have a constant or non-constant insertion into the low element of
6737     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6738     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6739     // depending on what the source datatype is.
6740     if (Idx == 0) {
6741       if (NumZero == 0)
6742         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6743
6744       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6745           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6746         if (VT.is256BitVector() || VT.is512BitVector()) {
6747           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6748           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6749                              Item, DAG.getIntPtrConstant(0));
6750         }
6751         assert(VT.is128BitVector() && "Expected an SSE value type!");
6752         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6753         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6754         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6755       }
6756
6757       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6758         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6759         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6760         if (VT.is256BitVector()) {
6761           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6762           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6763         } else {
6764           assert(VT.is128BitVector() && "Expected an SSE value type!");
6765           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6766         }
6767         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6768       }
6769     }
6770
6771     // Is it a vector logical left shift?
6772     if (NumElems == 2 && Idx == 1 &&
6773         X86::isZeroNode(Op.getOperand(0)) &&
6774         !X86::isZeroNode(Op.getOperand(1))) {
6775       unsigned NumBits = VT.getSizeInBits();
6776       return getVShift(true, VT,
6777                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6778                                    VT, Op.getOperand(1)),
6779                        NumBits/2, DAG, *this, dl);
6780     }
6781
6782     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6783       return SDValue();
6784
6785     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6786     // is a non-constant being inserted into an element other than the low one,
6787     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6788     // movd/movss) to move this into the low element, then shuffle it into
6789     // place.
6790     if (EVTBits == 32) {
6791       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6792
6793       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6794       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6795       SmallVector<int, 8> MaskVec;
6796       for (unsigned i = 0; i != NumElems; ++i)
6797         MaskVec.push_back(i == Idx ? 0 : 1);
6798       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6799     }
6800   }
6801
6802   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6803   if (Values.size() == 1) {
6804     if (EVTBits == 32) {
6805       // Instead of a shuffle like this:
6806       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6807       // Check if it's possible to issue this instead.
6808       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6809       unsigned Idx = countTrailingZeros(NonZeros);
6810       SDValue Item = Op.getOperand(Idx);
6811       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6812         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6813     }
6814     return SDValue();
6815   }
6816
6817   // A vector full of immediates; various special cases are already
6818   // handled, so this is best done with a single constant-pool load.
6819   if (IsAllConstants)
6820     return SDValue();
6821
6822   // For AVX-length vectors, build the individual 128-bit pieces and use
6823   // shuffles to put them in place.
6824   if (VT.is256BitVector() || VT.is512BitVector()) {
6825     SmallVector<SDValue, 64> V;
6826     for (unsigned i = 0; i != NumElems; ++i)
6827       V.push_back(Op.getOperand(i));
6828
6829     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6830
6831     // Build both the lower and upper subvector.
6832     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6833                                 makeArrayRef(&V[0], NumElems/2));
6834     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6835                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6836
6837     // Recreate the wider vector with the lower and upper part.
6838     if (VT.is256BitVector())
6839       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6840     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6841   }
6842
6843   // Let legalizer expand 2-wide build_vectors.
6844   if (EVTBits == 64) {
6845     if (NumNonZero == 1) {
6846       // One half is zero or undef.
6847       unsigned Idx = countTrailingZeros(NonZeros);
6848       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6849                                  Op.getOperand(Idx));
6850       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6851     }
6852     return SDValue();
6853   }
6854
6855   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6856   if (EVTBits == 8 && NumElems == 16) {
6857     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6858                                         Subtarget, *this);
6859     if (V.getNode()) return V;
6860   }
6861
6862   if (EVTBits == 16 && NumElems == 8) {
6863     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6864                                       Subtarget, *this);
6865     if (V.getNode()) return V;
6866   }
6867
6868   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6869   if (EVTBits == 32 && NumElems == 4) {
6870     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6871                                       NumZero, DAG, Subtarget, *this);
6872     if (V.getNode())
6873       return V;
6874   }
6875
6876   // If element VT is == 32 bits, turn it into a number of shuffles.
6877   SmallVector<SDValue, 8> V(NumElems);
6878   if (NumElems == 4 && NumZero > 0) {
6879     for (unsigned i = 0; i < 4; ++i) {
6880       bool isZero = !(NonZeros & (1 << i));
6881       if (isZero)
6882         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6883       else
6884         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6885     }
6886
6887     for (unsigned i = 0; i < 2; ++i) {
6888       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6889         default: break;
6890         case 0:
6891           V[i] = V[i*2];  // Must be a zero vector.
6892           break;
6893         case 1:
6894           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6895           break;
6896         case 2:
6897           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6898           break;
6899         case 3:
6900           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6901           break;
6902       }
6903     }
6904
6905     bool Reverse1 = (NonZeros & 0x3) == 2;
6906     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6907     int MaskVec[] = {
6908       Reverse1 ? 1 : 0,
6909       Reverse1 ? 0 : 1,
6910       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6911       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6912     };
6913     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6914   }
6915
6916   if (Values.size() > 1 && VT.is128BitVector()) {
6917     // Check for a build vector of consecutive loads.
6918     for (unsigned i = 0; i < NumElems; ++i)
6919       V[i] = Op.getOperand(i);
6920
6921     // Check for elements which are consecutive loads.
6922     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6923     if (LD.getNode())
6924       return LD;
6925
6926     // Check for a build vector from mostly shuffle plus few inserting.
6927     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6928     if (Sh.getNode())
6929       return Sh;
6930
6931     // For SSE 4.1, use insertps to put the high elements into the low element.
6932     if (getSubtarget()->hasSSE41()) {
6933       SDValue Result;
6934       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6935         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6936       else
6937         Result = DAG.getUNDEF(VT);
6938
6939       for (unsigned i = 1; i < NumElems; ++i) {
6940         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6941         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6942                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6943       }
6944       return Result;
6945     }
6946
6947     // Otherwise, expand into a number of unpckl*, start by extending each of
6948     // our (non-undef) elements to the full vector width with the element in the
6949     // bottom slot of the vector (which generates no code for SSE).
6950     for (unsigned i = 0; i < NumElems; ++i) {
6951       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6952         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6953       else
6954         V[i] = DAG.getUNDEF(VT);
6955     }
6956
6957     // Next, we iteratively mix elements, e.g. for v4f32:
6958     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6959     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6960     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6961     unsigned EltStride = NumElems >> 1;
6962     while (EltStride != 0) {
6963       for (unsigned i = 0; i < EltStride; ++i) {
6964         // If V[i+EltStride] is undef and this is the first round of mixing,
6965         // then it is safe to just drop this shuffle: V[i] is already in the
6966         // right place, the one element (since it's the first round) being
6967         // inserted as undef can be dropped.  This isn't safe for successive
6968         // rounds because they will permute elements within both vectors.
6969         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6970             EltStride == NumElems/2)
6971           continue;
6972
6973         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6974       }
6975       EltStride >>= 1;
6976     }
6977     return V[0];
6978   }
6979   return SDValue();
6980 }
6981
6982 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6983 // to create 256-bit vectors from two other 128-bit ones.
6984 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6985   SDLoc dl(Op);
6986   MVT ResVT = Op.getSimpleValueType();
6987
6988   assert((ResVT.is256BitVector() ||
6989           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6990
6991   SDValue V1 = Op.getOperand(0);
6992   SDValue V2 = Op.getOperand(1);
6993   unsigned NumElems = ResVT.getVectorNumElements();
6994   if(ResVT.is256BitVector())
6995     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6996
6997   if (Op.getNumOperands() == 4) {
6998     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6999                                 ResVT.getVectorNumElements()/2);
7000     SDValue V3 = Op.getOperand(2);
7001     SDValue V4 = Op.getOperand(3);
7002     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7003       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7004   }
7005   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7006 }
7007
7008 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7009   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7010   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7011          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7012           Op.getNumOperands() == 4)));
7013
7014   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7015   // from two other 128-bit ones.
7016
7017   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7018   return LowerAVXCONCAT_VECTORS(Op, DAG);
7019 }
7020
7021
7022 //===----------------------------------------------------------------------===//
7023 // Vector shuffle lowering
7024 //
7025 // This is an experimental code path for lowering vector shuffles on x86. It is
7026 // designed to handle arbitrary vector shuffles and blends, gracefully
7027 // degrading performance as necessary. It works hard to recognize idiomatic
7028 // shuffles and lower them to optimal instruction patterns without leaving
7029 // a framework that allows reasonably efficient handling of all vector shuffle
7030 // patterns.
7031 //===----------------------------------------------------------------------===//
7032
7033 /// \brief Tiny helper function to identify a no-op mask.
7034 ///
7035 /// This is a somewhat boring predicate function. It checks whether the mask
7036 /// array input, which is assumed to be a single-input shuffle mask of the kind
7037 /// used by the X86 shuffle instructions (not a fully general
7038 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7039 /// in-place shuffle are 'no-op's.
7040 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7041   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7042     if (Mask[i] != -1 && Mask[i] != i)
7043       return false;
7044   return true;
7045 }
7046
7047 /// \brief Helper function to classify a mask as a single-input mask.
7048 ///
7049 /// This isn't a generic single-input test because in the vector shuffle
7050 /// lowering we canonicalize single inputs to be the first input operand. This
7051 /// means we can more quickly test for a single input by only checking whether
7052 /// an input from the second operand exists. We also assume that the size of
7053 /// mask corresponds to the size of the input vectors which isn't true in the
7054 /// fully general case.
7055 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7056   for (int M : Mask)
7057     if (M >= (int)Mask.size())
7058       return false;
7059   return true;
7060 }
7061
7062 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7063 ///
7064 /// This helper function produces an 8-bit shuffle immediate corresponding to
7065 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7066 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7067 /// example.
7068 ///
7069 /// NB: We rely heavily on "undef" masks preserving the input lane.
7070 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7071                                           SelectionDAG &DAG) {
7072   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7073   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7074   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7075   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7076   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7077
7078   unsigned Imm = 0;
7079   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7080   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7081   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7082   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7083   return DAG.getConstant(Imm, MVT::i8);
7084 }
7085
7086 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7087 ///
7088 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7089 /// support for floating point shuffles but not integer shuffles. These
7090 /// instructions will incur a domain crossing penalty on some chips though so
7091 /// it is better to avoid lowering through this for integer vectors where
7092 /// possible.
7093 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7094                                        const X86Subtarget *Subtarget,
7095                                        SelectionDAG &DAG) {
7096   SDLoc DL(Op);
7097   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7098   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7099   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7100   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7101   ArrayRef<int> Mask = SVOp->getMask();
7102   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7103
7104   if (isSingleInputShuffleMask(Mask)) {
7105     // Straight shuffle of a single input vector. Simulate this by using the
7106     // single input as both of the "inputs" to this instruction..
7107     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7108     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7109                        DAG.getConstant(SHUFPDMask, MVT::i8));
7110   }
7111   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7112   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7113
7114   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7115   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7116                      DAG.getConstant(SHUFPDMask, MVT::i8));
7117 }
7118
7119 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7120 ///
7121 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7122 /// the integer unit to minimize domain crossing penalties. However, for blends
7123 /// it falls back to the floating point shuffle operation with appropriate bit
7124 /// casting.
7125 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7126                                        const X86Subtarget *Subtarget,
7127                                        SelectionDAG &DAG) {
7128   SDLoc DL(Op);
7129   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7130   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7131   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7132   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7133   ArrayRef<int> Mask = SVOp->getMask();
7134   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7135
7136   if (isSingleInputShuffleMask(Mask)) {
7137     // Straight shuffle of a single input vector. For everything from SSE2
7138     // onward this has a single fast instruction with no scary immediates.
7139     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7140     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7141     int WidenedMask[4] = {
7142         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7143         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7144     return DAG.getNode(
7145         ISD::BITCAST, DL, MVT::v2i64,
7146         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7147                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7148   }
7149
7150   // We implement this with SHUFPD which is pretty lame because it will likely
7151   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7152   // However, all the alternatives are still more cycles and newer chips don't
7153   // have this problem. It would be really nice if x86 had better shuffles here.
7154   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7155   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7156   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7157                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7158 }
7159
7160 /// \brief Lower 4-lane 32-bit floating point shuffles.
7161 ///
7162 /// Uses instructions exclusively from the floating point unit to minimize
7163 /// domain crossing penalties, as these are sufficient to implement all v4f32
7164 /// shuffles.
7165 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7166                                        const X86Subtarget *Subtarget,
7167                                        SelectionDAG &DAG) {
7168   SDLoc DL(Op);
7169   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7170   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7171   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7172   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7173   ArrayRef<int> Mask = SVOp->getMask();
7174   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7175
7176   SDValue LowV = V1, HighV = V2;
7177   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7178
7179   int NumV2Elements =
7180       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7181
7182   if (NumV2Elements == 0)
7183     // Straight shuffle of a single input vector. We pass the input vector to
7184     // both operands to simulate this with a SHUFPS.
7185     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7186                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7187
7188   if (NumV2Elements == 1) {
7189     int V2Index =
7190         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7191         Mask.begin();
7192     // Compute the index adjacent to V2Index and in the same half by toggling
7193     // the low bit.
7194     int V2AdjIndex = V2Index ^ 1;
7195
7196     if (Mask[V2AdjIndex] == -1) {
7197       // Handles all the cases where we have a single V2 element and an undef.
7198       // This will only ever happen in the high lanes because we commute the
7199       // vector otherwise.
7200       if (V2Index < 2)
7201         std::swap(LowV, HighV);
7202       NewMask[V2Index] -= 4;
7203     } else {
7204       // Handle the case where the V2 element ends up adjacent to a V1 element.
7205       // To make this work, blend them together as the first step.
7206       int V1Index = V2AdjIndex;
7207       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7208       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7209                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7210
7211       // Now proceed to reconstruct the final blend as we have the necessary
7212       // high or low half formed.
7213       if (V2Index < 2) {
7214         LowV = V2;
7215         HighV = V1;
7216       } else {
7217         HighV = V2;
7218       }
7219       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7220       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7221     }
7222   } else if (NumV2Elements == 2) {
7223     if (Mask[0] < 4 && Mask[1] < 4) {
7224       // Handle the easy case where we have V1 in the low lanes and V2 in the
7225       // high lanes. We never see this reversed because we sort the shuffle.
7226       NewMask[2] -= 4;
7227       NewMask[3] -= 4;
7228     } else {
7229       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7230       // trying to place elements directly, just blend them and set up the final
7231       // shuffle to place them.
7232
7233       // The first two blend mask elements are for V1, the second two are for
7234       // V2.
7235       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7236                           Mask[2] < 4 ? Mask[2] : Mask[3],
7237                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7238                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7239       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7240                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7241
7242       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7243       // a blend.
7244       LowV = HighV = V1;
7245       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7246       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7247       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7248       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7249     }
7250   }
7251   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7252                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7253 }
7254
7255 /// \brief Lower 4-lane i32 vector shuffles.
7256 ///
7257 /// We try to handle these with integer-domain shuffles where we can, but for
7258 /// blends we use the floating point domain blend instructions.
7259 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7260                                        const X86Subtarget *Subtarget,
7261                                        SelectionDAG &DAG) {
7262   SDLoc DL(Op);
7263   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7264   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7265   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7266   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7267   ArrayRef<int> Mask = SVOp->getMask();
7268   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7269
7270   if (isSingleInputShuffleMask(Mask))
7271     // Straight shuffle of a single input vector. For everything from SSE2
7272     // onward this has a single fast instruction with no scary immediates.
7273     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7274                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7275
7276   // We implement this with SHUFPS because it can blend from two vectors.
7277   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7278   // up the inputs, bypassing domain shift penalties that we would encur if we
7279   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7280   // relevant.
7281   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7282                      DAG.getVectorShuffle(
7283                          MVT::v4f32, DL,
7284                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7285                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7286 }
7287
7288 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7289 /// shuffle lowering, and the most complex part.
7290 ///
7291 /// The lowering strategy is to try to form pairs of input lanes which are
7292 /// targeted at the same half of the final vector, and then use a dword shuffle
7293 /// to place them onto the right half, and finally unpack the paired lanes into
7294 /// their final position.
7295 ///
7296 /// The exact breakdown of how to form these dword pairs and align them on the
7297 /// correct sides is really tricky. See the comments within the function for
7298 /// more of the details.
7299 static SDValue lowerV8I16SingleInputVectorShuffle(
7300     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7301     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7302   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7303   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7304   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7305
7306   SmallVector<int, 4> LoInputs;
7307   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7308                [](int M) { return M >= 0; });
7309   std::sort(LoInputs.begin(), LoInputs.end());
7310   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7311   SmallVector<int, 4> HiInputs;
7312   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7313                [](int M) { return M >= 0; });
7314   std::sort(HiInputs.begin(), HiInputs.end());
7315   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7316   int NumLToL =
7317       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7318   int NumHToL = LoInputs.size() - NumLToL;
7319   int NumLToH =
7320       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7321   int NumHToH = HiInputs.size() - NumLToH;
7322   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7323   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7324   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7325   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7326
7327   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7328   // such inputs we can swap two of the dwords across the half mark and end up
7329   // with <=2 inputs to each half in each half. Once there, we can fall through
7330   // to the generic code below. For example:
7331   //
7332   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7333   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7334   //
7335   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7336   // and 2-2.
7337   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7338                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7339     // Compute the index of dword with only one word among the three inputs in
7340     // a half by taking the sum of the half with three inputs and subtracting
7341     // the sum of the actual three inputs. The difference is the remaining
7342     // slot.
7343     int DWordA = (ThreeInputHalfSum -
7344                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7345                  2;
7346     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7347
7348     int PSHUFDMask[] = {0, 1, 2, 3};
7349     PSHUFDMask[DWordA] = DWordB;
7350     PSHUFDMask[DWordB] = DWordA;
7351     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7352                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7353                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7354                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7355
7356     // Adjust the mask to match the new locations of A and B.
7357     for (int &M : Mask)
7358       if (M != -1 && M/2 == DWordA)
7359         M = 2 * DWordB + M % 2;
7360       else if (M != -1 && M/2 == DWordB)
7361         M = 2 * DWordA + M % 2;
7362
7363     // Recurse back into this routine to re-compute state now that this isn't
7364     // a 3 and 1 problem.
7365     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7366                                 Mask);
7367   };
7368   if (NumLToL == 3 && NumHToL == 1)
7369     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7370   else if (NumLToL == 1 && NumHToL == 3)
7371     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7372   else if (NumLToH == 1 && NumHToH == 3)
7373     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7374   else if (NumLToH == 3 && NumHToH == 1)
7375     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7376
7377   // At this point there are at most two inputs to the low and high halves from
7378   // each half. That means the inputs can always be grouped into dwords and
7379   // those dwords can then be moved to the correct half with a dword shuffle.
7380   // We use at most one low and one high word shuffle to collect these paired
7381   // inputs into dwords, and finally a dword shuffle to place them.
7382   int PSHUFLMask[4] = {-1, -1, -1, -1};
7383   int PSHUFHMask[4] = {-1, -1, -1, -1};
7384   int PSHUFDMask[4] = {-1, -1, -1, -1};
7385
7386   // First fix the masks for all the inputs that are staying in their
7387   // original halves. This will then dictate the targets of the cross-half
7388   // shuffles.
7389   auto fixInPlaceInputs =
7390       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7391                     MutableArrayRef<int> SourceHalfMask,
7392                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7393     if (InPlaceInputs.empty())
7394       return;
7395     if (InPlaceInputs.size() == 1) {
7396       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7397           InPlaceInputs[0] - HalfOffset;
7398       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7399       return;
7400     }
7401     if (IncomingInputs.empty()) {
7402       // Just fix all of the in place inputs.
7403       for (int Input : InPlaceInputs) {
7404         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7405         PSHUFDMask[Input / 2] = Input / 2;
7406       }
7407       return;
7408     }
7409
7410     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7411     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7412         InPlaceInputs[0] - HalfOffset;
7413     // Put the second input next to the first so that they are packed into
7414     // a dword. We find the adjacent index by toggling the low bit.
7415     int AdjIndex = InPlaceInputs[0] ^ 1;
7416     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7417     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7418     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7419   };
7420   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7421   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7422
7423   // Now gather the cross-half inputs and place them into a free dword of
7424   // their target half.
7425   // FIXME: This operation could almost certainly be simplified dramatically to
7426   // look more like the 3-1 fixing operation.
7427   auto moveInputsToRightHalf = [&PSHUFDMask](
7428       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7429       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7430       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7431       int DestOffset) {
7432     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7433       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7434     };
7435     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7436                                                int Word) {
7437       int LowWord = Word & ~1;
7438       int HighWord = Word | 1;
7439       return isWordClobbered(SourceHalfMask, LowWord) ||
7440              isWordClobbered(SourceHalfMask, HighWord);
7441     };
7442
7443     if (IncomingInputs.empty())
7444       return;
7445
7446     if (ExistingInputs.empty()) {
7447       // Map any dwords with inputs from them into the right half.
7448       for (int Input : IncomingInputs) {
7449         // If the source half mask maps over the inputs, turn those into
7450         // swaps and use the swapped lane.
7451         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7452           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7453             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7454                 Input - SourceOffset;
7455             // We have to swap the uses in our half mask in one sweep.
7456             for (int &M : HalfMask)
7457               if (M == SourceHalfMask[Input - SourceOffset])
7458                 M = Input;
7459               else if (M == Input)
7460                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7461           } else {
7462             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7463                        Input - SourceOffset &&
7464                    "Previous placement doesn't match!");
7465           }
7466           // Note that this correctly re-maps both when we do a swap and when
7467           // we observe the other side of the swap above. We rely on that to
7468           // avoid swapping the members of the input list directly.
7469           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7470         }
7471
7472         // Map the input's dword into the correct half.
7473         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7474           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7475         else
7476           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7477                      Input / 2 &&
7478                  "Previous placement doesn't match!");
7479       }
7480
7481       // And just directly shift any other-half mask elements to be same-half
7482       // as we will have mirrored the dword containing the element into the
7483       // same position within that half.
7484       for (int &M : HalfMask)
7485         if (M >= SourceOffset && M < SourceOffset + 4) {
7486           M = M - SourceOffset + DestOffset;
7487           assert(M >= 0 && "This should never wrap below zero!");
7488         }
7489       return;
7490     }
7491
7492     // Ensure we have the input in a viable dword of its current half. This
7493     // is particularly tricky because the original position may be clobbered
7494     // by inputs being moved and *staying* in that half.
7495     if (IncomingInputs.size() == 1) {
7496       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7497         int InputFixed = std::find(std::begin(SourceHalfMask),
7498                                    std::end(SourceHalfMask), -1) -
7499                          std::begin(SourceHalfMask) + SourceOffset;
7500         SourceHalfMask[InputFixed - SourceOffset] =
7501             IncomingInputs[0] - SourceOffset;
7502         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7503                      InputFixed);
7504         IncomingInputs[0] = InputFixed;
7505       }
7506     } else if (IncomingInputs.size() == 2) {
7507       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7508           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7509         // We have two non-adjacent or clobbered inputs we need to extract from
7510         // the source half. To do this, we need to map them into some adjacent
7511         // dword slot in the source mask.
7512         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7513                               IncomingInputs[1] - SourceOffset};
7514
7515         // If there is a free slot in the source half mask adjacent to one of
7516         // the inputs, place the other input in it. We use (Index XOR 1) to
7517         // compute an adjacent index.
7518         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7519             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7520           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7521           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7522           InputsFixed[1] = InputsFixed[0] ^ 1;
7523         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7524                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7525           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7526           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7527           InputsFixed[0] = InputsFixed[1] ^ 1;
7528         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7529                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7530           // The two inputs are in the same DWord but it is clobbered and the
7531           // adjacent DWord isn't used at all. Move both inputs to the free
7532           // slot.
7533           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7534           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7535           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7536           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7537         } else {
7538           // The only way we hit this point is if there is no clobbering
7539           // (because there are no off-half inputs to this half) and there is no
7540           // free slot adjacent to one of the inputs. In this case, we have to
7541           // swap an input with a non-input.
7542           for (int i = 0; i < 4; ++i)
7543             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7544                    "We can't handle any clobbers here!");
7545           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7546                  "Cannot have adjacent inputs here!");
7547
7548           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7549           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7550
7551           // We also have to update the final source mask in this case because
7552           // it may need to undo the above swap.
7553           for (int &M : FinalSourceHalfMask)
7554             if (M == (InputsFixed[0] ^ 1))
7555               M = InputsFixed[1];
7556             else if (M == InputsFixed[1])
7557               M = InputsFixed[0] ^ 1;
7558
7559           InputsFixed[1] = InputsFixed[0] ^ 1;
7560         }
7561
7562         // Point everything at the fixed inputs.
7563         for (int &M : HalfMask)
7564           if (M == IncomingInputs[0])
7565             M = InputsFixed[0] + SourceOffset;
7566           else if (M == IncomingInputs[1])
7567             M = InputsFixed[1] + SourceOffset;
7568
7569         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7570         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7571       }
7572     } else {
7573       llvm_unreachable("Unhandled input size!");
7574     }
7575
7576     // Now hoist the DWord down to the right half.
7577     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7578     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7579     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7580     for (int &M : HalfMask)
7581       for (int Input : IncomingInputs)
7582         if (M == Input)
7583           M = FreeDWord * 2 + Input % 2;
7584   };
7585   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
7586                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7587   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
7588                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7589
7590   // Now enact all the shuffles we've computed to move the inputs into their
7591   // target half.
7592   if (!isNoopShuffleMask(PSHUFLMask))
7593     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7594                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7595   if (!isNoopShuffleMask(PSHUFHMask))
7596     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7597                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7598   if (!isNoopShuffleMask(PSHUFDMask))
7599     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7600                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7601                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7602                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7603
7604   // At this point, each half should contain all its inputs, and we can then
7605   // just shuffle them into their final position.
7606   assert(std::count_if(LoMask.begin(), LoMask.end(),
7607                        [](int M) { return M >= 4; }) == 0 &&
7608          "Failed to lift all the high half inputs to the low mask!");
7609   assert(std::count_if(HiMask.begin(), HiMask.end(),
7610                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7611          "Failed to lift all the low half inputs to the high mask!");
7612
7613   // Do a half shuffle for the low mask.
7614   if (!isNoopShuffleMask(LoMask))
7615     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7616                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7617
7618   // Do a half shuffle with the high mask after shifting its values down.
7619   for (int &M : HiMask)
7620     if (M >= 0)
7621       M -= 4;
7622   if (!isNoopShuffleMask(HiMask))
7623     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7624                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7625
7626   return V;
7627 }
7628
7629 /// \brief Detect whether the mask pattern should be lowered through
7630 /// interleaving.
7631 ///
7632 /// This essentially tests whether viewing the mask as an interleaving of two
7633 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7634 /// lowering it through interleaving is a significantly better strategy.
7635 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7636   int NumEvenInputs[2] = {0, 0};
7637   int NumOddInputs[2] = {0, 0};
7638   int NumLoInputs[2] = {0, 0};
7639   int NumHiInputs[2] = {0, 0};
7640   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7641     if (Mask[i] < 0)
7642       continue;
7643
7644     int InputIdx = Mask[i] >= Size;
7645
7646     if (i < Size / 2)
7647       ++NumLoInputs[InputIdx];
7648     else
7649       ++NumHiInputs[InputIdx];
7650
7651     if ((i % 2) == 0)
7652       ++NumEvenInputs[InputIdx];
7653     else
7654       ++NumOddInputs[InputIdx];
7655   }
7656
7657   // The minimum number of cross-input results for both the interleaved and
7658   // split cases. If interleaving results in fewer cross-input results, return
7659   // true.
7660   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7661                                     NumEvenInputs[0] + NumOddInputs[1]);
7662   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7663                               NumLoInputs[0] + NumHiInputs[1]);
7664   return InterleavedCrosses < SplitCrosses;
7665 }
7666
7667 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7668 ///
7669 /// This strategy only works when the inputs from each vector fit into a single
7670 /// half of that vector, and generally there are not so many inputs as to leave
7671 /// the in-place shuffles required highly constrained (and thus expensive). It
7672 /// shifts all the inputs into a single side of both input vectors and then
7673 /// uses an unpack to interleave these inputs in a single vector. At that
7674 /// point, we will fall back on the generic single input shuffle lowering.
7675 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7676                                                  SDValue V2,
7677                                                  MutableArrayRef<int> Mask,
7678                                                  const X86Subtarget *Subtarget,
7679                                                  SelectionDAG &DAG) {
7680   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7681   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7682   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7683   for (int i = 0; i < 8; ++i)
7684     if (Mask[i] >= 0 && Mask[i] < 4)
7685       LoV1Inputs.push_back(i);
7686     else if (Mask[i] >= 4 && Mask[i] < 8)
7687       HiV1Inputs.push_back(i);
7688     else if (Mask[i] >= 8 && Mask[i] < 12)
7689       LoV2Inputs.push_back(i);
7690     else if (Mask[i] >= 12)
7691       HiV2Inputs.push_back(i);
7692
7693   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7694   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7695   (void)NumV1Inputs;
7696   (void)NumV2Inputs;
7697   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7698   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7699   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7700
7701   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7702                      HiV1Inputs.size() + HiV2Inputs.size();
7703
7704   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7705                               ArrayRef<int> HiInputs, bool MoveToLo,
7706                               int MaskOffset) {
7707     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7708     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7709     if (BadInputs.empty())
7710       return V;
7711
7712     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7713     int MoveOffset = MoveToLo ? 0 : 4;
7714
7715     if (GoodInputs.empty()) {
7716       for (int BadInput : BadInputs) {
7717         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7718         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7719       }
7720     } else {
7721       if (GoodInputs.size() == 2) {
7722         // If the low inputs are spread across two dwords, pack them into
7723         // a single dword.
7724         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
7725         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
7726         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
7727         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
7728       } else {
7729         // Otherwise pin the good inputs.
7730         for (int GoodInput : GoodInputs)
7731           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7732       }
7733
7734       if (BadInputs.size() == 2) {
7735         // If we have two bad inputs then there may be either one or two good
7736         // inputs fixed in place. Find a fixed input, and then find the *other*
7737         // two adjacent indices by using modular arithmetic.
7738         int GoodMaskIdx =
7739             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
7740                          [](int M) { return M >= 0; }) -
7741             std::begin(MoveMask);
7742         int MoveMaskIdx =
7743             (((GoodMaskIdx - MoveOffset) & ~1) + 2 % 4) + MoveOffset;
7744         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7745         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7746         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7747         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
7748         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7749         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
7750       } else {
7751         assert(BadInputs.size() == 1 && "All sizes handled");
7752         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
7753                                     std::end(MoveMask), -1) -
7754                           std::begin(MoveMask);
7755         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7756         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7757       }
7758     }
7759
7760     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7761                                 MoveMask);
7762   };
7763   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7764                         /*MaskOffset*/ 0);
7765   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7766                         /*MaskOffset*/ 8);
7767
7768   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7769   // cross-half traffic in the final shuffle.
7770
7771   // Munge the mask to be a single-input mask after the unpack merges the
7772   // results.
7773   for (int &M : Mask)
7774     if (M != -1)
7775       M = 2 * (M % 4) + (M / 8);
7776
7777   return DAG.getVectorShuffle(
7778       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7779                                   DL, MVT::v8i16, V1, V2),
7780       DAG.getUNDEF(MVT::v8i16), Mask);
7781 }
7782
7783 /// \brief Generic lowering of 8-lane i16 shuffles.
7784 ///
7785 /// This handles both single-input shuffles and combined shuffle/blends with
7786 /// two inputs. The single input shuffles are immediately delegated to
7787 /// a dedicated lowering routine.
7788 ///
7789 /// The blends are lowered in one of three fundamental ways. If there are few
7790 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7791 /// of the input is significantly cheaper when lowered as an interleaving of
7792 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7793 /// halves of the inputs separately (making them have relatively few inputs)
7794 /// and then concatenate them.
7795 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7796                                        const X86Subtarget *Subtarget,
7797                                        SelectionDAG &DAG) {
7798   SDLoc DL(Op);
7799   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7800   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7801   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7802   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7803   ArrayRef<int> OrigMask = SVOp->getMask();
7804   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7805                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7806   MutableArrayRef<int> Mask(MaskStorage);
7807
7808   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7809
7810   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7811   auto isV2 = [](int M) { return M >= 8; };
7812
7813   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7814   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7815
7816   if (NumV2Inputs == 0)
7817     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7818
7819   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7820                             "to be V1-input shuffles.");
7821
7822   if (NumV1Inputs + NumV2Inputs <= 4)
7823     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7824
7825   // Check whether an interleaving lowering is likely to be more efficient.
7826   // This isn't perfect but it is a strong heuristic that tends to work well on
7827   // the kinds of shuffles that show up in practice.
7828   //
7829   // FIXME: Handle 1x, 2x, and 4x interleaving.
7830   if (shouldLowerAsInterleaving(Mask)) {
7831     // FIXME: Figure out whether we should pack these into the low or high
7832     // halves.
7833
7834     int EMask[8], OMask[8];
7835     for (int i = 0; i < 4; ++i) {
7836       EMask[i] = Mask[2*i];
7837       OMask[i] = Mask[2*i + 1];
7838       EMask[i + 4] = -1;
7839       OMask[i + 4] = -1;
7840     }
7841
7842     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7843     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7844
7845     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7846   }
7847
7848   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7849   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7850
7851   for (int i = 0; i < 4; ++i) {
7852     LoBlendMask[i] = Mask[i];
7853     HiBlendMask[i] = Mask[i + 4];
7854   }
7855
7856   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7857   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7858   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7859   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7860
7861   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7862                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7863 }
7864
7865 /// \brief Check whether a compaction lowering can be done by dropping even
7866 /// elements and compute how many times even elements must be dropped.
7867 ///
7868 /// This handles shuffles which take every Nth element where N is a power of
7869 /// two. Example shuffle masks:
7870 ///
7871 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
7872 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
7873 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
7874 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
7875 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
7876 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
7877 ///
7878 /// Any of these lanes can of course be undef.
7879 ///
7880 /// This routine only supports N <= 3.
7881 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
7882 /// for larger N.
7883 ///
7884 /// \returns N above, or the number of times even elements must be dropped if
7885 /// there is such a number. Otherwise returns zero.
7886 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
7887   // Figure out whether we're looping over two inputs or just one.
7888   bool IsSingleInput = isSingleInputShuffleMask(Mask);
7889
7890   // The modulus for the shuffle vector entries is based on whether this is
7891   // a single input or not.
7892   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
7893   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
7894          "We should only be called with masks with a power-of-2 size!");
7895
7896   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
7897
7898   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
7899   // and 2^3 simultaneously. This is because we may have ambiguity with
7900   // partially undef inputs.
7901   bool ViableForN[3] = {true, true, true};
7902
7903   for (int i = 0, e = Mask.size(); i < e; ++i) {
7904     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
7905     // want.
7906     if (Mask[i] == -1)
7907       continue;
7908
7909     bool IsAnyViable = false;
7910     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
7911       if (ViableForN[j]) {
7912         uint64_t N = j + 1;
7913
7914         // The shuffle mask must be equal to (i * 2^N) % M.
7915         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
7916           IsAnyViable = true;
7917         else
7918           ViableForN[j] = false;
7919       }
7920     // Early exit if we exhaust the possible powers of two.
7921     if (!IsAnyViable)
7922       break;
7923   }
7924
7925   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
7926     if (ViableForN[j])
7927       return j + 1;
7928
7929   // Return 0 as there is no viable power of two.
7930   return 0;
7931 }
7932
7933 /// \brief Generic lowering of v16i8 shuffles.
7934 ///
7935 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7936 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7937 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7938 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7939 /// back together.
7940 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7941                                        const X86Subtarget *Subtarget,
7942                                        SelectionDAG &DAG) {
7943   SDLoc DL(Op);
7944   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7945   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7946   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7947   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7948   ArrayRef<int> OrigMask = SVOp->getMask();
7949   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7950   int MaskStorage[16] = {
7951       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7952       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7953       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7954       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7955   MutableArrayRef<int> Mask(MaskStorage);
7956   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7957   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7958
7959   // For single-input shuffles, there are some nicer lowering tricks we can use.
7960   if (isSingleInputShuffleMask(Mask)) {
7961     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7962     // Notably, this handles splat and partial-splat shuffles more efficiently.
7963     // However, it only makes sense if the pre-duplication shuffle simplifies
7964     // things significantly. Currently, this means we need to be able to
7965     // express the pre-duplication shuffle as an i16 shuffle.
7966     //
7967     // FIXME: We should check for other patterns which can be widened into an
7968     // i16 shuffle as well.
7969     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7970       for (int i = 0; i < 16; i += 2) {
7971         if (Mask[i] != Mask[i + 1])
7972           return false;
7973       }
7974       return true;
7975     };
7976     auto tryToWidenViaDuplication = [&]() -> SDValue {
7977       if (!canWidenViaDuplication(Mask))
7978         return SDValue();
7979       SmallVector<int, 4> LoInputs;
7980       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7981                    [](int M) { return M >= 0 && M < 8; });
7982       std::sort(LoInputs.begin(), LoInputs.end());
7983       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7984                      LoInputs.end());
7985       SmallVector<int, 4> HiInputs;
7986       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7987                    [](int M) { return M >= 8; });
7988       std::sort(HiInputs.begin(), HiInputs.end());
7989       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7990                      HiInputs.end());
7991
7992       bool TargetLo = LoInputs.size() >= HiInputs.size();
7993       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7994       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7995
7996       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7997       SmallDenseMap<int, int, 8> LaneMap;
7998       for (int I : InPlaceInputs) {
7999         PreDupI16Shuffle[I/2] = I/2;
8000         LaneMap[I] = I;
8001       }
8002       int j = TargetLo ? 0 : 4, je = j + 4;
8003       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8004         // Check if j is already a shuffle of this input. This happens when
8005         // there are two adjacent bytes after we move the low one.
8006         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8007           // If we haven't yet mapped the input, search for a slot into which
8008           // we can map it.
8009           while (j < je && PreDupI16Shuffle[j] != -1)
8010             ++j;
8011
8012           if (j == je)
8013             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8014             return SDValue();
8015
8016           // Map this input with the i16 shuffle.
8017           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8018         }
8019
8020         // Update the lane map based on the mapping we ended up with.
8021         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8022       }
8023       V1 = DAG.getNode(
8024           ISD::BITCAST, DL, MVT::v16i8,
8025           DAG.getVectorShuffle(MVT::v8i16, DL,
8026                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8027                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8028
8029       // Unpack the bytes to form the i16s that will be shuffled into place.
8030       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8031                        MVT::v16i8, V1, V1);
8032
8033       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8034       for (int i = 0; i < 16; i += 2) {
8035         if (Mask[i] != -1)
8036           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8037         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8038       }
8039       return DAG.getNode(
8040           ISD::BITCAST, DL, MVT::v16i8,
8041           DAG.getVectorShuffle(MVT::v8i16, DL,
8042                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8043                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8044     };
8045     if (SDValue V = tryToWidenViaDuplication())
8046       return V;
8047   }
8048
8049   // Check whether an interleaving lowering is likely to be more efficient.
8050   // This isn't perfect but it is a strong heuristic that tends to work well on
8051   // the kinds of shuffles that show up in practice.
8052   //
8053   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8054   if (shouldLowerAsInterleaving(Mask)) {
8055     // FIXME: Figure out whether we should pack these into the low or high
8056     // halves.
8057
8058     int EMask[16], OMask[16];
8059     for (int i = 0; i < 8; ++i) {
8060       EMask[i] = Mask[2*i];
8061       OMask[i] = Mask[2*i + 1];
8062       EMask[i + 8] = -1;
8063       OMask[i + 8] = -1;
8064     }
8065
8066     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8067     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8068
8069     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8070   }
8071
8072   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8073   // with PSHUFB. It is important to do this before we attempt to generate any
8074   // blends but after all of the single-input lowerings. If the single input
8075   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8076   // want to preserve that and we can DAG combine any longer sequences into
8077   // a PSHUFB in the end. But once we start blending from multiple inputs,
8078   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8079   // and there are *very* few patterns that would actually be faster than the
8080   // PSHUFB approach because of its ability to zero lanes.
8081   //
8082   // FIXME: The only exceptions to the above are blends which are exact
8083   // interleavings with direct instructions supporting them. We currently don't
8084   // handle those well here.
8085   if (Subtarget->hasSSSE3()) {
8086     SDValue V1Mask[16];
8087     SDValue V2Mask[16];
8088     for (int i = 0; i < 16; ++i)
8089       if (Mask[i] == -1) {
8090         V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8091       } else {
8092         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8093         V2Mask[i] =
8094             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8095       }
8096     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8097                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8098     if (isSingleInputShuffleMask(Mask))
8099       return V1; // Single inputs are easy.
8100
8101     // Otherwise, blend the two.
8102     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8103                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8104     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8105   }
8106
8107   // Check whether a compaction lowering can be done. This handles shuffles
8108   // which take every Nth element for some even N. See the helper function for
8109   // details.
8110   //
8111   // We special case these as they can be particularly efficiently handled with
8112   // the PACKUSB instruction on x86 and they show up in common patterns of
8113   // rearranging bytes to truncate wide elements.
8114   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8115     // NumEvenDrops is the power of two stride of the elements. Another way of
8116     // thinking about it is that we need to drop the even elements this many
8117     // times to get the original input.
8118     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8119
8120     // First we need to zero all the dropped bytes.
8121     assert(NumEvenDrops <= 3 &&
8122            "No support for dropping even elements more than 3 times.");
8123     // We use the mask type to pick which bytes are preserved based on how many
8124     // elements are dropped.
8125     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8126     SDValue ByteClearMask =
8127         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8128                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8129     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8130     if (!IsSingleInput)
8131       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8132
8133     // Now pack things back together.
8134     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8135     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8136     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8137     for (int i = 1; i < NumEvenDrops; ++i) {
8138       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8139       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8140     }
8141
8142     return Result;
8143   }
8144
8145   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8146   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8147   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8148   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8149
8150   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8151                             MutableArrayRef<int> V1HalfBlendMask,
8152                             MutableArrayRef<int> V2HalfBlendMask) {
8153     for (int i = 0; i < 8; ++i)
8154       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8155         V1HalfBlendMask[i] = HalfMask[i];
8156         HalfMask[i] = i;
8157       } else if (HalfMask[i] >= 16) {
8158         V2HalfBlendMask[i] = HalfMask[i] - 16;
8159         HalfMask[i] = i + 8;
8160       }
8161   };
8162   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8163   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8164
8165   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8166
8167   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8168                              MutableArrayRef<int> HiBlendMask) {
8169     SDValue V1, V2;
8170     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8171     // them out and avoid using UNPCK{L,H} to extract the elements of V as
8172     // i16s.
8173     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8174                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
8175         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8176                      [](int M) { return M >= 0 && M % 2 == 1; })) {
8177       // Use a mask to drop the high bytes.
8178       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8179       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8180                        DAG.getConstant(0x00FF, MVT::v8i16));
8181
8182       // This will be a single vector shuffle instead of a blend so nuke V2.
8183       V2 = DAG.getUNDEF(MVT::v8i16);
8184
8185       // Squash the masks to point directly into V1.
8186       for (int &M : LoBlendMask)
8187         if (M >= 0)
8188           M /= 2;
8189       for (int &M : HiBlendMask)
8190         if (M >= 0)
8191           M /= 2;
8192     } else {
8193       // Otherwise just unpack the low half of V into V1 and the high half into
8194       // V2 so that we can blend them as i16s.
8195       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8196                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8197       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8198                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8199     }
8200
8201     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8202     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8203     return std::make_pair(BlendedLo, BlendedHi);
8204   };
8205   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8206   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8207   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8208
8209   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8210   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8211
8212   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8213 }
8214
8215 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8216 ///
8217 /// This routine breaks down the specific type of 128-bit shuffle and
8218 /// dispatches to the lowering routines accordingly.
8219 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8220                                         MVT VT, const X86Subtarget *Subtarget,
8221                                         SelectionDAG &DAG) {
8222   switch (VT.SimpleTy) {
8223   case MVT::v2i64:
8224     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8225   case MVT::v2f64:
8226     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8227   case MVT::v4i32:
8228     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8229   case MVT::v4f32:
8230     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8231   case MVT::v8i16:
8232     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8233   case MVT::v16i8:
8234     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8235
8236   default:
8237     llvm_unreachable("Unimplemented!");
8238   }
8239 }
8240
8241 /// \brief Tiny helper function to test whether adjacent masks are sequential.
8242 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
8243   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8244     if (Mask[i] + 1 != Mask[i+1])
8245       return false;
8246
8247   return true;
8248 }
8249
8250 /// \brief Top-level lowering for x86 vector shuffles.
8251 ///
8252 /// This handles decomposition, canonicalization, and lowering of all x86
8253 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8254 /// above in helper routines. The canonicalization attempts to widen shuffles
8255 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8256 /// s.t. only one of the two inputs needs to be tested, etc.
8257 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8258                                   SelectionDAG &DAG) {
8259   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8260   ArrayRef<int> Mask = SVOp->getMask();
8261   SDValue V1 = Op.getOperand(0);
8262   SDValue V2 = Op.getOperand(1);
8263   MVT VT = Op.getSimpleValueType();
8264   int NumElements = VT.getVectorNumElements();
8265   SDLoc dl(Op);
8266
8267   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8268
8269   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8270   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8271   if (V1IsUndef && V2IsUndef)
8272     return DAG.getUNDEF(VT);
8273
8274   // When we create a shuffle node we put the UNDEF node to second operand,
8275   // but in some cases the first operand may be transformed to UNDEF.
8276   // In this case we should just commute the node.
8277   if (V1IsUndef)
8278     return DAG.getCommutedVectorShuffle(*SVOp);
8279
8280   // Check for non-undef masks pointing at an undef vector and make the masks
8281   // undef as well. This makes it easier to match the shuffle based solely on
8282   // the mask.
8283   if (V2IsUndef)
8284     for (int M : Mask)
8285       if (M >= NumElements) {
8286         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8287         for (int &M : NewMask)
8288           if (M >= NumElements)
8289             M = -1;
8290         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8291       }
8292
8293   // For integer vector shuffles, try to collapse them into a shuffle of fewer
8294   // lanes but wider integers. We cap this to not form integers larger than i64
8295   // but it might be interesting to form i128 integers to handle flipping the
8296   // low and high halves of AVX 256-bit vectors.
8297   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8298       areAdjacentMasksSequential(Mask)) {
8299     SmallVector<int, 8> NewMask;
8300     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8301       NewMask.push_back(Mask[i] / 2);
8302     MVT NewVT =
8303         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8304                          VT.getVectorNumElements() / 2);
8305     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8306     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8307     return DAG.getNode(ISD::BITCAST, dl, VT,
8308                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8309   }
8310
8311   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8312   for (int M : SVOp->getMask())
8313     if (M < 0)
8314       ++NumUndefElements;
8315     else if (M < NumElements)
8316       ++NumV1Elements;
8317     else
8318       ++NumV2Elements;
8319
8320   // Commute the shuffle as needed such that more elements come from V1 than
8321   // V2. This allows us to match the shuffle pattern strictly on how many
8322   // elements come from V1 without handling the symmetric cases.
8323   if (NumV2Elements > NumV1Elements)
8324     return DAG.getCommutedVectorShuffle(*SVOp);
8325
8326   // When the number of V1 and V2 elements are the same, try to minimize the
8327   // number of uses of V2 in the low half of the vector.
8328   if (NumV1Elements == NumV2Elements) {
8329     int LowV1Elements = 0, LowV2Elements = 0;
8330     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8331       if (M >= NumElements)
8332         ++LowV2Elements;
8333       else if (M >= 0)
8334         ++LowV1Elements;
8335     if (LowV2Elements > LowV1Elements)
8336       return DAG.getCommutedVectorShuffle(*SVOp);
8337   }
8338
8339   // For each vector width, delegate to a specialized lowering routine.
8340   if (VT.getSizeInBits() == 128)
8341     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8342
8343   llvm_unreachable("Unimplemented!");
8344 }
8345
8346
8347 //===----------------------------------------------------------------------===//
8348 // Legacy vector shuffle lowering
8349 //
8350 // This code is the legacy code handling vector shuffles until the above
8351 // replaces its functionality and performance.
8352 //===----------------------------------------------------------------------===//
8353
8354 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8355                         bool hasInt256, unsigned *MaskOut = nullptr) {
8356   MVT EltVT = VT.getVectorElementType();
8357
8358   // There is no blend with immediate in AVX-512.
8359   if (VT.is512BitVector())
8360     return false;
8361
8362   if (!hasSSE41 || EltVT == MVT::i8)
8363     return false;
8364   if (!hasInt256 && VT == MVT::v16i16)
8365     return false;
8366
8367   unsigned MaskValue = 0;
8368   unsigned NumElems = VT.getVectorNumElements();
8369   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8370   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8371   unsigned NumElemsInLane = NumElems / NumLanes;
8372
8373   // Blend for v16i16 should be symetric for the both lanes.
8374   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8375
8376     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8377     int EltIdx = MaskVals[i];
8378
8379     if ((EltIdx < 0 || EltIdx == (int)i) &&
8380         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8381       continue;
8382
8383     if (((unsigned)EltIdx == (i + NumElems)) &&
8384         (SndLaneEltIdx < 0 ||
8385          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8386       MaskValue |= (1 << i);
8387     else
8388       return false;
8389   }
8390
8391   if (MaskOut)
8392     *MaskOut = MaskValue;
8393   return true;
8394 }
8395
8396 // Try to lower a shuffle node into a simple blend instruction.
8397 // This function assumes isBlendMask returns true for this
8398 // SuffleVectorSDNode
8399 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8400                                           unsigned MaskValue,
8401                                           const X86Subtarget *Subtarget,
8402                                           SelectionDAG &DAG) {
8403   MVT VT = SVOp->getSimpleValueType(0);
8404   MVT EltVT = VT.getVectorElementType();
8405   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8406                      Subtarget->hasInt256() && "Trying to lower a "
8407                                                "VECTOR_SHUFFLE to a Blend but "
8408                                                "with the wrong mask"));
8409   SDValue V1 = SVOp->getOperand(0);
8410   SDValue V2 = SVOp->getOperand(1);
8411   SDLoc dl(SVOp);
8412   unsigned NumElems = VT.getVectorNumElements();
8413
8414   // Convert i32 vectors to floating point if it is not AVX2.
8415   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8416   MVT BlendVT = VT;
8417   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8418     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8419                                NumElems);
8420     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8421     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8422   }
8423
8424   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8425                             DAG.getConstant(MaskValue, MVT::i32));
8426   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8427 }
8428
8429 /// In vector type \p VT, return true if the element at index \p InputIdx
8430 /// falls on a different 128-bit lane than \p OutputIdx.
8431 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8432                                      unsigned OutputIdx) {
8433   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8434   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8435 }
8436
8437 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8438 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8439 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8440 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8441 /// zero.
8442 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8443                          SelectionDAG &DAG) {
8444   MVT VT = V1.getSimpleValueType();
8445   assert(VT.is128BitVector() || VT.is256BitVector());
8446
8447   MVT EltVT = VT.getVectorElementType();
8448   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8449   unsigned NumElts = VT.getVectorNumElements();
8450
8451   SmallVector<SDValue, 32> PshufbMask;
8452   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8453     int InputIdx = MaskVals[OutputIdx];
8454     unsigned InputByteIdx;
8455
8456     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8457       InputByteIdx = 0x80;
8458     else {
8459       // Cross lane is not allowed.
8460       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8461         return SDValue();
8462       InputByteIdx = InputIdx * EltSizeInBytes;
8463       // Index is an byte offset within the 128-bit lane.
8464       InputByteIdx &= 0xf;
8465     }
8466
8467     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8468       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8469       if (InputByteIdx != 0x80)
8470         ++InputByteIdx;
8471     }
8472   }
8473
8474   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8475   if (ShufVT != VT)
8476     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8477   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8478                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8479 }
8480
8481 // v8i16 shuffles - Prefer shuffles in the following order:
8482 // 1. [all]   pshuflw, pshufhw, optional move
8483 // 2. [ssse3] 1 x pshufb
8484 // 3. [ssse3] 2 x pshufb + 1 x por
8485 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8486 static SDValue
8487 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8488                          SelectionDAG &DAG) {
8489   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8490   SDValue V1 = SVOp->getOperand(0);
8491   SDValue V2 = SVOp->getOperand(1);
8492   SDLoc dl(SVOp);
8493   SmallVector<int, 8> MaskVals;
8494
8495   // Determine if more than 1 of the words in each of the low and high quadwords
8496   // of the result come from the same quadword of one of the two inputs.  Undef
8497   // mask values count as coming from any quadword, for better codegen.
8498   //
8499   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8500   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8501   unsigned LoQuad[] = { 0, 0, 0, 0 };
8502   unsigned HiQuad[] = { 0, 0, 0, 0 };
8503   // Indices of quads used.
8504   std::bitset<4> InputQuads;
8505   for (unsigned i = 0; i < 8; ++i) {
8506     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8507     int EltIdx = SVOp->getMaskElt(i);
8508     MaskVals.push_back(EltIdx);
8509     if (EltIdx < 0) {
8510       ++Quad[0];
8511       ++Quad[1];
8512       ++Quad[2];
8513       ++Quad[3];
8514       continue;
8515     }
8516     ++Quad[EltIdx / 4];
8517     InputQuads.set(EltIdx / 4);
8518   }
8519
8520   int BestLoQuad = -1;
8521   unsigned MaxQuad = 1;
8522   for (unsigned i = 0; i < 4; ++i) {
8523     if (LoQuad[i] > MaxQuad) {
8524       BestLoQuad = i;
8525       MaxQuad = LoQuad[i];
8526     }
8527   }
8528
8529   int BestHiQuad = -1;
8530   MaxQuad = 1;
8531   for (unsigned i = 0; i < 4; ++i) {
8532     if (HiQuad[i] > MaxQuad) {
8533       BestHiQuad = i;
8534       MaxQuad = HiQuad[i];
8535     }
8536   }
8537
8538   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8539   // of the two input vectors, shuffle them into one input vector so only a
8540   // single pshufb instruction is necessary. If there are more than 2 input
8541   // quads, disable the next transformation since it does not help SSSE3.
8542   bool V1Used = InputQuads[0] || InputQuads[1];
8543   bool V2Used = InputQuads[2] || InputQuads[3];
8544   if (Subtarget->hasSSSE3()) {
8545     if (InputQuads.count() == 2 && V1Used && V2Used) {
8546       BestLoQuad = InputQuads[0] ? 0 : 1;
8547       BestHiQuad = InputQuads[2] ? 2 : 3;
8548     }
8549     if (InputQuads.count() > 2) {
8550       BestLoQuad = -1;
8551       BestHiQuad = -1;
8552     }
8553   }
8554
8555   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8556   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8557   // words from all 4 input quadwords.
8558   SDValue NewV;
8559   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8560     int MaskV[] = {
8561       BestLoQuad < 0 ? 0 : BestLoQuad,
8562       BestHiQuad < 0 ? 1 : BestHiQuad
8563     };
8564     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8565                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8566                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8567     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8568
8569     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8570     // source words for the shuffle, to aid later transformations.
8571     bool AllWordsInNewV = true;
8572     bool InOrder[2] = { true, true };
8573     for (unsigned i = 0; i != 8; ++i) {
8574       int idx = MaskVals[i];
8575       if (idx != (int)i)
8576         InOrder[i/4] = false;
8577       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8578         continue;
8579       AllWordsInNewV = false;
8580       break;
8581     }
8582
8583     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8584     if (AllWordsInNewV) {
8585       for (int i = 0; i != 8; ++i) {
8586         int idx = MaskVals[i];
8587         if (idx < 0)
8588           continue;
8589         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8590         if ((idx != i) && idx < 4)
8591           pshufhw = false;
8592         if ((idx != i) && idx > 3)
8593           pshuflw = false;
8594       }
8595       V1 = NewV;
8596       V2Used = false;
8597       BestLoQuad = 0;
8598       BestHiQuad = 1;
8599     }
8600
8601     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8602     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8603     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8604       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8605       unsigned TargetMask = 0;
8606       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8607                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8608       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8609       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8610                              getShufflePSHUFLWImmediate(SVOp);
8611       V1 = NewV.getOperand(0);
8612       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8613     }
8614   }
8615
8616   // Promote splats to a larger type which usually leads to more efficient code.
8617   // FIXME: Is this true if pshufb is available?
8618   if (SVOp->isSplat())
8619     return PromoteSplat(SVOp, DAG);
8620
8621   // If we have SSSE3, and all words of the result are from 1 input vector,
8622   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8623   // is present, fall back to case 4.
8624   if (Subtarget->hasSSSE3()) {
8625     SmallVector<SDValue,16> pshufbMask;
8626
8627     // If we have elements from both input vectors, set the high bit of the
8628     // shuffle mask element to zero out elements that come from V2 in the V1
8629     // mask, and elements that come from V1 in the V2 mask, so that the two
8630     // results can be OR'd together.
8631     bool TwoInputs = V1Used && V2Used;
8632     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8633     if (!TwoInputs)
8634       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8635
8636     // Calculate the shuffle mask for the second input, shuffle it, and
8637     // OR it with the first shuffled input.
8638     CommuteVectorShuffleMask(MaskVals, 8);
8639     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8640     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8641     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8642   }
8643
8644   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8645   // and update MaskVals with new element order.
8646   std::bitset<8> InOrder;
8647   if (BestLoQuad >= 0) {
8648     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8649     for (int i = 0; i != 4; ++i) {
8650       int idx = MaskVals[i];
8651       if (idx < 0) {
8652         InOrder.set(i);
8653       } else if ((idx / 4) == BestLoQuad) {
8654         MaskV[i] = idx & 3;
8655         InOrder.set(i);
8656       }
8657     }
8658     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8659                                 &MaskV[0]);
8660
8661     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8662       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8663       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8664                                   NewV.getOperand(0),
8665                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8666     }
8667   }
8668
8669   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8670   // and update MaskVals with the new element order.
8671   if (BestHiQuad >= 0) {
8672     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8673     for (unsigned i = 4; i != 8; ++i) {
8674       int idx = MaskVals[i];
8675       if (idx < 0) {
8676         InOrder.set(i);
8677       } else if ((idx / 4) == BestHiQuad) {
8678         MaskV[i] = (idx & 3) + 4;
8679         InOrder.set(i);
8680       }
8681     }
8682     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8683                                 &MaskV[0]);
8684
8685     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8686       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8687       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8688                                   NewV.getOperand(0),
8689                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8690     }
8691   }
8692
8693   // In case BestHi & BestLo were both -1, which means each quadword has a word
8694   // from each of the four input quadwords, calculate the InOrder bitvector now
8695   // before falling through to the insert/extract cleanup.
8696   if (BestLoQuad == -1 && BestHiQuad == -1) {
8697     NewV = V1;
8698     for (int i = 0; i != 8; ++i)
8699       if (MaskVals[i] < 0 || MaskVals[i] == i)
8700         InOrder.set(i);
8701   }
8702
8703   // The other elements are put in the right place using pextrw and pinsrw.
8704   for (unsigned i = 0; i != 8; ++i) {
8705     if (InOrder[i])
8706       continue;
8707     int EltIdx = MaskVals[i];
8708     if (EltIdx < 0)
8709       continue;
8710     SDValue ExtOp = (EltIdx < 8) ?
8711       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8712                   DAG.getIntPtrConstant(EltIdx)) :
8713       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8714                   DAG.getIntPtrConstant(EltIdx - 8));
8715     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8716                        DAG.getIntPtrConstant(i));
8717   }
8718   return NewV;
8719 }
8720
8721 /// \brief v16i16 shuffles
8722 ///
8723 /// FIXME: We only support generation of a single pshufb currently.  We can
8724 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8725 /// well (e.g 2 x pshufb + 1 x por).
8726 static SDValue
8727 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8728   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8729   SDValue V1 = SVOp->getOperand(0);
8730   SDValue V2 = SVOp->getOperand(1);
8731   SDLoc dl(SVOp);
8732
8733   if (V2.getOpcode() != ISD::UNDEF)
8734     return SDValue();
8735
8736   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8737   return getPSHUFB(MaskVals, V1, dl, DAG);
8738 }
8739
8740 // v16i8 shuffles - Prefer shuffles in the following order:
8741 // 1. [ssse3] 1 x pshufb
8742 // 2. [ssse3] 2 x pshufb + 1 x por
8743 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8744 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8745                                         const X86Subtarget* Subtarget,
8746                                         SelectionDAG &DAG) {
8747   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8748   SDValue V1 = SVOp->getOperand(0);
8749   SDValue V2 = SVOp->getOperand(1);
8750   SDLoc dl(SVOp);
8751   ArrayRef<int> MaskVals = SVOp->getMask();
8752
8753   // Promote splats to a larger type which usually leads to more efficient code.
8754   // FIXME: Is this true if pshufb is available?
8755   if (SVOp->isSplat())
8756     return PromoteSplat(SVOp, DAG);
8757
8758   // If we have SSSE3, case 1 is generated when all result bytes come from
8759   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8760   // present, fall back to case 3.
8761
8762   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8763   if (Subtarget->hasSSSE3()) {
8764     SmallVector<SDValue,16> pshufbMask;
8765
8766     // If all result elements are from one input vector, then only translate
8767     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8768     //
8769     // Otherwise, we have elements from both input vectors, and must zero out
8770     // elements that come from V2 in the first mask, and V1 in the second mask
8771     // so that we can OR them together.
8772     for (unsigned i = 0; i != 16; ++i) {
8773       int EltIdx = MaskVals[i];
8774       if (EltIdx < 0 || EltIdx >= 16)
8775         EltIdx = 0x80;
8776       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8777     }
8778     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8779                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8780                                  MVT::v16i8, pshufbMask));
8781
8782     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8783     // the 2nd operand if it's undefined or zero.
8784     if (V2.getOpcode() == ISD::UNDEF ||
8785         ISD::isBuildVectorAllZeros(V2.getNode()))
8786       return V1;
8787
8788     // Calculate the shuffle mask for the second input, shuffle it, and
8789     // OR it with the first shuffled input.
8790     pshufbMask.clear();
8791     for (unsigned i = 0; i != 16; ++i) {
8792       int EltIdx = MaskVals[i];
8793       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8794       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8795     }
8796     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8797                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8798                                  MVT::v16i8, pshufbMask));
8799     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8800   }
8801
8802   // No SSSE3 - Calculate in place words and then fix all out of place words
8803   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8804   // the 16 different words that comprise the two doublequadword input vectors.
8805   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8806   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8807   SDValue NewV = V1;
8808   for (int i = 0; i != 8; ++i) {
8809     int Elt0 = MaskVals[i*2];
8810     int Elt1 = MaskVals[i*2+1];
8811
8812     // This word of the result is all undef, skip it.
8813     if (Elt0 < 0 && Elt1 < 0)
8814       continue;
8815
8816     // This word of the result is already in the correct place, skip it.
8817     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8818       continue;
8819
8820     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8821     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8822     SDValue InsElt;
8823
8824     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8825     // using a single extract together, load it and store it.
8826     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8827       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8828                            DAG.getIntPtrConstant(Elt1 / 2));
8829       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8830                         DAG.getIntPtrConstant(i));
8831       continue;
8832     }
8833
8834     // If Elt1 is defined, extract it from the appropriate source.  If the
8835     // source byte is not also odd, shift the extracted word left 8 bits
8836     // otherwise clear the bottom 8 bits if we need to do an or.
8837     if (Elt1 >= 0) {
8838       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8839                            DAG.getIntPtrConstant(Elt1 / 2));
8840       if ((Elt1 & 1) == 0)
8841         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8842                              DAG.getConstant(8,
8843                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8844       else if (Elt0 >= 0)
8845         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8846                              DAG.getConstant(0xFF00, MVT::i16));
8847     }
8848     // If Elt0 is defined, extract it from the appropriate source.  If the
8849     // source byte is not also even, shift the extracted word right 8 bits. If
8850     // Elt1 was also defined, OR the extracted values together before
8851     // inserting them in the result.
8852     if (Elt0 >= 0) {
8853       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8854                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8855       if ((Elt0 & 1) != 0)
8856         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8857                               DAG.getConstant(8,
8858                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8859       else if (Elt1 >= 0)
8860         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8861                              DAG.getConstant(0x00FF, MVT::i16));
8862       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8863                          : InsElt0;
8864     }
8865     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8866                        DAG.getIntPtrConstant(i));
8867   }
8868   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8869 }
8870
8871 // v32i8 shuffles - Translate to VPSHUFB if possible.
8872 static
8873 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8874                                  const X86Subtarget *Subtarget,
8875                                  SelectionDAG &DAG) {
8876   MVT VT = SVOp->getSimpleValueType(0);
8877   SDValue V1 = SVOp->getOperand(0);
8878   SDValue V2 = SVOp->getOperand(1);
8879   SDLoc dl(SVOp);
8880   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8881
8882   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8883   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8884   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8885
8886   // VPSHUFB may be generated if
8887   // (1) one of input vector is undefined or zeroinitializer.
8888   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8889   // And (2) the mask indexes don't cross the 128-bit lane.
8890   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8891       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8892     return SDValue();
8893
8894   if (V1IsAllZero && !V2IsAllZero) {
8895     CommuteVectorShuffleMask(MaskVals, 32);
8896     V1 = V2;
8897   }
8898   return getPSHUFB(MaskVals, V1, dl, DAG);
8899 }
8900
8901 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8902 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8903 /// done when every pair / quad of shuffle mask elements point to elements in
8904 /// the right sequence. e.g.
8905 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8906 static
8907 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8908                                  SelectionDAG &DAG) {
8909   MVT VT = SVOp->getSimpleValueType(0);
8910   SDLoc dl(SVOp);
8911   unsigned NumElems = VT.getVectorNumElements();
8912   MVT NewVT;
8913   unsigned Scale;
8914   switch (VT.SimpleTy) {
8915   default: llvm_unreachable("Unexpected!");
8916   case MVT::v2i64:
8917   case MVT::v2f64:
8918            return SDValue(SVOp, 0);
8919   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8920   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8921   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8922   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8923   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8924   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8925   }
8926
8927   SmallVector<int, 8> MaskVec;
8928   for (unsigned i = 0; i != NumElems; i += Scale) {
8929     int StartIdx = -1;
8930     for (unsigned j = 0; j != Scale; ++j) {
8931       int EltIdx = SVOp->getMaskElt(i+j);
8932       if (EltIdx < 0)
8933         continue;
8934       if (StartIdx < 0)
8935         StartIdx = (EltIdx / Scale);
8936       if (EltIdx != (int)(StartIdx*Scale + j))
8937         return SDValue();
8938     }
8939     MaskVec.push_back(StartIdx);
8940   }
8941
8942   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8943   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8944   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8945 }
8946
8947 /// getVZextMovL - Return a zero-extending vector move low node.
8948 ///
8949 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8950                             SDValue SrcOp, SelectionDAG &DAG,
8951                             const X86Subtarget *Subtarget, SDLoc dl) {
8952   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8953     LoadSDNode *LD = nullptr;
8954     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8955       LD = dyn_cast<LoadSDNode>(SrcOp);
8956     if (!LD) {
8957       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8958       // instead.
8959       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8960       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8961           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8962           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8963           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8964         // PR2108
8965         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8966         return DAG.getNode(ISD::BITCAST, dl, VT,
8967                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8968                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8969                                                    OpVT,
8970                                                    SrcOp.getOperand(0)
8971                                                           .getOperand(0))));
8972       }
8973     }
8974   }
8975
8976   return DAG.getNode(ISD::BITCAST, dl, VT,
8977                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8978                                  DAG.getNode(ISD::BITCAST, dl,
8979                                              OpVT, SrcOp)));
8980 }
8981
8982 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8983 /// which could not be matched by any known target speficic shuffle
8984 static SDValue
8985 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8986
8987   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8988   if (NewOp.getNode())
8989     return NewOp;
8990
8991   MVT VT = SVOp->getSimpleValueType(0);
8992
8993   unsigned NumElems = VT.getVectorNumElements();
8994   unsigned NumLaneElems = NumElems / 2;
8995
8996   SDLoc dl(SVOp);
8997   MVT EltVT = VT.getVectorElementType();
8998   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8999   SDValue Output[2];
9000
9001   SmallVector<int, 16> Mask;
9002   for (unsigned l = 0; l < 2; ++l) {
9003     // Build a shuffle mask for the output, discovering on the fly which
9004     // input vectors to use as shuffle operands (recorded in InputUsed).
9005     // If building a suitable shuffle vector proves too hard, then bail
9006     // out with UseBuildVector set.
9007     bool UseBuildVector = false;
9008     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9009     unsigned LaneStart = l * NumLaneElems;
9010     for (unsigned i = 0; i != NumLaneElems; ++i) {
9011       // The mask element.  This indexes into the input.
9012       int Idx = SVOp->getMaskElt(i+LaneStart);
9013       if (Idx < 0) {
9014         // the mask element does not index into any input vector.
9015         Mask.push_back(-1);
9016         continue;
9017       }
9018
9019       // The input vector this mask element indexes into.
9020       int Input = Idx / NumLaneElems;
9021
9022       // Turn the index into an offset from the start of the input vector.
9023       Idx -= Input * NumLaneElems;
9024
9025       // Find or create a shuffle vector operand to hold this input.
9026       unsigned OpNo;
9027       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9028         if (InputUsed[OpNo] == Input)
9029           // This input vector is already an operand.
9030           break;
9031         if (InputUsed[OpNo] < 0) {
9032           // Create a new operand for this input vector.
9033           InputUsed[OpNo] = Input;
9034           break;
9035         }
9036       }
9037
9038       if (OpNo >= array_lengthof(InputUsed)) {
9039         // More than two input vectors used!  Give up on trying to create a
9040         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
9041         UseBuildVector = true;
9042         break;
9043       }
9044
9045       // Add the mask index for the new shuffle vector.
9046       Mask.push_back(Idx + OpNo * NumLaneElems);
9047     }
9048
9049     if (UseBuildVector) {
9050       SmallVector<SDValue, 16> SVOps;
9051       for (unsigned i = 0; i != NumLaneElems; ++i) {
9052         // The mask element.  This indexes into the input.
9053         int Idx = SVOp->getMaskElt(i+LaneStart);
9054         if (Idx < 0) {
9055           SVOps.push_back(DAG.getUNDEF(EltVT));
9056           continue;
9057         }
9058
9059         // The input vector this mask element indexes into.
9060         int Input = Idx / NumElems;
9061
9062         // Turn the index into an offset from the start of the input vector.
9063         Idx -= Input * NumElems;
9064
9065         // Extract the vector element by hand.
9066         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9067                                     SVOp->getOperand(Input),
9068                                     DAG.getIntPtrConstant(Idx)));
9069       }
9070
9071       // Construct the output using a BUILD_VECTOR.
9072       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9073     } else if (InputUsed[0] < 0) {
9074       // No input vectors were used! The result is undefined.
9075       Output[l] = DAG.getUNDEF(NVT);
9076     } else {
9077       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9078                                         (InputUsed[0] % 2) * NumLaneElems,
9079                                         DAG, dl);
9080       // If only one input was used, use an undefined vector for the other.
9081       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9082         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9083                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9084       // At least one input vector was used. Create a new shuffle vector.
9085       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9086     }
9087
9088     Mask.clear();
9089   }
9090
9091   // Concatenate the result back
9092   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9093 }
9094
9095 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9096 /// 4 elements, and match them with several different shuffle types.
9097 static SDValue
9098 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9099   SDValue V1 = SVOp->getOperand(0);
9100   SDValue V2 = SVOp->getOperand(1);
9101   SDLoc dl(SVOp);
9102   MVT VT = SVOp->getSimpleValueType(0);
9103
9104   assert(VT.is128BitVector() && "Unsupported vector size");
9105
9106   std::pair<int, int> Locs[4];
9107   int Mask1[] = { -1, -1, -1, -1 };
9108   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9109
9110   unsigned NumHi = 0;
9111   unsigned NumLo = 0;
9112   for (unsigned i = 0; i != 4; ++i) {
9113     int Idx = PermMask[i];
9114     if (Idx < 0) {
9115       Locs[i] = std::make_pair(-1, -1);
9116     } else {
9117       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9118       if (Idx < 4) {
9119         Locs[i] = std::make_pair(0, NumLo);
9120         Mask1[NumLo] = Idx;
9121         NumLo++;
9122       } else {
9123         Locs[i] = std::make_pair(1, NumHi);
9124         if (2+NumHi < 4)
9125           Mask1[2+NumHi] = Idx;
9126         NumHi++;
9127       }
9128     }
9129   }
9130
9131   if (NumLo <= 2 && NumHi <= 2) {
9132     // If no more than two elements come from either vector. This can be
9133     // implemented with two shuffles. First shuffle gather the elements.
9134     // The second shuffle, which takes the first shuffle as both of its
9135     // vector operands, put the elements into the right order.
9136     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9137
9138     int Mask2[] = { -1, -1, -1, -1 };
9139
9140     for (unsigned i = 0; i != 4; ++i)
9141       if (Locs[i].first != -1) {
9142         unsigned Idx = (i < 2) ? 0 : 4;
9143         Idx += Locs[i].first * 2 + Locs[i].second;
9144         Mask2[i] = Idx;
9145       }
9146
9147     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9148   }
9149
9150   if (NumLo == 3 || NumHi == 3) {
9151     // Otherwise, we must have three elements from one vector, call it X, and
9152     // one element from the other, call it Y.  First, use a shufps to build an
9153     // intermediate vector with the one element from Y and the element from X
9154     // that will be in the same half in the final destination (the indexes don't
9155     // matter). Then, use a shufps to build the final vector, taking the half
9156     // containing the element from Y from the intermediate, and the other half
9157     // from X.
9158     if (NumHi == 3) {
9159       // Normalize it so the 3 elements come from V1.
9160       CommuteVectorShuffleMask(PermMask, 4);
9161       std::swap(V1, V2);
9162     }
9163
9164     // Find the element from V2.
9165     unsigned HiIndex;
9166     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9167       int Val = PermMask[HiIndex];
9168       if (Val < 0)
9169         continue;
9170       if (Val >= 4)
9171         break;
9172     }
9173
9174     Mask1[0] = PermMask[HiIndex];
9175     Mask1[1] = -1;
9176     Mask1[2] = PermMask[HiIndex^1];
9177     Mask1[3] = -1;
9178     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9179
9180     if (HiIndex >= 2) {
9181       Mask1[0] = PermMask[0];
9182       Mask1[1] = PermMask[1];
9183       Mask1[2] = HiIndex & 1 ? 6 : 4;
9184       Mask1[3] = HiIndex & 1 ? 4 : 6;
9185       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9186     }
9187
9188     Mask1[0] = HiIndex & 1 ? 2 : 0;
9189     Mask1[1] = HiIndex & 1 ? 0 : 2;
9190     Mask1[2] = PermMask[2];
9191     Mask1[3] = PermMask[3];
9192     if (Mask1[2] >= 0)
9193       Mask1[2] += 4;
9194     if (Mask1[3] >= 0)
9195       Mask1[3] += 4;
9196     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9197   }
9198
9199   // Break it into (shuffle shuffle_hi, shuffle_lo).
9200   int LoMask[] = { -1, -1, -1, -1 };
9201   int HiMask[] = { -1, -1, -1, -1 };
9202
9203   int *MaskPtr = LoMask;
9204   unsigned MaskIdx = 0;
9205   unsigned LoIdx = 0;
9206   unsigned HiIdx = 2;
9207   for (unsigned i = 0; i != 4; ++i) {
9208     if (i == 2) {
9209       MaskPtr = HiMask;
9210       MaskIdx = 1;
9211       LoIdx = 0;
9212       HiIdx = 2;
9213     }
9214     int Idx = PermMask[i];
9215     if (Idx < 0) {
9216       Locs[i] = std::make_pair(-1, -1);
9217     } else if (Idx < 4) {
9218       Locs[i] = std::make_pair(MaskIdx, LoIdx);
9219       MaskPtr[LoIdx] = Idx;
9220       LoIdx++;
9221     } else {
9222       Locs[i] = std::make_pair(MaskIdx, HiIdx);
9223       MaskPtr[HiIdx] = Idx;
9224       HiIdx++;
9225     }
9226   }
9227
9228   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9229   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9230   int MaskOps[] = { -1, -1, -1, -1 };
9231   for (unsigned i = 0; i != 4; ++i)
9232     if (Locs[i].first != -1)
9233       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9234   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9235 }
9236
9237 static bool MayFoldVectorLoad(SDValue V) {
9238   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9239     V = V.getOperand(0);
9240
9241   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9242     V = V.getOperand(0);
9243   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9244       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9245     // BUILD_VECTOR (load), undef
9246     V = V.getOperand(0);
9247
9248   return MayFoldLoad(V);
9249 }
9250
9251 static
9252 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9253   MVT VT = Op.getSimpleValueType();
9254
9255   // Canonizalize to v2f64.
9256   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9257   return DAG.getNode(ISD::BITCAST, dl, VT,
9258                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9259                                           V1, DAG));
9260 }
9261
9262 static
9263 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9264                         bool HasSSE2) {
9265   SDValue V1 = Op.getOperand(0);
9266   SDValue V2 = Op.getOperand(1);
9267   MVT VT = Op.getSimpleValueType();
9268
9269   assert(VT != MVT::v2i64 && "unsupported shuffle type");
9270
9271   if (HasSSE2 && VT == MVT::v2f64)
9272     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9273
9274   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9275   return DAG.getNode(ISD::BITCAST, dl, VT,
9276                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9277                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9278                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9279 }
9280
9281 static
9282 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9283   SDValue V1 = Op.getOperand(0);
9284   SDValue V2 = Op.getOperand(1);
9285   MVT VT = Op.getSimpleValueType();
9286
9287   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9288          "unsupported shuffle type");
9289
9290   if (V2.getOpcode() == ISD::UNDEF)
9291     V2 = V1;
9292
9293   // v4i32 or v4f32
9294   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9295 }
9296
9297 static
9298 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9299   SDValue V1 = Op.getOperand(0);
9300   SDValue V2 = Op.getOperand(1);
9301   MVT VT = Op.getSimpleValueType();
9302   unsigned NumElems = VT.getVectorNumElements();
9303
9304   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9305   // operand of these instructions is only memory, so check if there's a
9306   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9307   // same masks.
9308   bool CanFoldLoad = false;
9309
9310   // Trivial case, when V2 comes from a load.
9311   if (MayFoldVectorLoad(V2))
9312     CanFoldLoad = true;
9313
9314   // When V1 is a load, it can be folded later into a store in isel, example:
9315   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9316   //    turns into:
9317   //  (MOVLPSmr addr:$src1, VR128:$src2)
9318   // So, recognize this potential and also use MOVLPS or MOVLPD
9319   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9320     CanFoldLoad = true;
9321
9322   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9323   if (CanFoldLoad) {
9324     if (HasSSE2 && NumElems == 2)
9325       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9326
9327     if (NumElems == 4)
9328       // If we don't care about the second element, proceed to use movss.
9329       if (SVOp->getMaskElt(1) != -1)
9330         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9331   }
9332
9333   // movl and movlp will both match v2i64, but v2i64 is never matched by
9334   // movl earlier because we make it strict to avoid messing with the movlp load
9335   // folding logic (see the code above getMOVLP call). Match it here then,
9336   // this is horrible, but will stay like this until we move all shuffle
9337   // matching to x86 specific nodes. Note that for the 1st condition all
9338   // types are matched with movsd.
9339   if (HasSSE2) {
9340     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9341     // as to remove this logic from here, as much as possible
9342     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9343       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9344     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9345   }
9346
9347   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9348
9349   // Invert the operand order and use SHUFPS to match it.
9350   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9351                               getShuffleSHUFImmediate(SVOp), DAG);
9352 }
9353
9354 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9355                                          SelectionDAG &DAG) {
9356   SDLoc dl(Load);
9357   MVT VT = Load->getSimpleValueType(0);
9358   MVT EVT = VT.getVectorElementType();
9359   SDValue Addr = Load->getOperand(1);
9360   SDValue NewAddr = DAG.getNode(
9361       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9362       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9363
9364   SDValue NewLoad =
9365       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9366                   DAG.getMachineFunction().getMachineMemOperand(
9367                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9368   return NewLoad;
9369 }
9370
9371 // It is only safe to call this function if isINSERTPSMask is true for
9372 // this shufflevector mask.
9373 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9374                            SelectionDAG &DAG) {
9375   // Generate an insertps instruction when inserting an f32 from memory onto a
9376   // v4f32 or when copying a member from one v4f32 to another.
9377   // We also use it for transferring i32 from one register to another,
9378   // since it simply copies the same bits.
9379   // If we're transferring an i32 from memory to a specific element in a
9380   // register, we output a generic DAG that will match the PINSRD
9381   // instruction.
9382   MVT VT = SVOp->getSimpleValueType(0);
9383   MVT EVT = VT.getVectorElementType();
9384   SDValue V1 = SVOp->getOperand(0);
9385   SDValue V2 = SVOp->getOperand(1);
9386   auto Mask = SVOp->getMask();
9387   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9388          "unsupported vector type for insertps/pinsrd");
9389
9390   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9391   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9392   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9393
9394   SDValue From;
9395   SDValue To;
9396   unsigned DestIndex;
9397   if (FromV1 == 1) {
9398     From = V1;
9399     To = V2;
9400     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9401                 Mask.begin();
9402
9403     // If we have 1 element from each vector, we have to check if we're
9404     // changing V1's element's place. If so, we're done. Otherwise, we
9405     // should assume we're changing V2's element's place and behave
9406     // accordingly.
9407     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9408     assert(DestIndex <= INT32_MAX && "truncated destination index");
9409     if (FromV1 == FromV2 &&
9410         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9411       From = V2;
9412       To = V1;
9413       DestIndex =
9414           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9415     }
9416   } else {
9417     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9418            "More than one element from V1 and from V2, or no elements from one "
9419            "of the vectors. This case should not have returned true from "
9420            "isINSERTPSMask");
9421     From = V2;
9422     To = V1;
9423     DestIndex =
9424         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9425   }
9426
9427   // Get an index into the source vector in the range [0,4) (the mask is
9428   // in the range [0,8) because it can address V1 and V2)
9429   unsigned SrcIndex = Mask[DestIndex] % 4;
9430   if (MayFoldLoad(From)) {
9431     // Trivial case, when From comes from a load and is only used by the
9432     // shuffle. Make it use insertps from the vector that we need from that
9433     // load.
9434     SDValue NewLoad =
9435         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9436     if (!NewLoad.getNode())
9437       return SDValue();
9438
9439     if (EVT == MVT::f32) {
9440       // Create this as a scalar to vector to match the instruction pattern.
9441       SDValue LoadScalarToVector =
9442           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9443       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9444       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9445                          InsertpsMask);
9446     } else { // EVT == MVT::i32
9447       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9448       // instruction, to match the PINSRD instruction, which loads an i32 to a
9449       // certain vector element.
9450       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9451                          DAG.getConstant(DestIndex, MVT::i32));
9452     }
9453   }
9454
9455   // Vector-element-to-vector
9456   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9457   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9458 }
9459
9460 // Reduce a vector shuffle to zext.
9461 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9462                                     SelectionDAG &DAG) {
9463   // PMOVZX is only available from SSE41.
9464   if (!Subtarget->hasSSE41())
9465     return SDValue();
9466
9467   MVT VT = Op.getSimpleValueType();
9468
9469   // Only AVX2 support 256-bit vector integer extending.
9470   if (!Subtarget->hasInt256() && VT.is256BitVector())
9471     return SDValue();
9472
9473   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9474   SDLoc DL(Op);
9475   SDValue V1 = Op.getOperand(0);
9476   SDValue V2 = Op.getOperand(1);
9477   unsigned NumElems = VT.getVectorNumElements();
9478
9479   // Extending is an unary operation and the element type of the source vector
9480   // won't be equal to or larger than i64.
9481   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9482       VT.getVectorElementType() == MVT::i64)
9483     return SDValue();
9484
9485   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9486   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9487   while ((1U << Shift) < NumElems) {
9488     if (SVOp->getMaskElt(1U << Shift) == 1)
9489       break;
9490     Shift += 1;
9491     // The maximal ratio is 8, i.e. from i8 to i64.
9492     if (Shift > 3)
9493       return SDValue();
9494   }
9495
9496   // Check the shuffle mask.
9497   unsigned Mask = (1U << Shift) - 1;
9498   for (unsigned i = 0; i != NumElems; ++i) {
9499     int EltIdx = SVOp->getMaskElt(i);
9500     if ((i & Mask) != 0 && EltIdx != -1)
9501       return SDValue();
9502     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9503       return SDValue();
9504   }
9505
9506   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9507   MVT NeVT = MVT::getIntegerVT(NBits);
9508   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9509
9510   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9511     return SDValue();
9512
9513   // Simplify the operand as it's prepared to be fed into shuffle.
9514   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9515   if (V1.getOpcode() == ISD::BITCAST &&
9516       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9517       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9518       V1.getOperand(0).getOperand(0)
9519         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9520     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9521     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9522     ConstantSDNode *CIdx =
9523       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9524     // If it's foldable, i.e. normal load with single use, we will let code
9525     // selection to fold it. Otherwise, we will short the conversion sequence.
9526     if (CIdx && CIdx->getZExtValue() == 0 &&
9527         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9528       MVT FullVT = V.getSimpleValueType();
9529       MVT V1VT = V1.getSimpleValueType();
9530       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9531         // The "ext_vec_elt" node is wider than the result node.
9532         // In this case we should extract subvector from V.
9533         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9534         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9535         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9536                                         FullVT.getVectorNumElements()/Ratio);
9537         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9538                         DAG.getIntPtrConstant(0));
9539       }
9540       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9541     }
9542   }
9543
9544   return DAG.getNode(ISD::BITCAST, DL, VT,
9545                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9546 }
9547
9548 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9549                                       SelectionDAG &DAG) {
9550   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9551   MVT VT = Op.getSimpleValueType();
9552   SDLoc dl(Op);
9553   SDValue V1 = Op.getOperand(0);
9554   SDValue V2 = Op.getOperand(1);
9555
9556   if (isZeroShuffle(SVOp))
9557     return getZeroVector(VT, Subtarget, DAG, dl);
9558
9559   // Handle splat operations
9560   if (SVOp->isSplat()) {
9561     // Use vbroadcast whenever the splat comes from a foldable load
9562     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9563     if (Broadcast.getNode())
9564       return Broadcast;
9565   }
9566
9567   // Check integer expanding shuffles.
9568   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9569   if (NewOp.getNode())
9570     return NewOp;
9571
9572   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9573   // do it!
9574   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9575       VT == MVT::v32i8) {
9576     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9577     if (NewOp.getNode())
9578       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9579   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9580     // FIXME: Figure out a cleaner way to do this.
9581     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9582       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9583       if (NewOp.getNode()) {
9584         MVT NewVT = NewOp.getSimpleValueType();
9585         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9586                                NewVT, true, false))
9587           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9588                               dl);
9589       }
9590     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9591       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9592       if (NewOp.getNode()) {
9593         MVT NewVT = NewOp.getSimpleValueType();
9594         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9595           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9596                               dl);
9597       }
9598     }
9599   }
9600   return SDValue();
9601 }
9602
9603 SDValue
9604 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9605   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9606   SDValue V1 = Op.getOperand(0);
9607   SDValue V2 = Op.getOperand(1);
9608   MVT VT = Op.getSimpleValueType();
9609   SDLoc dl(Op);
9610   unsigned NumElems = VT.getVectorNumElements();
9611   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9612   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9613   bool V1IsSplat = false;
9614   bool V2IsSplat = false;
9615   bool HasSSE2 = Subtarget->hasSSE2();
9616   bool HasFp256    = Subtarget->hasFp256();
9617   bool HasInt256   = Subtarget->hasInt256();
9618   MachineFunction &MF = DAG.getMachineFunction();
9619   bool OptForSize = MF.getFunction()->getAttributes().
9620     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9621
9622   // Check if we should use the experimental vector shuffle lowering. If so,
9623   // delegate completely to that code path.
9624   if (ExperimentalVectorShuffleLowering)
9625     return lowerVectorShuffle(Op, Subtarget, DAG);
9626
9627   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9628
9629   if (V1IsUndef && V2IsUndef)
9630     return DAG.getUNDEF(VT);
9631
9632   // When we create a shuffle node we put the UNDEF node to second operand,
9633   // but in some cases the first operand may be transformed to UNDEF.
9634   // In this case we should just commute the node.
9635   if (V1IsUndef)
9636     return DAG.getCommutedVectorShuffle(*SVOp);
9637
9638   // Vector shuffle lowering takes 3 steps:
9639   //
9640   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9641   //    narrowing and commutation of operands should be handled.
9642   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9643   //    shuffle nodes.
9644   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9645   //    so the shuffle can be broken into other shuffles and the legalizer can
9646   //    try the lowering again.
9647   //
9648   // The general idea is that no vector_shuffle operation should be left to
9649   // be matched during isel, all of them must be converted to a target specific
9650   // node here.
9651
9652   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9653   // narrowing and commutation of operands should be handled. The actual code
9654   // doesn't include all of those, work in progress...
9655   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9656   if (NewOp.getNode())
9657     return NewOp;
9658
9659   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9660
9661   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9662   // unpckh_undef). Only use pshufd if speed is more important than size.
9663   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9664     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9665   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9666     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9667
9668   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9669       V2IsUndef && MayFoldVectorLoad(V1))
9670     return getMOVDDup(Op, dl, V1, DAG);
9671
9672   if (isMOVHLPS_v_undef_Mask(M, VT))
9673     return getMOVHighToLow(Op, dl, DAG);
9674
9675   // Use to match splats
9676   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9677       (VT == MVT::v2f64 || VT == MVT::v2i64))
9678     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9679
9680   if (isPSHUFDMask(M, VT)) {
9681     // The actual implementation will match the mask in the if above and then
9682     // during isel it can match several different instructions, not only pshufd
9683     // as its name says, sad but true, emulate the behavior for now...
9684     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9685       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9686
9687     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9688
9689     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9690       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9691
9692     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9693       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9694                                   DAG);
9695
9696     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9697                                 TargetMask, DAG);
9698   }
9699
9700   if (isPALIGNRMask(M, VT, Subtarget))
9701     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9702                                 getShufflePALIGNRImmediate(SVOp),
9703                                 DAG);
9704
9705   if (isVALIGNMask(M, VT, Subtarget))
9706     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
9707                                 getShuffleVALIGNImmediate(SVOp),
9708                                 DAG);
9709
9710   // Check if this can be converted into a logical shift.
9711   bool isLeft = false;
9712   unsigned ShAmt = 0;
9713   SDValue ShVal;
9714   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9715   if (isShift && ShVal.hasOneUse()) {
9716     // If the shifted value has multiple uses, it may be cheaper to use
9717     // v_set0 + movlhps or movhlps, etc.
9718     MVT EltVT = VT.getVectorElementType();
9719     ShAmt *= EltVT.getSizeInBits();
9720     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9721   }
9722
9723   if (isMOVLMask(M, VT)) {
9724     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9725       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9726     if (!isMOVLPMask(M, VT)) {
9727       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9728         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9729
9730       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9731         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9732     }
9733   }
9734
9735   // FIXME: fold these into legal mask.
9736   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9737     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9738
9739   if (isMOVHLPSMask(M, VT))
9740     return getMOVHighToLow(Op, dl, DAG);
9741
9742   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9743     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9744
9745   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9746     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9747
9748   if (isMOVLPMask(M, VT))
9749     return getMOVLP(Op, dl, DAG, HasSSE2);
9750
9751   if (ShouldXformToMOVHLPS(M, VT) ||
9752       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9753     return DAG.getCommutedVectorShuffle(*SVOp);
9754
9755   if (isShift) {
9756     // No better options. Use a vshldq / vsrldq.
9757     MVT EltVT = VT.getVectorElementType();
9758     ShAmt *= EltVT.getSizeInBits();
9759     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9760   }
9761
9762   bool Commuted = false;
9763   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9764   // 1,1,1,1 -> v8i16 though.
9765   BitVector UndefElements;
9766   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9767     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9768       V1IsSplat = true;
9769   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9770     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9771       V2IsSplat = true;
9772
9773   // Canonicalize the splat or undef, if present, to be on the RHS.
9774   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9775     CommuteVectorShuffleMask(M, NumElems);
9776     std::swap(V1, V2);
9777     std::swap(V1IsSplat, V2IsSplat);
9778     Commuted = true;
9779   }
9780
9781   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9782     // Shuffling low element of v1 into undef, just return v1.
9783     if (V2IsUndef)
9784       return V1;
9785     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9786     // the instruction selector will not match, so get a canonical MOVL with
9787     // swapped operands to undo the commute.
9788     return getMOVL(DAG, dl, VT, V2, V1);
9789   }
9790
9791   if (isUNPCKLMask(M, VT, HasInt256))
9792     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9793
9794   if (isUNPCKHMask(M, VT, HasInt256))
9795     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9796
9797   if (V2IsSplat) {
9798     // Normalize mask so all entries that point to V2 points to its first
9799     // element then try to match unpck{h|l} again. If match, return a
9800     // new vector_shuffle with the corrected mask.p
9801     SmallVector<int, 8> NewMask(M.begin(), M.end());
9802     NormalizeMask(NewMask, NumElems);
9803     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9804       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9805     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9806       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9807   }
9808
9809   if (Commuted) {
9810     // Commute is back and try unpck* again.
9811     // FIXME: this seems wrong.
9812     CommuteVectorShuffleMask(M, NumElems);
9813     std::swap(V1, V2);
9814     std::swap(V1IsSplat, V2IsSplat);
9815
9816     if (isUNPCKLMask(M, VT, HasInt256))
9817       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9818
9819     if (isUNPCKHMask(M, VT, HasInt256))
9820       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9821   }
9822
9823   // Normalize the node to match x86 shuffle ops if needed
9824   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9825     return DAG.getCommutedVectorShuffle(*SVOp);
9826
9827   // The checks below are all present in isShuffleMaskLegal, but they are
9828   // inlined here right now to enable us to directly emit target specific
9829   // nodes, and remove one by one until they don't return Op anymore.
9830
9831   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9832       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9833     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9834       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9835   }
9836
9837   if (isPSHUFHWMask(M, VT, HasInt256))
9838     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9839                                 getShufflePSHUFHWImmediate(SVOp),
9840                                 DAG);
9841
9842   if (isPSHUFLWMask(M, VT, HasInt256))
9843     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9844                                 getShufflePSHUFLWImmediate(SVOp),
9845                                 DAG);
9846
9847   unsigned MaskValue;
9848   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9849                   &MaskValue))
9850     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9851
9852   if (isSHUFPMask(M, VT))
9853     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9854                                 getShuffleSHUFImmediate(SVOp), DAG);
9855
9856   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9857     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9858   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9859     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9860
9861   //===--------------------------------------------------------------------===//
9862   // Generate target specific nodes for 128 or 256-bit shuffles only
9863   // supported in the AVX instruction set.
9864   //
9865
9866   // Handle VMOVDDUPY permutations
9867   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9868     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9869
9870   // Handle VPERMILPS/D* permutations
9871   if (isVPERMILPMask(M, VT)) {
9872     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9873       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9874                                   getShuffleSHUFImmediate(SVOp), DAG);
9875     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9876                                 getShuffleSHUFImmediate(SVOp), DAG);
9877   }
9878
9879   unsigned Idx;
9880   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9881     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9882                               Idx*(NumElems/2), DAG, dl);
9883
9884   // Handle VPERM2F128/VPERM2I128 permutations
9885   if (isVPERM2X128Mask(M, VT, HasFp256))
9886     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9887                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9888
9889   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9890     return getINSERTPS(SVOp, dl, DAG);
9891
9892   unsigned Imm8;
9893   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9894     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9895
9896   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9897       VT.is512BitVector()) {
9898     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9899     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9900     SmallVector<SDValue, 16> permclMask;
9901     for (unsigned i = 0; i != NumElems; ++i) {
9902       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9903     }
9904
9905     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9906     if (V2IsUndef)
9907       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9908       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9909                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9910     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9911                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9912   }
9913
9914   //===--------------------------------------------------------------------===//
9915   // Since no target specific shuffle was selected for this generic one,
9916   // lower it into other known shuffles. FIXME: this isn't true yet, but
9917   // this is the plan.
9918   //
9919
9920   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9921   if (VT == MVT::v8i16) {
9922     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9923     if (NewOp.getNode())
9924       return NewOp;
9925   }
9926
9927   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9928     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9929     if (NewOp.getNode())
9930       return NewOp;
9931   }
9932
9933   if (VT == MVT::v16i8) {
9934     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9935     if (NewOp.getNode())
9936       return NewOp;
9937   }
9938
9939   if (VT == MVT::v32i8) {
9940     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9941     if (NewOp.getNode())
9942       return NewOp;
9943   }
9944
9945   // Handle all 128-bit wide vectors with 4 elements, and match them with
9946   // several different shuffle types.
9947   if (NumElems == 4 && VT.is128BitVector())
9948     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9949
9950   // Handle general 256-bit shuffles
9951   if (VT.is256BitVector())
9952     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9953
9954   return SDValue();
9955 }
9956
9957 // This function assumes its argument is a BUILD_VECTOR of constants or
9958 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9959 // true.
9960 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9961                                     unsigned &MaskValue) {
9962   MaskValue = 0;
9963   unsigned NumElems = BuildVector->getNumOperands();
9964   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9965   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9966   unsigned NumElemsInLane = NumElems / NumLanes;
9967
9968   // Blend for v16i16 should be symetric for the both lanes.
9969   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9970     SDValue EltCond = BuildVector->getOperand(i);
9971     SDValue SndLaneEltCond =
9972         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9973
9974     int Lane1Cond = -1, Lane2Cond = -1;
9975     if (isa<ConstantSDNode>(EltCond))
9976       Lane1Cond = !isZero(EltCond);
9977     if (isa<ConstantSDNode>(SndLaneEltCond))
9978       Lane2Cond = !isZero(SndLaneEltCond);
9979
9980     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9981       // Lane1Cond != 0, means we want the first argument.
9982       // Lane1Cond == 0, means we want the second argument.
9983       // The encoding of this argument is 0 for the first argument, 1
9984       // for the second. Therefore, invert the condition.
9985       MaskValue |= !Lane1Cond << i;
9986     else if (Lane1Cond < 0)
9987       MaskValue |= !Lane2Cond << i;
9988     else
9989       return false;
9990   }
9991   return true;
9992 }
9993
9994 // Try to lower a vselect node into a simple blend instruction.
9995 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9996                                    SelectionDAG &DAG) {
9997   SDValue Cond = Op.getOperand(0);
9998   SDValue LHS = Op.getOperand(1);
9999   SDValue RHS = Op.getOperand(2);
10000   SDLoc dl(Op);
10001   MVT VT = Op.getSimpleValueType();
10002   MVT EltVT = VT.getVectorElementType();
10003   unsigned NumElems = VT.getVectorNumElements();
10004
10005   // There is no blend with immediate in AVX-512.
10006   if (VT.is512BitVector())
10007     return SDValue();
10008
10009   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10010     return SDValue();
10011   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10012     return SDValue();
10013
10014   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10015     return SDValue();
10016
10017   // Check the mask for BLEND and build the value.
10018   unsigned MaskValue = 0;
10019   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10020     return SDValue();
10021
10022   // Convert i32 vectors to floating point if it is not AVX2.
10023   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10024   MVT BlendVT = VT;
10025   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10026     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10027                                NumElems);
10028     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10029     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10030   }
10031
10032   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10033                             DAG.getConstant(MaskValue, MVT::i32));
10034   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10035 }
10036
10037 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10038   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10039   if (BlendOp.getNode())
10040     return BlendOp;
10041
10042   // Some types for vselect were previously set to Expand, not Legal or
10043   // Custom. Return an empty SDValue so we fall-through to Expand, after
10044   // the Custom lowering phase.
10045   MVT VT = Op.getSimpleValueType();
10046   switch (VT.SimpleTy) {
10047   default:
10048     break;
10049   case MVT::v8i16:
10050   case MVT::v16i16:
10051     return SDValue();
10052   }
10053
10054   // We couldn't create a "Blend with immediate" node.
10055   // This node should still be legal, but we'll have to emit a blendv*
10056   // instruction.
10057   return Op;
10058 }
10059
10060 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10061   MVT VT = Op.getSimpleValueType();
10062   SDLoc dl(Op);
10063
10064   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10065     return SDValue();
10066
10067   if (VT.getSizeInBits() == 8) {
10068     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10069                                   Op.getOperand(0), Op.getOperand(1));
10070     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10071                                   DAG.getValueType(VT));
10072     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10073   }
10074
10075   if (VT.getSizeInBits() == 16) {
10076     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10077     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10078     if (Idx == 0)
10079       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10080                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10081                                      DAG.getNode(ISD::BITCAST, dl,
10082                                                  MVT::v4i32,
10083                                                  Op.getOperand(0)),
10084                                      Op.getOperand(1)));
10085     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10086                                   Op.getOperand(0), Op.getOperand(1));
10087     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10088                                   DAG.getValueType(VT));
10089     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10090   }
10091
10092   if (VT == MVT::f32) {
10093     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10094     // the result back to FR32 register. It's only worth matching if the
10095     // result has a single use which is a store or a bitcast to i32.  And in
10096     // the case of a store, it's not worth it if the index is a constant 0,
10097     // because a MOVSSmr can be used instead, which is smaller and faster.
10098     if (!Op.hasOneUse())
10099       return SDValue();
10100     SDNode *User = *Op.getNode()->use_begin();
10101     if ((User->getOpcode() != ISD::STORE ||
10102          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10103           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10104         (User->getOpcode() != ISD::BITCAST ||
10105          User->getValueType(0) != MVT::i32))
10106       return SDValue();
10107     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10108                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10109                                               Op.getOperand(0)),
10110                                               Op.getOperand(1));
10111     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10112   }
10113
10114   if (VT == MVT::i32 || VT == MVT::i64) {
10115     // ExtractPS/pextrq works with constant index.
10116     if (isa<ConstantSDNode>(Op.getOperand(1)))
10117       return Op;
10118   }
10119   return SDValue();
10120 }
10121
10122 /// Extract one bit from mask vector, like v16i1 or v8i1.
10123 /// AVX-512 feature.
10124 SDValue
10125 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10126   SDValue Vec = Op.getOperand(0);
10127   SDLoc dl(Vec);
10128   MVT VecVT = Vec.getSimpleValueType();
10129   SDValue Idx = Op.getOperand(1);
10130   MVT EltVT = Op.getSimpleValueType();
10131
10132   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10133
10134   // variable index can't be handled in mask registers,
10135   // extend vector to VR512
10136   if (!isa<ConstantSDNode>(Idx)) {
10137     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10138     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10139     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10140                               ExtVT.getVectorElementType(), Ext, Idx);
10141     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10142   }
10143
10144   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10145   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10146   unsigned MaxSift = rc->getSize()*8 - 1;
10147   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10148                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10149   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10150                     DAG.getConstant(MaxSift, MVT::i8));
10151   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10152                        DAG.getIntPtrConstant(0));
10153 }
10154
10155 SDValue
10156 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10157                                            SelectionDAG &DAG) const {
10158   SDLoc dl(Op);
10159   SDValue Vec = Op.getOperand(0);
10160   MVT VecVT = Vec.getSimpleValueType();
10161   SDValue Idx = Op.getOperand(1);
10162
10163   if (Op.getSimpleValueType() == MVT::i1)
10164     return ExtractBitFromMaskVector(Op, DAG);
10165
10166   if (!isa<ConstantSDNode>(Idx)) {
10167     if (VecVT.is512BitVector() ||
10168         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10169          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10170
10171       MVT MaskEltVT =
10172         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10173       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10174                                     MaskEltVT.getSizeInBits());
10175
10176       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10177       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10178                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10179                                 Idx, DAG.getConstant(0, getPointerTy()));
10180       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10181       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10182                         Perm, DAG.getConstant(0, getPointerTy()));
10183     }
10184     return SDValue();
10185   }
10186
10187   // If this is a 256-bit vector result, first extract the 128-bit vector and
10188   // then extract the element from the 128-bit vector.
10189   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10190
10191     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10192     // Get the 128-bit vector.
10193     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10194     MVT EltVT = VecVT.getVectorElementType();
10195
10196     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10197
10198     //if (IdxVal >= NumElems/2)
10199     //  IdxVal -= NumElems/2;
10200     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10201     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10202                        DAG.getConstant(IdxVal, MVT::i32));
10203   }
10204
10205   assert(VecVT.is128BitVector() && "Unexpected vector length");
10206
10207   if (Subtarget->hasSSE41()) {
10208     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10209     if (Res.getNode())
10210       return Res;
10211   }
10212
10213   MVT VT = Op.getSimpleValueType();
10214   // TODO: handle v16i8.
10215   if (VT.getSizeInBits() == 16) {
10216     SDValue Vec = Op.getOperand(0);
10217     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10218     if (Idx == 0)
10219       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10220                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10221                                      DAG.getNode(ISD::BITCAST, dl,
10222                                                  MVT::v4i32, Vec),
10223                                      Op.getOperand(1)));
10224     // Transform it so it match pextrw which produces a 32-bit result.
10225     MVT EltVT = MVT::i32;
10226     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10227                                   Op.getOperand(0), Op.getOperand(1));
10228     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10229                                   DAG.getValueType(VT));
10230     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10231   }
10232
10233   if (VT.getSizeInBits() == 32) {
10234     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10235     if (Idx == 0)
10236       return Op;
10237
10238     // SHUFPS the element to the lowest double word, then movss.
10239     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10240     MVT VVT = Op.getOperand(0).getSimpleValueType();
10241     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10242                                        DAG.getUNDEF(VVT), Mask);
10243     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10244                        DAG.getIntPtrConstant(0));
10245   }
10246
10247   if (VT.getSizeInBits() == 64) {
10248     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10249     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10250     //        to match extract_elt for f64.
10251     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10252     if (Idx == 0)
10253       return Op;
10254
10255     // UNPCKHPD the element to the lowest double word, then movsd.
10256     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10257     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10258     int Mask[2] = { 1, -1 };
10259     MVT VVT = Op.getOperand(0).getSimpleValueType();
10260     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10261                                        DAG.getUNDEF(VVT), Mask);
10262     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10263                        DAG.getIntPtrConstant(0));
10264   }
10265
10266   return SDValue();
10267 }
10268
10269 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10270   MVT VT = Op.getSimpleValueType();
10271   MVT EltVT = VT.getVectorElementType();
10272   SDLoc dl(Op);
10273
10274   SDValue N0 = Op.getOperand(0);
10275   SDValue N1 = Op.getOperand(1);
10276   SDValue N2 = Op.getOperand(2);
10277
10278   if (!VT.is128BitVector())
10279     return SDValue();
10280
10281   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
10282       isa<ConstantSDNode>(N2)) {
10283     unsigned Opc;
10284     if (VT == MVT::v8i16)
10285       Opc = X86ISD::PINSRW;
10286     else if (VT == MVT::v16i8)
10287       Opc = X86ISD::PINSRB;
10288     else
10289       Opc = X86ISD::PINSRB;
10290
10291     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10292     // argument.
10293     if (N1.getValueType() != MVT::i32)
10294       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10295     if (N2.getValueType() != MVT::i32)
10296       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10297     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10298   }
10299
10300   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
10301     // Bits [7:6] of the constant are the source select.  This will always be
10302     //  zero here.  The DAG Combiner may combine an extract_elt index into these
10303     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
10304     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10305     // Bits [5:4] of the constant are the destination select.  This is the
10306     //  value of the incoming immediate.
10307     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10308     //   combine either bitwise AND or insert of float 0.0 to set these bits.
10309     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10310     // Create this as a scalar to vector..
10311     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10312     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10313   }
10314
10315   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10316     // PINSR* works with constant index.
10317     return Op;
10318   }
10319   return SDValue();
10320 }
10321
10322 /// Insert one bit to mask vector, like v16i1 or v8i1.
10323 /// AVX-512 feature.
10324 SDValue 
10325 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10326   SDLoc dl(Op);
10327   SDValue Vec = Op.getOperand(0);
10328   SDValue Elt = Op.getOperand(1);
10329   SDValue Idx = Op.getOperand(2);
10330   MVT VecVT = Vec.getSimpleValueType();
10331
10332   if (!isa<ConstantSDNode>(Idx)) {
10333     // Non constant index. Extend source and destination,
10334     // insert element and then truncate the result.
10335     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10336     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10337     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10338       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10339       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10340     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10341   }
10342
10343   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10344   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10345   if (Vec.getOpcode() == ISD::UNDEF)
10346     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10347                        DAG.getConstant(IdxVal, MVT::i8));
10348   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10349   unsigned MaxSift = rc->getSize()*8 - 1;
10350   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10351                     DAG.getConstant(MaxSift, MVT::i8));
10352   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10353                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10354   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10355 }
10356 SDValue
10357 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10358   MVT VT = Op.getSimpleValueType();
10359   MVT EltVT = VT.getVectorElementType();
10360   
10361   if (EltVT == MVT::i1)
10362     return InsertBitToMaskVector(Op, DAG);
10363
10364   SDLoc dl(Op);
10365   SDValue N0 = Op.getOperand(0);
10366   SDValue N1 = Op.getOperand(1);
10367   SDValue N2 = Op.getOperand(2);
10368
10369   // If this is a 256-bit vector result, first extract the 128-bit vector,
10370   // insert the element into the extracted half and then place it back.
10371   if (VT.is256BitVector() || VT.is512BitVector()) {
10372     if (!isa<ConstantSDNode>(N2))
10373       return SDValue();
10374
10375     // Get the desired 128-bit vector half.
10376     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10377     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10378
10379     // Insert the element into the desired half.
10380     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10381     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10382
10383     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10384                     DAG.getConstant(IdxIn128, MVT::i32));
10385
10386     // Insert the changed part back to the 256-bit vector
10387     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10388   }
10389
10390   if (Subtarget->hasSSE41())
10391     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10392
10393   if (EltVT == MVT::i8)
10394     return SDValue();
10395
10396   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10397     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10398     // as its second argument.
10399     if (N1.getValueType() != MVT::i32)
10400       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10401     if (N2.getValueType() != MVT::i32)
10402       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10403     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10404   }
10405   return SDValue();
10406 }
10407
10408 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10409   SDLoc dl(Op);
10410   MVT OpVT = Op.getSimpleValueType();
10411
10412   // If this is a 256-bit vector result, first insert into a 128-bit
10413   // vector and then insert into the 256-bit vector.
10414   if (!OpVT.is128BitVector()) {
10415     // Insert into a 128-bit vector.
10416     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10417     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10418                                  OpVT.getVectorNumElements() / SizeFactor);
10419
10420     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10421
10422     // Insert the 128-bit vector.
10423     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10424   }
10425
10426   if (OpVT == MVT::v1i64 &&
10427       Op.getOperand(0).getValueType() == MVT::i64)
10428     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10429
10430   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10431   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10432   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10433                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10434 }
10435
10436 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10437 // a simple subregister reference or explicit instructions to grab
10438 // upper bits of a vector.
10439 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10440                                       SelectionDAG &DAG) {
10441   SDLoc dl(Op);
10442   SDValue In =  Op.getOperand(0);
10443   SDValue Idx = Op.getOperand(1);
10444   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10445   MVT ResVT   = Op.getSimpleValueType();
10446   MVT InVT    = In.getSimpleValueType();
10447
10448   if (Subtarget->hasFp256()) {
10449     if (ResVT.is128BitVector() &&
10450         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10451         isa<ConstantSDNode>(Idx)) {
10452       return Extract128BitVector(In, IdxVal, DAG, dl);
10453     }
10454     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10455         isa<ConstantSDNode>(Idx)) {
10456       return Extract256BitVector(In, IdxVal, DAG, dl);
10457     }
10458   }
10459   return SDValue();
10460 }
10461
10462 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10463 // simple superregister reference or explicit instructions to insert
10464 // the upper bits of a vector.
10465 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10466                                      SelectionDAG &DAG) {
10467   if (Subtarget->hasFp256()) {
10468     SDLoc dl(Op.getNode());
10469     SDValue Vec = Op.getNode()->getOperand(0);
10470     SDValue SubVec = Op.getNode()->getOperand(1);
10471     SDValue Idx = Op.getNode()->getOperand(2);
10472
10473     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10474          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10475         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10476         isa<ConstantSDNode>(Idx)) {
10477       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10478       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10479     }
10480
10481     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10482         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10483         isa<ConstantSDNode>(Idx)) {
10484       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10485       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10486     }
10487   }
10488   return SDValue();
10489 }
10490
10491 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10492 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10493 // one of the above mentioned nodes. It has to be wrapped because otherwise
10494 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10495 // be used to form addressing mode. These wrapped nodes will be selected
10496 // into MOV32ri.
10497 SDValue
10498 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10499   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10500
10501   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10502   // global base reg.
10503   unsigned char OpFlag = 0;
10504   unsigned WrapperKind = X86ISD::Wrapper;
10505   CodeModel::Model M = DAG.getTarget().getCodeModel();
10506
10507   if (Subtarget->isPICStyleRIPRel() &&
10508       (M == CodeModel::Small || M == CodeModel::Kernel))
10509     WrapperKind = X86ISD::WrapperRIP;
10510   else if (Subtarget->isPICStyleGOT())
10511     OpFlag = X86II::MO_GOTOFF;
10512   else if (Subtarget->isPICStyleStubPIC())
10513     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10514
10515   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10516                                              CP->getAlignment(),
10517                                              CP->getOffset(), OpFlag);
10518   SDLoc DL(CP);
10519   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10520   // With PIC, the address is actually $g + Offset.
10521   if (OpFlag) {
10522     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10523                          DAG.getNode(X86ISD::GlobalBaseReg,
10524                                      SDLoc(), getPointerTy()),
10525                          Result);
10526   }
10527
10528   return Result;
10529 }
10530
10531 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10532   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10533
10534   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10535   // global base reg.
10536   unsigned char OpFlag = 0;
10537   unsigned WrapperKind = X86ISD::Wrapper;
10538   CodeModel::Model M = DAG.getTarget().getCodeModel();
10539
10540   if (Subtarget->isPICStyleRIPRel() &&
10541       (M == CodeModel::Small || M == CodeModel::Kernel))
10542     WrapperKind = X86ISD::WrapperRIP;
10543   else if (Subtarget->isPICStyleGOT())
10544     OpFlag = X86II::MO_GOTOFF;
10545   else if (Subtarget->isPICStyleStubPIC())
10546     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10547
10548   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10549                                           OpFlag);
10550   SDLoc DL(JT);
10551   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10552
10553   // With PIC, the address is actually $g + Offset.
10554   if (OpFlag)
10555     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10556                          DAG.getNode(X86ISD::GlobalBaseReg,
10557                                      SDLoc(), getPointerTy()),
10558                          Result);
10559
10560   return Result;
10561 }
10562
10563 SDValue
10564 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10565   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10566
10567   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10568   // global base reg.
10569   unsigned char OpFlag = 0;
10570   unsigned WrapperKind = X86ISD::Wrapper;
10571   CodeModel::Model M = DAG.getTarget().getCodeModel();
10572
10573   if (Subtarget->isPICStyleRIPRel() &&
10574       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10575     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10576       OpFlag = X86II::MO_GOTPCREL;
10577     WrapperKind = X86ISD::WrapperRIP;
10578   } else if (Subtarget->isPICStyleGOT()) {
10579     OpFlag = X86II::MO_GOT;
10580   } else if (Subtarget->isPICStyleStubPIC()) {
10581     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10582   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10583     OpFlag = X86II::MO_DARWIN_NONLAZY;
10584   }
10585
10586   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10587
10588   SDLoc DL(Op);
10589   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10590
10591   // With PIC, the address is actually $g + Offset.
10592   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10593       !Subtarget->is64Bit()) {
10594     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10595                          DAG.getNode(X86ISD::GlobalBaseReg,
10596                                      SDLoc(), getPointerTy()),
10597                          Result);
10598   }
10599
10600   // For symbols that require a load from a stub to get the address, emit the
10601   // load.
10602   if (isGlobalStubReference(OpFlag))
10603     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10604                          MachinePointerInfo::getGOT(), false, false, false, 0);
10605
10606   return Result;
10607 }
10608
10609 SDValue
10610 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10611   // Create the TargetBlockAddressAddress node.
10612   unsigned char OpFlags =
10613     Subtarget->ClassifyBlockAddressReference();
10614   CodeModel::Model M = DAG.getTarget().getCodeModel();
10615   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10616   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10617   SDLoc dl(Op);
10618   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10619                                              OpFlags);
10620
10621   if (Subtarget->isPICStyleRIPRel() &&
10622       (M == CodeModel::Small || M == CodeModel::Kernel))
10623     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10624   else
10625     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10626
10627   // With PIC, the address is actually $g + Offset.
10628   if (isGlobalRelativeToPICBase(OpFlags)) {
10629     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10630                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10631                          Result);
10632   }
10633
10634   return Result;
10635 }
10636
10637 SDValue
10638 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10639                                       int64_t Offset, SelectionDAG &DAG) const {
10640   // Create the TargetGlobalAddress node, folding in the constant
10641   // offset if it is legal.
10642   unsigned char OpFlags =
10643       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10644   CodeModel::Model M = DAG.getTarget().getCodeModel();
10645   SDValue Result;
10646   if (OpFlags == X86II::MO_NO_FLAG &&
10647       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10648     // A direct static reference to a global.
10649     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10650     Offset = 0;
10651   } else {
10652     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10653   }
10654
10655   if (Subtarget->isPICStyleRIPRel() &&
10656       (M == CodeModel::Small || M == CodeModel::Kernel))
10657     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10658   else
10659     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10660
10661   // With PIC, the address is actually $g + Offset.
10662   if (isGlobalRelativeToPICBase(OpFlags)) {
10663     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10664                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10665                          Result);
10666   }
10667
10668   // For globals that require a load from a stub to get the address, emit the
10669   // load.
10670   if (isGlobalStubReference(OpFlags))
10671     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10672                          MachinePointerInfo::getGOT(), false, false, false, 0);
10673
10674   // If there was a non-zero offset that we didn't fold, create an explicit
10675   // addition for it.
10676   if (Offset != 0)
10677     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10678                          DAG.getConstant(Offset, getPointerTy()));
10679
10680   return Result;
10681 }
10682
10683 SDValue
10684 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10685   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10686   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10687   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10688 }
10689
10690 static SDValue
10691 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10692            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10693            unsigned char OperandFlags, bool LocalDynamic = false) {
10694   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10695   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10696   SDLoc dl(GA);
10697   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10698                                            GA->getValueType(0),
10699                                            GA->getOffset(),
10700                                            OperandFlags);
10701
10702   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10703                                            : X86ISD::TLSADDR;
10704
10705   if (InFlag) {
10706     SDValue Ops[] = { Chain,  TGA, *InFlag };
10707     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10708   } else {
10709     SDValue Ops[]  = { Chain, TGA };
10710     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10711   }
10712
10713   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10714   MFI->setAdjustsStack(true);
10715
10716   SDValue Flag = Chain.getValue(1);
10717   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10718 }
10719
10720 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10721 static SDValue
10722 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10723                                 const EVT PtrVT) {
10724   SDValue InFlag;
10725   SDLoc dl(GA);  // ? function entry point might be better
10726   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10727                                    DAG.getNode(X86ISD::GlobalBaseReg,
10728                                                SDLoc(), PtrVT), InFlag);
10729   InFlag = Chain.getValue(1);
10730
10731   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10732 }
10733
10734 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10735 static SDValue
10736 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10737                                 const EVT PtrVT) {
10738   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10739                     X86::RAX, X86II::MO_TLSGD);
10740 }
10741
10742 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10743                                            SelectionDAG &DAG,
10744                                            const EVT PtrVT,
10745                                            bool is64Bit) {
10746   SDLoc dl(GA);
10747
10748   // Get the start address of the TLS block for this module.
10749   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10750       .getInfo<X86MachineFunctionInfo>();
10751   MFI->incNumLocalDynamicTLSAccesses();
10752
10753   SDValue Base;
10754   if (is64Bit) {
10755     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10756                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10757   } else {
10758     SDValue InFlag;
10759     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10760         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10761     InFlag = Chain.getValue(1);
10762     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10763                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10764   }
10765
10766   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10767   // of Base.
10768
10769   // Build x@dtpoff.
10770   unsigned char OperandFlags = X86II::MO_DTPOFF;
10771   unsigned WrapperKind = X86ISD::Wrapper;
10772   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10773                                            GA->getValueType(0),
10774                                            GA->getOffset(), OperandFlags);
10775   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10776
10777   // Add x@dtpoff with the base.
10778   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10779 }
10780
10781 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10782 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10783                                    const EVT PtrVT, TLSModel::Model model,
10784                                    bool is64Bit, bool isPIC) {
10785   SDLoc dl(GA);
10786
10787   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10788   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10789                                                          is64Bit ? 257 : 256));
10790
10791   SDValue ThreadPointer =
10792       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10793                   MachinePointerInfo(Ptr), false, false, false, 0);
10794
10795   unsigned char OperandFlags = 0;
10796   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10797   // initialexec.
10798   unsigned WrapperKind = X86ISD::Wrapper;
10799   if (model == TLSModel::LocalExec) {
10800     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10801   } else if (model == TLSModel::InitialExec) {
10802     if (is64Bit) {
10803       OperandFlags = X86II::MO_GOTTPOFF;
10804       WrapperKind = X86ISD::WrapperRIP;
10805     } else {
10806       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10807     }
10808   } else {
10809     llvm_unreachable("Unexpected model");
10810   }
10811
10812   // emit "addl x@ntpoff,%eax" (local exec)
10813   // or "addl x@indntpoff,%eax" (initial exec)
10814   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10815   SDValue TGA =
10816       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10817                                  GA->getOffset(), OperandFlags);
10818   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10819
10820   if (model == TLSModel::InitialExec) {
10821     if (isPIC && !is64Bit) {
10822       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10823                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10824                            Offset);
10825     }
10826
10827     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10828                          MachinePointerInfo::getGOT(), false, false, false, 0);
10829   }
10830
10831   // The address of the thread local variable is the add of the thread
10832   // pointer with the offset of the variable.
10833   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10834 }
10835
10836 SDValue
10837 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10838
10839   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10840   const GlobalValue *GV = GA->getGlobal();
10841
10842   if (Subtarget->isTargetELF()) {
10843     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10844
10845     switch (model) {
10846       case TLSModel::GeneralDynamic:
10847         if (Subtarget->is64Bit())
10848           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10849         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10850       case TLSModel::LocalDynamic:
10851         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10852                                            Subtarget->is64Bit());
10853       case TLSModel::InitialExec:
10854       case TLSModel::LocalExec:
10855         return LowerToTLSExecModel(
10856             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10857             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10858     }
10859     llvm_unreachable("Unknown TLS model.");
10860   }
10861
10862   if (Subtarget->isTargetDarwin()) {
10863     // Darwin only has one model of TLS.  Lower to that.
10864     unsigned char OpFlag = 0;
10865     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10866                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10867
10868     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10869     // global base reg.
10870     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10871                  !Subtarget->is64Bit();
10872     if (PIC32)
10873       OpFlag = X86II::MO_TLVP_PIC_BASE;
10874     else
10875       OpFlag = X86II::MO_TLVP;
10876     SDLoc DL(Op);
10877     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10878                                                 GA->getValueType(0),
10879                                                 GA->getOffset(), OpFlag);
10880     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10881
10882     // With PIC32, the address is actually $g + Offset.
10883     if (PIC32)
10884       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10885                            DAG.getNode(X86ISD::GlobalBaseReg,
10886                                        SDLoc(), getPointerTy()),
10887                            Offset);
10888
10889     // Lowering the machine isd will make sure everything is in the right
10890     // location.
10891     SDValue Chain = DAG.getEntryNode();
10892     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10893     SDValue Args[] = { Chain, Offset };
10894     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10895
10896     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10897     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10898     MFI->setAdjustsStack(true);
10899
10900     // And our return value (tls address) is in the standard call return value
10901     // location.
10902     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10903     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10904                               Chain.getValue(1));
10905   }
10906
10907   if (Subtarget->isTargetKnownWindowsMSVC() ||
10908       Subtarget->isTargetWindowsGNU()) {
10909     // Just use the implicit TLS architecture
10910     // Need to generate someting similar to:
10911     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10912     //                                  ; from TEB
10913     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10914     //   mov     rcx, qword [rdx+rcx*8]
10915     //   mov     eax, .tls$:tlsvar
10916     //   [rax+rcx] contains the address
10917     // Windows 64bit: gs:0x58
10918     // Windows 32bit: fs:__tls_array
10919
10920     SDLoc dl(GA);
10921     SDValue Chain = DAG.getEntryNode();
10922
10923     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10924     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10925     // use its literal value of 0x2C.
10926     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10927                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10928                                                              256)
10929                                         : Type::getInt32PtrTy(*DAG.getContext(),
10930                                                               257));
10931
10932     SDValue TlsArray =
10933         Subtarget->is64Bit()
10934             ? DAG.getIntPtrConstant(0x58)
10935             : (Subtarget->isTargetWindowsGNU()
10936                    ? DAG.getIntPtrConstant(0x2C)
10937                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10938
10939     SDValue ThreadPointer =
10940         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10941                     MachinePointerInfo(Ptr), false, false, false, 0);
10942
10943     // Load the _tls_index variable
10944     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10945     if (Subtarget->is64Bit())
10946       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10947                            IDX, MachinePointerInfo(), MVT::i32,
10948                            false, false, false, 0);
10949     else
10950       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10951                         false, false, false, 0);
10952
10953     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10954                                     getPointerTy());
10955     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10956
10957     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10958     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10959                       false, false, false, 0);
10960
10961     // Get the offset of start of .tls section
10962     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10963                                              GA->getValueType(0),
10964                                              GA->getOffset(), X86II::MO_SECREL);
10965     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10966
10967     // The address of the thread local variable is the add of the thread
10968     // pointer with the offset of the variable.
10969     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10970   }
10971
10972   llvm_unreachable("TLS not implemented for this target.");
10973 }
10974
10975 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10976 /// and take a 2 x i32 value to shift plus a shift amount.
10977 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10978   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10979   MVT VT = Op.getSimpleValueType();
10980   unsigned VTBits = VT.getSizeInBits();
10981   SDLoc dl(Op);
10982   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10983   SDValue ShOpLo = Op.getOperand(0);
10984   SDValue ShOpHi = Op.getOperand(1);
10985   SDValue ShAmt  = Op.getOperand(2);
10986   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10987   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10988   // during isel.
10989   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10990                                   DAG.getConstant(VTBits - 1, MVT::i8));
10991   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10992                                      DAG.getConstant(VTBits - 1, MVT::i8))
10993                        : DAG.getConstant(0, VT);
10994
10995   SDValue Tmp2, Tmp3;
10996   if (Op.getOpcode() == ISD::SHL_PARTS) {
10997     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10998     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10999   } else {
11000     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11001     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11002   }
11003
11004   // If the shift amount is larger or equal than the width of a part we can't
11005   // rely on the results of shld/shrd. Insert a test and select the appropriate
11006   // values for large shift amounts.
11007   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11008                                 DAG.getConstant(VTBits, MVT::i8));
11009   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11010                              AndNode, DAG.getConstant(0, MVT::i8));
11011
11012   SDValue Hi, Lo;
11013   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11014   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11015   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11016
11017   if (Op.getOpcode() == ISD::SHL_PARTS) {
11018     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11019     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11020   } else {
11021     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11022     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11023   }
11024
11025   SDValue Ops[2] = { Lo, Hi };
11026   return DAG.getMergeValues(Ops, dl);
11027 }
11028
11029 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11030                                            SelectionDAG &DAG) const {
11031   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11032
11033   if (SrcVT.isVector())
11034     return SDValue();
11035
11036   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11037          "Unknown SINT_TO_FP to lower!");
11038
11039   // These are really Legal; return the operand so the caller accepts it as
11040   // Legal.
11041   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11042     return Op;
11043   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11044       Subtarget->is64Bit()) {
11045     return Op;
11046   }
11047
11048   SDLoc dl(Op);
11049   unsigned Size = SrcVT.getSizeInBits()/8;
11050   MachineFunction &MF = DAG.getMachineFunction();
11051   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11052   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11053   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11054                                StackSlot,
11055                                MachinePointerInfo::getFixedStack(SSFI),
11056                                false, false, 0);
11057   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11058 }
11059
11060 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11061                                      SDValue StackSlot,
11062                                      SelectionDAG &DAG) const {
11063   // Build the FILD
11064   SDLoc DL(Op);
11065   SDVTList Tys;
11066   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11067   if (useSSE)
11068     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11069   else
11070     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11071
11072   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11073
11074   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11075   MachineMemOperand *MMO;
11076   if (FI) {
11077     int SSFI = FI->getIndex();
11078     MMO =
11079       DAG.getMachineFunction()
11080       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11081                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11082   } else {
11083     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11084     StackSlot = StackSlot.getOperand(1);
11085   }
11086   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11087   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11088                                            X86ISD::FILD, DL,
11089                                            Tys, Ops, SrcVT, MMO);
11090
11091   if (useSSE) {
11092     Chain = Result.getValue(1);
11093     SDValue InFlag = Result.getValue(2);
11094
11095     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11096     // shouldn't be necessary except that RFP cannot be live across
11097     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11098     MachineFunction &MF = DAG.getMachineFunction();
11099     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11100     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11101     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11102     Tys = DAG.getVTList(MVT::Other);
11103     SDValue Ops[] = {
11104       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11105     };
11106     MachineMemOperand *MMO =
11107       DAG.getMachineFunction()
11108       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11109                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11110
11111     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11112                                     Ops, Op.getValueType(), MMO);
11113     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11114                          MachinePointerInfo::getFixedStack(SSFI),
11115                          false, false, false, 0);
11116   }
11117
11118   return Result;
11119 }
11120
11121 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11122 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11123                                                SelectionDAG &DAG) const {
11124   // This algorithm is not obvious. Here it is what we're trying to output:
11125   /*
11126      movq       %rax,  %xmm0
11127      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11128      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11129      #ifdef __SSE3__
11130        haddpd   %xmm0, %xmm0
11131      #else
11132        pshufd   $0x4e, %xmm0, %xmm1
11133        addpd    %xmm1, %xmm0
11134      #endif
11135   */
11136
11137   SDLoc dl(Op);
11138   LLVMContext *Context = DAG.getContext();
11139
11140   // Build some magic constants.
11141   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11142   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11143   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11144
11145   SmallVector<Constant*,2> CV1;
11146   CV1.push_back(
11147     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11148                                       APInt(64, 0x4330000000000000ULL))));
11149   CV1.push_back(
11150     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11151                                       APInt(64, 0x4530000000000000ULL))));
11152   Constant *C1 = ConstantVector::get(CV1);
11153   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11154
11155   // Load the 64-bit value into an XMM register.
11156   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11157                             Op.getOperand(0));
11158   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11159                               MachinePointerInfo::getConstantPool(),
11160                               false, false, false, 16);
11161   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11162                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11163                               CLod0);
11164
11165   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11166                               MachinePointerInfo::getConstantPool(),
11167                               false, false, false, 16);
11168   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11169   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11170   SDValue Result;
11171
11172   if (Subtarget->hasSSE3()) {
11173     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11174     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11175   } else {
11176     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11177     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11178                                            S2F, 0x4E, DAG);
11179     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11180                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11181                          Sub);
11182   }
11183
11184   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11185                      DAG.getIntPtrConstant(0));
11186 }
11187
11188 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11189 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11190                                                SelectionDAG &DAG) const {
11191   SDLoc dl(Op);
11192   // FP constant to bias correct the final result.
11193   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11194                                    MVT::f64);
11195
11196   // Load the 32-bit value into an XMM register.
11197   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11198                              Op.getOperand(0));
11199
11200   // Zero out the upper parts of the register.
11201   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11202
11203   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11204                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11205                      DAG.getIntPtrConstant(0));
11206
11207   // Or the load with the bias.
11208   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11209                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11210                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11211                                                    MVT::v2f64, Load)),
11212                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11213                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11214                                                    MVT::v2f64, Bias)));
11215   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11216                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11217                    DAG.getIntPtrConstant(0));
11218
11219   // Subtract the bias.
11220   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11221
11222   // Handle final rounding.
11223   EVT DestVT = Op.getValueType();
11224
11225   if (DestVT.bitsLT(MVT::f64))
11226     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11227                        DAG.getIntPtrConstant(0));
11228   if (DestVT.bitsGT(MVT::f64))
11229     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11230
11231   // Handle final rounding.
11232   return Sub;
11233 }
11234
11235 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11236                                                SelectionDAG &DAG) const {
11237   SDValue N0 = Op.getOperand(0);
11238   MVT SVT = N0.getSimpleValueType();
11239   SDLoc dl(Op);
11240
11241   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11242           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11243          "Custom UINT_TO_FP is not supported!");
11244
11245   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11246   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11247                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11248 }
11249
11250 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11251                                            SelectionDAG &DAG) const {
11252   SDValue N0 = Op.getOperand(0);
11253   SDLoc dl(Op);
11254
11255   if (Op.getValueType().isVector())
11256     return lowerUINT_TO_FP_vec(Op, DAG);
11257
11258   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11259   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11260   // the optimization here.
11261   if (DAG.SignBitIsZero(N0))
11262     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11263
11264   MVT SrcVT = N0.getSimpleValueType();
11265   MVT DstVT = Op.getSimpleValueType();
11266   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11267     return LowerUINT_TO_FP_i64(Op, DAG);
11268   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11269     return LowerUINT_TO_FP_i32(Op, DAG);
11270   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11271     return SDValue();
11272
11273   // Make a 64-bit buffer, and use it to build an FILD.
11274   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11275   if (SrcVT == MVT::i32) {
11276     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11277     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11278                                      getPointerTy(), StackSlot, WordOff);
11279     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11280                                   StackSlot, MachinePointerInfo(),
11281                                   false, false, 0);
11282     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11283                                   OffsetSlot, MachinePointerInfo(),
11284                                   false, false, 0);
11285     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11286     return Fild;
11287   }
11288
11289   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11290   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11291                                StackSlot, MachinePointerInfo(),
11292                                false, false, 0);
11293   // For i64 source, we need to add the appropriate power of 2 if the input
11294   // was negative.  This is the same as the optimization in
11295   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11296   // we must be careful to do the computation in x87 extended precision, not
11297   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11298   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11299   MachineMemOperand *MMO =
11300     DAG.getMachineFunction()
11301     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11302                           MachineMemOperand::MOLoad, 8, 8);
11303
11304   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11305   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11306   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11307                                          MVT::i64, MMO);
11308
11309   APInt FF(32, 0x5F800000ULL);
11310
11311   // Check whether the sign bit is set.
11312   SDValue SignSet = DAG.getSetCC(dl,
11313                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11314                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11315                                  ISD::SETLT);
11316
11317   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11318   SDValue FudgePtr = DAG.getConstantPool(
11319                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11320                                          getPointerTy());
11321
11322   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11323   SDValue Zero = DAG.getIntPtrConstant(0);
11324   SDValue Four = DAG.getIntPtrConstant(4);
11325   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11326                                Zero, Four);
11327   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11328
11329   // Load the value out, extending it from f32 to f80.
11330   // FIXME: Avoid the extend by constructing the right constant pool?
11331   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11332                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11333                                  MVT::f32, false, false, false, 4);
11334   // Extend everything to 80 bits to force it to be done on x87.
11335   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11336   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11337 }
11338
11339 std::pair<SDValue,SDValue>
11340 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11341                                     bool IsSigned, bool IsReplace) const {
11342   SDLoc DL(Op);
11343
11344   EVT DstTy = Op.getValueType();
11345
11346   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11347     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11348     DstTy = MVT::i64;
11349   }
11350
11351   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11352          DstTy.getSimpleVT() >= MVT::i16 &&
11353          "Unknown FP_TO_INT to lower!");
11354
11355   // These are really Legal.
11356   if (DstTy == MVT::i32 &&
11357       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11358     return std::make_pair(SDValue(), SDValue());
11359   if (Subtarget->is64Bit() &&
11360       DstTy == MVT::i64 &&
11361       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11362     return std::make_pair(SDValue(), SDValue());
11363
11364   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11365   // stack slot, or into the FTOL runtime function.
11366   MachineFunction &MF = DAG.getMachineFunction();
11367   unsigned MemSize = DstTy.getSizeInBits()/8;
11368   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11369   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11370
11371   unsigned Opc;
11372   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11373     Opc = X86ISD::WIN_FTOL;
11374   else
11375     switch (DstTy.getSimpleVT().SimpleTy) {
11376     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11377     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11378     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11379     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11380     }
11381
11382   SDValue Chain = DAG.getEntryNode();
11383   SDValue Value = Op.getOperand(0);
11384   EVT TheVT = Op.getOperand(0).getValueType();
11385   // FIXME This causes a redundant load/store if the SSE-class value is already
11386   // in memory, such as if it is on the callstack.
11387   if (isScalarFPTypeInSSEReg(TheVT)) {
11388     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11389     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11390                          MachinePointerInfo::getFixedStack(SSFI),
11391                          false, false, 0);
11392     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11393     SDValue Ops[] = {
11394       Chain, StackSlot, DAG.getValueType(TheVT)
11395     };
11396
11397     MachineMemOperand *MMO =
11398       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11399                               MachineMemOperand::MOLoad, MemSize, MemSize);
11400     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11401     Chain = Value.getValue(1);
11402     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11403     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11404   }
11405
11406   MachineMemOperand *MMO =
11407     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11408                             MachineMemOperand::MOStore, MemSize, MemSize);
11409
11410   if (Opc != X86ISD::WIN_FTOL) {
11411     // Build the FP_TO_INT*_IN_MEM
11412     SDValue Ops[] = { Chain, Value, StackSlot };
11413     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11414                                            Ops, DstTy, MMO);
11415     return std::make_pair(FIST, StackSlot);
11416   } else {
11417     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11418       DAG.getVTList(MVT::Other, MVT::Glue),
11419       Chain, Value);
11420     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11421       MVT::i32, ftol.getValue(1));
11422     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11423       MVT::i32, eax.getValue(2));
11424     SDValue Ops[] = { eax, edx };
11425     SDValue pair = IsReplace
11426       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11427       : DAG.getMergeValues(Ops, DL);
11428     return std::make_pair(pair, SDValue());
11429   }
11430 }
11431
11432 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11433                               const X86Subtarget *Subtarget) {
11434   MVT VT = Op->getSimpleValueType(0);
11435   SDValue In = Op->getOperand(0);
11436   MVT InVT = In.getSimpleValueType();
11437   SDLoc dl(Op);
11438
11439   // Optimize vectors in AVX mode:
11440   //
11441   //   v8i16 -> v8i32
11442   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11443   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11444   //   Concat upper and lower parts.
11445   //
11446   //   v4i32 -> v4i64
11447   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11448   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11449   //   Concat upper and lower parts.
11450   //
11451
11452   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11453       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11454       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11455     return SDValue();
11456
11457   if (Subtarget->hasInt256())
11458     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11459
11460   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11461   SDValue Undef = DAG.getUNDEF(InVT);
11462   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11463   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11464   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11465
11466   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11467                              VT.getVectorNumElements()/2);
11468
11469   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11470   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11471
11472   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11473 }
11474
11475 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11476                                         SelectionDAG &DAG) {
11477   MVT VT = Op->getSimpleValueType(0);
11478   SDValue In = Op->getOperand(0);
11479   MVT InVT = In.getSimpleValueType();
11480   SDLoc DL(Op);
11481   unsigned int NumElts = VT.getVectorNumElements();
11482   if (NumElts != 8 && NumElts != 16)
11483     return SDValue();
11484
11485   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11486     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11487
11488   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11489   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11490   // Now we have only mask extension
11491   assert(InVT.getVectorElementType() == MVT::i1);
11492   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11493   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11494   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11495   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11496   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11497                            MachinePointerInfo::getConstantPool(),
11498                            false, false, false, Alignment);
11499
11500   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11501   if (VT.is512BitVector())
11502     return Brcst;
11503   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11504 }
11505
11506 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11507                                SelectionDAG &DAG) {
11508   if (Subtarget->hasFp256()) {
11509     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11510     if (Res.getNode())
11511       return Res;
11512   }
11513
11514   return SDValue();
11515 }
11516
11517 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11518                                 SelectionDAG &DAG) {
11519   SDLoc DL(Op);
11520   MVT VT = Op.getSimpleValueType();
11521   SDValue In = Op.getOperand(0);
11522   MVT SVT = In.getSimpleValueType();
11523
11524   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11525     return LowerZERO_EXTEND_AVX512(Op, DAG);
11526
11527   if (Subtarget->hasFp256()) {
11528     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11529     if (Res.getNode())
11530       return Res;
11531   }
11532
11533   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11534          VT.getVectorNumElements() != SVT.getVectorNumElements());
11535   return SDValue();
11536 }
11537
11538 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11539   SDLoc DL(Op);
11540   MVT VT = Op.getSimpleValueType();
11541   SDValue In = Op.getOperand(0);
11542   MVT InVT = In.getSimpleValueType();
11543
11544   if (VT == MVT::i1) {
11545     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11546            "Invalid scalar TRUNCATE operation");
11547     if (InVT == MVT::i32)
11548       return SDValue();
11549     if (InVT.getSizeInBits() == 64)
11550       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11551     else if (InVT.getSizeInBits() < 32)
11552       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11553     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11554   }
11555   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11556          "Invalid TRUNCATE operation");
11557
11558   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11559     if (VT.getVectorElementType().getSizeInBits() >=8)
11560       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11561
11562     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11563     unsigned NumElts = InVT.getVectorNumElements();
11564     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11565     if (InVT.getSizeInBits() < 512) {
11566       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11567       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11568       InVT = ExtVT;
11569     }
11570     
11571     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11572     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11573     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11574     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11575     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11576                            MachinePointerInfo::getConstantPool(),
11577                            false, false, false, Alignment);
11578     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11579     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11580     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11581   }
11582
11583   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11584     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11585     if (Subtarget->hasInt256()) {
11586       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11587       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11588       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11589                                 ShufMask);
11590       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11591                          DAG.getIntPtrConstant(0));
11592     }
11593
11594     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11595                                DAG.getIntPtrConstant(0));
11596     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11597                                DAG.getIntPtrConstant(2));
11598     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11599     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11600     static const int ShufMask[] = {0, 2, 4, 6};
11601     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11602   }
11603
11604   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11605     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11606     if (Subtarget->hasInt256()) {
11607       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11608
11609       SmallVector<SDValue,32> pshufbMask;
11610       for (unsigned i = 0; i < 2; ++i) {
11611         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11612         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11613         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11614         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11615         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11616         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11617         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11618         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11619         for (unsigned j = 0; j < 8; ++j)
11620           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11621       }
11622       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11623       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11624       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11625
11626       static const int ShufMask[] = {0,  2,  -1,  -1};
11627       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11628                                 &ShufMask[0]);
11629       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11630                        DAG.getIntPtrConstant(0));
11631       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11632     }
11633
11634     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11635                                DAG.getIntPtrConstant(0));
11636
11637     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11638                                DAG.getIntPtrConstant(4));
11639
11640     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11641     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11642
11643     // The PSHUFB mask:
11644     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11645                                    -1, -1, -1, -1, -1, -1, -1, -1};
11646
11647     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11648     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11649     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11650
11651     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11652     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11653
11654     // The MOVLHPS Mask:
11655     static const int ShufMask2[] = {0, 1, 4, 5};
11656     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11657     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11658   }
11659
11660   // Handle truncation of V256 to V128 using shuffles.
11661   if (!VT.is128BitVector() || !InVT.is256BitVector())
11662     return SDValue();
11663
11664   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11665
11666   unsigned NumElems = VT.getVectorNumElements();
11667   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11668
11669   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11670   // Prepare truncation shuffle mask
11671   for (unsigned i = 0; i != NumElems; ++i)
11672     MaskVec[i] = i * 2;
11673   SDValue V = DAG.getVectorShuffle(NVT, DL,
11674                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11675                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11676   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11677                      DAG.getIntPtrConstant(0));
11678 }
11679
11680 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11681                                            SelectionDAG &DAG) const {
11682   assert(!Op.getSimpleValueType().isVector());
11683
11684   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11685     /*IsSigned=*/ true, /*IsReplace=*/ false);
11686   SDValue FIST = Vals.first, StackSlot = Vals.second;
11687   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11688   if (!FIST.getNode()) return Op;
11689
11690   if (StackSlot.getNode())
11691     // Load the result.
11692     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11693                        FIST, StackSlot, MachinePointerInfo(),
11694                        false, false, false, 0);
11695
11696   // The node is the result.
11697   return FIST;
11698 }
11699
11700 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11701                                            SelectionDAG &DAG) const {
11702   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11703     /*IsSigned=*/ false, /*IsReplace=*/ false);
11704   SDValue FIST = Vals.first, StackSlot = Vals.second;
11705   assert(FIST.getNode() && "Unexpected failure");
11706
11707   if (StackSlot.getNode())
11708     // Load the result.
11709     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11710                        FIST, StackSlot, MachinePointerInfo(),
11711                        false, false, false, 0);
11712
11713   // The node is the result.
11714   return FIST;
11715 }
11716
11717 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11718   SDLoc DL(Op);
11719   MVT VT = Op.getSimpleValueType();
11720   SDValue In = Op.getOperand(0);
11721   MVT SVT = In.getSimpleValueType();
11722
11723   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11724
11725   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11726                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11727                                  In, DAG.getUNDEF(SVT)));
11728 }
11729
11730 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11731   LLVMContext *Context = DAG.getContext();
11732   SDLoc dl(Op);
11733   MVT VT = Op.getSimpleValueType();
11734   MVT EltVT = VT;
11735   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11736   if (VT.isVector()) {
11737     EltVT = VT.getVectorElementType();
11738     NumElts = VT.getVectorNumElements();
11739   }
11740   Constant *C;
11741   if (EltVT == MVT::f64)
11742     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11743                                           APInt(64, ~(1ULL << 63))));
11744   else
11745     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11746                                           APInt(32, ~(1U << 31))));
11747   C = ConstantVector::getSplat(NumElts, C);
11748   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11749   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11750   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11751   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11752                              MachinePointerInfo::getConstantPool(),
11753                              false, false, false, Alignment);
11754   if (VT.isVector()) {
11755     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11756     return DAG.getNode(ISD::BITCAST, dl, VT,
11757                        DAG.getNode(ISD::AND, dl, ANDVT,
11758                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11759                                                Op.getOperand(0)),
11760                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11761   }
11762   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11763 }
11764
11765 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11766   LLVMContext *Context = DAG.getContext();
11767   SDLoc dl(Op);
11768   MVT VT = Op.getSimpleValueType();
11769   MVT EltVT = VT;
11770   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11771   if (VT.isVector()) {
11772     EltVT = VT.getVectorElementType();
11773     NumElts = VT.getVectorNumElements();
11774   }
11775   Constant *C;
11776   if (EltVT == MVT::f64)
11777     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11778                                           APInt(64, 1ULL << 63)));
11779   else
11780     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11781                                           APInt(32, 1U << 31)));
11782   C = ConstantVector::getSplat(NumElts, C);
11783   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11784   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11785   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11786   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11787                              MachinePointerInfo::getConstantPool(),
11788                              false, false, false, Alignment);
11789   if (VT.isVector()) {
11790     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11791     return DAG.getNode(ISD::BITCAST, dl, VT,
11792                        DAG.getNode(ISD::XOR, dl, XORVT,
11793                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11794                                                Op.getOperand(0)),
11795                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11796   }
11797
11798   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11799 }
11800
11801 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11802   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11803   LLVMContext *Context = DAG.getContext();
11804   SDValue Op0 = Op.getOperand(0);
11805   SDValue Op1 = Op.getOperand(1);
11806   SDLoc dl(Op);
11807   MVT VT = Op.getSimpleValueType();
11808   MVT SrcVT = Op1.getSimpleValueType();
11809
11810   // If second operand is smaller, extend it first.
11811   if (SrcVT.bitsLT(VT)) {
11812     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11813     SrcVT = VT;
11814   }
11815   // And if it is bigger, shrink it first.
11816   if (SrcVT.bitsGT(VT)) {
11817     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11818     SrcVT = VT;
11819   }
11820
11821   // At this point the operands and the result should have the same
11822   // type, and that won't be f80 since that is not custom lowered.
11823
11824   // First get the sign bit of second operand.
11825   SmallVector<Constant*,4> CV;
11826   if (SrcVT == MVT::f64) {
11827     const fltSemantics &Sem = APFloat::IEEEdouble;
11828     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11829     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11830   } else {
11831     const fltSemantics &Sem = APFloat::IEEEsingle;
11832     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11833     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11834     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11835     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11836   }
11837   Constant *C = ConstantVector::get(CV);
11838   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11839   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11840                               MachinePointerInfo::getConstantPool(),
11841                               false, false, false, 16);
11842   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11843
11844   // Shift sign bit right or left if the two operands have different types.
11845   if (SrcVT.bitsGT(VT)) {
11846     // Op0 is MVT::f32, Op1 is MVT::f64.
11847     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11848     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11849                           DAG.getConstant(32, MVT::i32));
11850     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11851     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11852                           DAG.getIntPtrConstant(0));
11853   }
11854
11855   // Clear first operand sign bit.
11856   CV.clear();
11857   if (VT == MVT::f64) {
11858     const fltSemantics &Sem = APFloat::IEEEdouble;
11859     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11860                                                    APInt(64, ~(1ULL << 63)))));
11861     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11862   } else {
11863     const fltSemantics &Sem = APFloat::IEEEsingle;
11864     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11865                                                    APInt(32, ~(1U << 31)))));
11866     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11867     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11868     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11869   }
11870   C = ConstantVector::get(CV);
11871   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11872   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11873                               MachinePointerInfo::getConstantPool(),
11874                               false, false, false, 16);
11875   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11876
11877   // Or the value with the sign bit.
11878   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11879 }
11880
11881 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11882   SDValue N0 = Op.getOperand(0);
11883   SDLoc dl(Op);
11884   MVT VT = Op.getSimpleValueType();
11885
11886   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11887   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11888                                   DAG.getConstant(1, VT));
11889   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11890 }
11891
11892 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11893 //
11894 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11895                                       SelectionDAG &DAG) {
11896   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11897
11898   if (!Subtarget->hasSSE41())
11899     return SDValue();
11900
11901   if (!Op->hasOneUse())
11902     return SDValue();
11903
11904   SDNode *N = Op.getNode();
11905   SDLoc DL(N);
11906
11907   SmallVector<SDValue, 8> Opnds;
11908   DenseMap<SDValue, unsigned> VecInMap;
11909   SmallVector<SDValue, 8> VecIns;
11910   EVT VT = MVT::Other;
11911
11912   // Recognize a special case where a vector is casted into wide integer to
11913   // test all 0s.
11914   Opnds.push_back(N->getOperand(0));
11915   Opnds.push_back(N->getOperand(1));
11916
11917   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11918     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11919     // BFS traverse all OR'd operands.
11920     if (I->getOpcode() == ISD::OR) {
11921       Opnds.push_back(I->getOperand(0));
11922       Opnds.push_back(I->getOperand(1));
11923       // Re-evaluate the number of nodes to be traversed.
11924       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11925       continue;
11926     }
11927
11928     // Quit if a non-EXTRACT_VECTOR_ELT
11929     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11930       return SDValue();
11931
11932     // Quit if without a constant index.
11933     SDValue Idx = I->getOperand(1);
11934     if (!isa<ConstantSDNode>(Idx))
11935       return SDValue();
11936
11937     SDValue ExtractedFromVec = I->getOperand(0);
11938     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11939     if (M == VecInMap.end()) {
11940       VT = ExtractedFromVec.getValueType();
11941       // Quit if not 128/256-bit vector.
11942       if (!VT.is128BitVector() && !VT.is256BitVector())
11943         return SDValue();
11944       // Quit if not the same type.
11945       if (VecInMap.begin() != VecInMap.end() &&
11946           VT != VecInMap.begin()->first.getValueType())
11947         return SDValue();
11948       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11949       VecIns.push_back(ExtractedFromVec);
11950     }
11951     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11952   }
11953
11954   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11955          "Not extracted from 128-/256-bit vector.");
11956
11957   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11958
11959   for (DenseMap<SDValue, unsigned>::const_iterator
11960         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11961     // Quit if not all elements are used.
11962     if (I->second != FullMask)
11963       return SDValue();
11964   }
11965
11966   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11967
11968   // Cast all vectors into TestVT for PTEST.
11969   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11970     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11971
11972   // If more than one full vectors are evaluated, OR them first before PTEST.
11973   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11974     // Each iteration will OR 2 nodes and append the result until there is only
11975     // 1 node left, i.e. the final OR'd value of all vectors.
11976     SDValue LHS = VecIns[Slot];
11977     SDValue RHS = VecIns[Slot + 1];
11978     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11979   }
11980
11981   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11982                      VecIns.back(), VecIns.back());
11983 }
11984
11985 /// \brief return true if \c Op has a use that doesn't just read flags.
11986 static bool hasNonFlagsUse(SDValue Op) {
11987   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11988        ++UI) {
11989     SDNode *User = *UI;
11990     unsigned UOpNo = UI.getOperandNo();
11991     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11992       // Look pass truncate.
11993       UOpNo = User->use_begin().getOperandNo();
11994       User = *User->use_begin();
11995     }
11996
11997     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11998         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11999       return true;
12000   }
12001   return false;
12002 }
12003
12004 /// Emit nodes that will be selected as "test Op0,Op0", or something
12005 /// equivalent.
12006 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12007                                     SelectionDAG &DAG) const {
12008   if (Op.getValueType() == MVT::i1)
12009     // KORTEST instruction should be selected
12010     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12011                        DAG.getConstant(0, Op.getValueType()));
12012
12013   // CF and OF aren't always set the way we want. Determine which
12014   // of these we need.
12015   bool NeedCF = false;
12016   bool NeedOF = false;
12017   switch (X86CC) {
12018   default: break;
12019   case X86::COND_A: case X86::COND_AE:
12020   case X86::COND_B: case X86::COND_BE:
12021     NeedCF = true;
12022     break;
12023   case X86::COND_G: case X86::COND_GE:
12024   case X86::COND_L: case X86::COND_LE:
12025   case X86::COND_O: case X86::COND_NO: {
12026     // Check if we really need to set the
12027     // Overflow flag. If NoSignedWrap is present
12028     // that is not actually needed.
12029     switch (Op->getOpcode()) {
12030     case ISD::ADD:
12031     case ISD::SUB:
12032     case ISD::MUL:
12033     case ISD::SHL: {
12034       const BinaryWithFlagsSDNode *BinNode =
12035           cast<BinaryWithFlagsSDNode>(Op.getNode());
12036       if (BinNode->hasNoSignedWrap())
12037         break;
12038     }
12039     default:
12040       NeedOF = true;
12041       break;
12042     }
12043     break;
12044   }
12045   }
12046   // See if we can use the EFLAGS value from the operand instead of
12047   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12048   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12049   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12050     // Emit a CMP with 0, which is the TEST pattern.
12051     //if (Op.getValueType() == MVT::i1)
12052     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12053     //                     DAG.getConstant(0, MVT::i1));
12054     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12055                        DAG.getConstant(0, Op.getValueType()));
12056   }
12057   unsigned Opcode = 0;
12058   unsigned NumOperands = 0;
12059
12060   // Truncate operations may prevent the merge of the SETCC instruction
12061   // and the arithmetic instruction before it. Attempt to truncate the operands
12062   // of the arithmetic instruction and use a reduced bit-width instruction.
12063   bool NeedTruncation = false;
12064   SDValue ArithOp = Op;
12065   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12066     SDValue Arith = Op->getOperand(0);
12067     // Both the trunc and the arithmetic op need to have one user each.
12068     if (Arith->hasOneUse())
12069       switch (Arith.getOpcode()) {
12070         default: break;
12071         case ISD::ADD:
12072         case ISD::SUB:
12073         case ISD::AND:
12074         case ISD::OR:
12075         case ISD::XOR: {
12076           NeedTruncation = true;
12077           ArithOp = Arith;
12078         }
12079       }
12080   }
12081
12082   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12083   // which may be the result of a CAST.  We use the variable 'Op', which is the
12084   // non-casted variable when we check for possible users.
12085   switch (ArithOp.getOpcode()) {
12086   case ISD::ADD:
12087     // Due to an isel shortcoming, be conservative if this add is likely to be
12088     // selected as part of a load-modify-store instruction. When the root node
12089     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12090     // uses of other nodes in the match, such as the ADD in this case. This
12091     // leads to the ADD being left around and reselected, with the result being
12092     // two adds in the output.  Alas, even if none our users are stores, that
12093     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12094     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12095     // climbing the DAG back to the root, and it doesn't seem to be worth the
12096     // effort.
12097     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12098          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12099       if (UI->getOpcode() != ISD::CopyToReg &&
12100           UI->getOpcode() != ISD::SETCC &&
12101           UI->getOpcode() != ISD::STORE)
12102         goto default_case;
12103
12104     if (ConstantSDNode *C =
12105         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12106       // An add of one will be selected as an INC.
12107       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12108         Opcode = X86ISD::INC;
12109         NumOperands = 1;
12110         break;
12111       }
12112
12113       // An add of negative one (subtract of one) will be selected as a DEC.
12114       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12115         Opcode = X86ISD::DEC;
12116         NumOperands = 1;
12117         break;
12118       }
12119     }
12120
12121     // Otherwise use a regular EFLAGS-setting add.
12122     Opcode = X86ISD::ADD;
12123     NumOperands = 2;
12124     break;
12125   case ISD::SHL:
12126   case ISD::SRL:
12127     // If we have a constant logical shift that's only used in a comparison
12128     // against zero turn it into an equivalent AND. This allows turning it into
12129     // a TEST instruction later.
12130     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12131         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12132       EVT VT = Op.getValueType();
12133       unsigned BitWidth = VT.getSizeInBits();
12134       unsigned ShAmt = Op->getConstantOperandVal(1);
12135       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12136         break;
12137       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12138                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12139                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12140       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12141         break;
12142       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12143                                 DAG.getConstant(Mask, VT));
12144       DAG.ReplaceAllUsesWith(Op, New);
12145       Op = New;
12146     }
12147     break;
12148
12149   case ISD::AND:
12150     // If the primary and result isn't used, don't bother using X86ISD::AND,
12151     // because a TEST instruction will be better.
12152     if (!hasNonFlagsUse(Op))
12153       break;
12154     // FALL THROUGH
12155   case ISD::SUB:
12156   case ISD::OR:
12157   case ISD::XOR:
12158     // Due to the ISEL shortcoming noted above, be conservative if this op is
12159     // likely to be selected as part of a load-modify-store instruction.
12160     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12161            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12162       if (UI->getOpcode() == ISD::STORE)
12163         goto default_case;
12164
12165     // Otherwise use a regular EFLAGS-setting instruction.
12166     switch (ArithOp.getOpcode()) {
12167     default: llvm_unreachable("unexpected operator!");
12168     case ISD::SUB: Opcode = X86ISD::SUB; break;
12169     case ISD::XOR: Opcode = X86ISD::XOR; break;
12170     case ISD::AND: Opcode = X86ISD::AND; break;
12171     case ISD::OR: {
12172       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12173         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12174         if (EFLAGS.getNode())
12175           return EFLAGS;
12176       }
12177       Opcode = X86ISD::OR;
12178       break;
12179     }
12180     }
12181
12182     NumOperands = 2;
12183     break;
12184   case X86ISD::ADD:
12185   case X86ISD::SUB:
12186   case X86ISD::INC:
12187   case X86ISD::DEC:
12188   case X86ISD::OR:
12189   case X86ISD::XOR:
12190   case X86ISD::AND:
12191     return SDValue(Op.getNode(), 1);
12192   default:
12193   default_case:
12194     break;
12195   }
12196
12197   // If we found that truncation is beneficial, perform the truncation and
12198   // update 'Op'.
12199   if (NeedTruncation) {
12200     EVT VT = Op.getValueType();
12201     SDValue WideVal = Op->getOperand(0);
12202     EVT WideVT = WideVal.getValueType();
12203     unsigned ConvertedOp = 0;
12204     // Use a target machine opcode to prevent further DAGCombine
12205     // optimizations that may separate the arithmetic operations
12206     // from the setcc node.
12207     switch (WideVal.getOpcode()) {
12208       default: break;
12209       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12210       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12211       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12212       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12213       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12214     }
12215
12216     if (ConvertedOp) {
12217       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12218       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12219         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12220         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12221         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12222       }
12223     }
12224   }
12225
12226   if (Opcode == 0)
12227     // Emit a CMP with 0, which is the TEST pattern.
12228     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12229                        DAG.getConstant(0, Op.getValueType()));
12230
12231   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12232   SmallVector<SDValue, 4> Ops;
12233   for (unsigned i = 0; i != NumOperands; ++i)
12234     Ops.push_back(Op.getOperand(i));
12235
12236   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12237   DAG.ReplaceAllUsesWith(Op, New);
12238   return SDValue(New.getNode(), 1);
12239 }
12240
12241 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12242 /// equivalent.
12243 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12244                                    SDLoc dl, SelectionDAG &DAG) const {
12245   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12246     if (C->getAPIntValue() == 0)
12247       return EmitTest(Op0, X86CC, dl, DAG);
12248
12249      if (Op0.getValueType() == MVT::i1)
12250        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12251   }
12252  
12253   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12254        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12255     // Do the comparison at i32 if it's smaller, besides the Atom case. 
12256     // This avoids subregister aliasing issues. Keep the smaller reference 
12257     // if we're optimizing for size, however, as that'll allow better folding 
12258     // of memory operations.
12259     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12260         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12261              AttributeSet::FunctionIndex, Attribute::MinSize) &&
12262         !Subtarget->isAtom()) {
12263       unsigned ExtendOp =
12264           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12265       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12266       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12267     }
12268     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12269     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12270     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12271                               Op0, Op1);
12272     return SDValue(Sub.getNode(), 1);
12273   }
12274   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12275 }
12276
12277 /// Convert a comparison if required by the subtarget.
12278 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12279                                                  SelectionDAG &DAG) const {
12280   // If the subtarget does not support the FUCOMI instruction, floating-point
12281   // comparisons have to be converted.
12282   if (Subtarget->hasCMov() ||
12283       Cmp.getOpcode() != X86ISD::CMP ||
12284       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12285       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12286     return Cmp;
12287
12288   // The instruction selector will select an FUCOM instruction instead of
12289   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12290   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12291   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12292   SDLoc dl(Cmp);
12293   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12294   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12295   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12296                             DAG.getConstant(8, MVT::i8));
12297   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12298   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12299 }
12300
12301 static bool isAllOnes(SDValue V) {
12302   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12303   return C && C->isAllOnesValue();
12304 }
12305
12306 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12307 /// if it's possible.
12308 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12309                                      SDLoc dl, SelectionDAG &DAG) const {
12310   SDValue Op0 = And.getOperand(0);
12311   SDValue Op1 = And.getOperand(1);
12312   if (Op0.getOpcode() == ISD::TRUNCATE)
12313     Op0 = Op0.getOperand(0);
12314   if (Op1.getOpcode() == ISD::TRUNCATE)
12315     Op1 = Op1.getOperand(0);
12316
12317   SDValue LHS, RHS;
12318   if (Op1.getOpcode() == ISD::SHL)
12319     std::swap(Op0, Op1);
12320   if (Op0.getOpcode() == ISD::SHL) {
12321     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12322       if (And00C->getZExtValue() == 1) {
12323         // If we looked past a truncate, check that it's only truncating away
12324         // known zeros.
12325         unsigned BitWidth = Op0.getValueSizeInBits();
12326         unsigned AndBitWidth = And.getValueSizeInBits();
12327         if (BitWidth > AndBitWidth) {
12328           APInt Zeros, Ones;
12329           DAG.computeKnownBits(Op0, Zeros, Ones);
12330           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12331             return SDValue();
12332         }
12333         LHS = Op1;
12334         RHS = Op0.getOperand(1);
12335       }
12336   } else if (Op1.getOpcode() == ISD::Constant) {
12337     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12338     uint64_t AndRHSVal = AndRHS->getZExtValue();
12339     SDValue AndLHS = Op0;
12340
12341     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12342       LHS = AndLHS.getOperand(0);
12343       RHS = AndLHS.getOperand(1);
12344     }
12345
12346     // Use BT if the immediate can't be encoded in a TEST instruction.
12347     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12348       LHS = AndLHS;
12349       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12350     }
12351   }
12352
12353   if (LHS.getNode()) {
12354     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12355     // instruction.  Since the shift amount is in-range-or-undefined, we know
12356     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12357     // the encoding for the i16 version is larger than the i32 version.
12358     // Also promote i16 to i32 for performance / code size reason.
12359     if (LHS.getValueType() == MVT::i8 ||
12360         LHS.getValueType() == MVT::i16)
12361       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12362
12363     // If the operand types disagree, extend the shift amount to match.  Since
12364     // BT ignores high bits (like shifts) we can use anyextend.
12365     if (LHS.getValueType() != RHS.getValueType())
12366       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12367
12368     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12369     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12370     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12371                        DAG.getConstant(Cond, MVT::i8), BT);
12372   }
12373
12374   return SDValue();
12375 }
12376
12377 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12378 /// mask CMPs.
12379 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12380                               SDValue &Op1) {
12381   unsigned SSECC;
12382   bool Swap = false;
12383
12384   // SSE Condition code mapping:
12385   //  0 - EQ
12386   //  1 - LT
12387   //  2 - LE
12388   //  3 - UNORD
12389   //  4 - NEQ
12390   //  5 - NLT
12391   //  6 - NLE
12392   //  7 - ORD
12393   switch (SetCCOpcode) {
12394   default: llvm_unreachable("Unexpected SETCC condition");
12395   case ISD::SETOEQ:
12396   case ISD::SETEQ:  SSECC = 0; break;
12397   case ISD::SETOGT:
12398   case ISD::SETGT:  Swap = true; // Fallthrough
12399   case ISD::SETLT:
12400   case ISD::SETOLT: SSECC = 1; break;
12401   case ISD::SETOGE:
12402   case ISD::SETGE:  Swap = true; // Fallthrough
12403   case ISD::SETLE:
12404   case ISD::SETOLE: SSECC = 2; break;
12405   case ISD::SETUO:  SSECC = 3; break;
12406   case ISD::SETUNE:
12407   case ISD::SETNE:  SSECC = 4; break;
12408   case ISD::SETULE: Swap = true; // Fallthrough
12409   case ISD::SETUGE: SSECC = 5; break;
12410   case ISD::SETULT: Swap = true; // Fallthrough
12411   case ISD::SETUGT: SSECC = 6; break;
12412   case ISD::SETO:   SSECC = 7; break;
12413   case ISD::SETUEQ:
12414   case ISD::SETONE: SSECC = 8; break;
12415   }
12416   if (Swap)
12417     std::swap(Op0, Op1);
12418
12419   return SSECC;
12420 }
12421
12422 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12423 // ones, and then concatenate the result back.
12424 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12425   MVT VT = Op.getSimpleValueType();
12426
12427   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12428          "Unsupported value type for operation");
12429
12430   unsigned NumElems = VT.getVectorNumElements();
12431   SDLoc dl(Op);
12432   SDValue CC = Op.getOperand(2);
12433
12434   // Extract the LHS vectors
12435   SDValue LHS = Op.getOperand(0);
12436   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12437   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12438
12439   // Extract the RHS vectors
12440   SDValue RHS = Op.getOperand(1);
12441   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12442   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12443
12444   // Issue the operation on the smaller types and concatenate the result back
12445   MVT EltVT = VT.getVectorElementType();
12446   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12447   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12448                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12449                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12450 }
12451
12452 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12453                                      const X86Subtarget *Subtarget) {
12454   SDValue Op0 = Op.getOperand(0);
12455   SDValue Op1 = Op.getOperand(1);
12456   SDValue CC = Op.getOperand(2);
12457   MVT VT = Op.getSimpleValueType();
12458   SDLoc dl(Op);
12459
12460   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12461          Op.getValueType().getScalarType() == MVT::i1 &&
12462          "Cannot set masked compare for this operation");
12463
12464   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12465   unsigned  Opc = 0;
12466   bool Unsigned = false;
12467   bool Swap = false;
12468   unsigned SSECC;
12469   switch (SetCCOpcode) {
12470   default: llvm_unreachable("Unexpected SETCC condition");
12471   case ISD::SETNE:  SSECC = 4; break;
12472   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12473   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12474   case ISD::SETLT:  Swap = true; //fall-through
12475   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12476   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12477   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12478   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12479   case ISD::SETULE: Unsigned = true; //fall-through
12480   case ISD::SETLE:  SSECC = 2; break;
12481   }
12482
12483   if (Swap)
12484     std::swap(Op0, Op1);
12485   if (Opc)
12486     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12487   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12488   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12489                      DAG.getConstant(SSECC, MVT::i8));
12490 }
12491
12492 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12493 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12494 /// return an empty value.
12495 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12496 {
12497   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12498   if (!BV)
12499     return SDValue();
12500
12501   MVT VT = Op1.getSimpleValueType();
12502   MVT EVT = VT.getVectorElementType();
12503   unsigned n = VT.getVectorNumElements();
12504   SmallVector<SDValue, 8> ULTOp1;
12505
12506   for (unsigned i = 0; i < n; ++i) {
12507     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12508     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12509       return SDValue();
12510
12511     // Avoid underflow.
12512     APInt Val = Elt->getAPIntValue();
12513     if (Val == 0)
12514       return SDValue();
12515
12516     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12517   }
12518
12519   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12520 }
12521
12522 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12523                            SelectionDAG &DAG) {
12524   SDValue Op0 = Op.getOperand(0);
12525   SDValue Op1 = Op.getOperand(1);
12526   SDValue CC = Op.getOperand(2);
12527   MVT VT = Op.getSimpleValueType();
12528   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12529   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12530   SDLoc dl(Op);
12531
12532   if (isFP) {
12533 #ifndef NDEBUG
12534     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12535     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12536 #endif
12537
12538     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12539     unsigned Opc = X86ISD::CMPP;
12540     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12541       assert(VT.getVectorNumElements() <= 16);
12542       Opc = X86ISD::CMPM;
12543     }
12544     // In the two special cases we can't handle, emit two comparisons.
12545     if (SSECC == 8) {
12546       unsigned CC0, CC1;
12547       unsigned CombineOpc;
12548       if (SetCCOpcode == ISD::SETUEQ) {
12549         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12550       } else {
12551         assert(SetCCOpcode == ISD::SETONE);
12552         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12553       }
12554
12555       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12556                                  DAG.getConstant(CC0, MVT::i8));
12557       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12558                                  DAG.getConstant(CC1, MVT::i8));
12559       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12560     }
12561     // Handle all other FP comparisons here.
12562     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12563                        DAG.getConstant(SSECC, MVT::i8));
12564   }
12565
12566   // Break 256-bit integer vector compare into smaller ones.
12567   if (VT.is256BitVector() && !Subtarget->hasInt256())
12568     return Lower256IntVSETCC(Op, DAG);
12569
12570   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12571   EVT OpVT = Op1.getValueType();
12572   if (Subtarget->hasAVX512()) {
12573     if (Op1.getValueType().is512BitVector() ||
12574         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12575       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12576
12577     // In AVX-512 architecture setcc returns mask with i1 elements,
12578     // But there is no compare instruction for i8 and i16 elements.
12579     // We are not talking about 512-bit operands in this case, these
12580     // types are illegal.
12581     if (MaskResult &&
12582         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12583          OpVT.getVectorElementType().getSizeInBits() >= 8))
12584       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12585                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12586   }
12587
12588   // We are handling one of the integer comparisons here.  Since SSE only has
12589   // GT and EQ comparisons for integer, swapping operands and multiple
12590   // operations may be required for some comparisons.
12591   unsigned Opc;
12592   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12593   bool Subus = false;
12594
12595   switch (SetCCOpcode) {
12596   default: llvm_unreachable("Unexpected SETCC condition");
12597   case ISD::SETNE:  Invert = true;
12598   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12599   case ISD::SETLT:  Swap = true;
12600   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12601   case ISD::SETGE:  Swap = true;
12602   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12603                     Invert = true; break;
12604   case ISD::SETULT: Swap = true;
12605   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12606                     FlipSigns = true; break;
12607   case ISD::SETUGE: Swap = true;
12608   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12609                     FlipSigns = true; Invert = true; break;
12610   }
12611
12612   // Special case: Use min/max operations for SETULE/SETUGE
12613   MVT VET = VT.getVectorElementType();
12614   bool hasMinMax =
12615        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12616     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12617
12618   if (hasMinMax) {
12619     switch (SetCCOpcode) {
12620     default: break;
12621     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12622     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12623     }
12624
12625     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12626   }
12627
12628   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12629   if (!MinMax && hasSubus) {
12630     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12631     // Op0 u<= Op1:
12632     //   t = psubus Op0, Op1
12633     //   pcmpeq t, <0..0>
12634     switch (SetCCOpcode) {
12635     default: break;
12636     case ISD::SETULT: {
12637       // If the comparison is against a constant we can turn this into a
12638       // setule.  With psubus, setule does not require a swap.  This is
12639       // beneficial because the constant in the register is no longer
12640       // destructed as the destination so it can be hoisted out of a loop.
12641       // Only do this pre-AVX since vpcmp* is no longer destructive.
12642       if (Subtarget->hasAVX())
12643         break;
12644       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12645       if (ULEOp1.getNode()) {
12646         Op1 = ULEOp1;
12647         Subus = true; Invert = false; Swap = false;
12648       }
12649       break;
12650     }
12651     // Psubus is better than flip-sign because it requires no inversion.
12652     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12653     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12654     }
12655
12656     if (Subus) {
12657       Opc = X86ISD::SUBUS;
12658       FlipSigns = false;
12659     }
12660   }
12661
12662   if (Swap)
12663     std::swap(Op0, Op1);
12664
12665   // Check that the operation in question is available (most are plain SSE2,
12666   // but PCMPGTQ and PCMPEQQ have different requirements).
12667   if (VT == MVT::v2i64) {
12668     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12669       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12670
12671       // First cast everything to the right type.
12672       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12673       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12674
12675       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12676       // bits of the inputs before performing those operations. The lower
12677       // compare is always unsigned.
12678       SDValue SB;
12679       if (FlipSigns) {
12680         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12681       } else {
12682         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12683         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12684         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12685                          Sign, Zero, Sign, Zero);
12686       }
12687       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12688       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12689
12690       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12691       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12692       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12693
12694       // Create masks for only the low parts/high parts of the 64 bit integers.
12695       static const int MaskHi[] = { 1, 1, 3, 3 };
12696       static const int MaskLo[] = { 0, 0, 2, 2 };
12697       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12698       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12699       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12700
12701       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12702       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12703
12704       if (Invert)
12705         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12706
12707       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12708     }
12709
12710     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12711       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12712       // pcmpeqd + pshufd + pand.
12713       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12714
12715       // First cast everything to the right type.
12716       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12717       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12718
12719       // Do the compare.
12720       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12721
12722       // Make sure the lower and upper halves are both all-ones.
12723       static const int Mask[] = { 1, 0, 3, 2 };
12724       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12725       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12726
12727       if (Invert)
12728         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12729
12730       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12731     }
12732   }
12733
12734   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12735   // bits of the inputs before performing those operations.
12736   if (FlipSigns) {
12737     EVT EltVT = VT.getVectorElementType();
12738     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12739     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12740     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12741   }
12742
12743   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12744
12745   // If the logical-not of the result is required, perform that now.
12746   if (Invert)
12747     Result = DAG.getNOT(dl, Result, VT);
12748
12749   if (MinMax)
12750     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12751
12752   if (Subus)
12753     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12754                          getZeroVector(VT, Subtarget, DAG, dl));
12755
12756   return Result;
12757 }
12758
12759 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12760
12761   MVT VT = Op.getSimpleValueType();
12762
12763   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12764
12765   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12766          && "SetCC type must be 8-bit or 1-bit integer");
12767   SDValue Op0 = Op.getOperand(0);
12768   SDValue Op1 = Op.getOperand(1);
12769   SDLoc dl(Op);
12770   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12771
12772   // Optimize to BT if possible.
12773   // Lower (X & (1 << N)) == 0 to BT(X, N).
12774   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12775   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12776   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12777       Op1.getOpcode() == ISD::Constant &&
12778       cast<ConstantSDNode>(Op1)->isNullValue() &&
12779       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12780     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12781     if (NewSetCC.getNode())
12782       return NewSetCC;
12783   }
12784
12785   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12786   // these.
12787   if (Op1.getOpcode() == ISD::Constant &&
12788       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12789        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12790       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12791
12792     // If the input is a setcc, then reuse the input setcc or use a new one with
12793     // the inverted condition.
12794     if (Op0.getOpcode() == X86ISD::SETCC) {
12795       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12796       bool Invert = (CC == ISD::SETNE) ^
12797         cast<ConstantSDNode>(Op1)->isNullValue();
12798       if (!Invert)
12799         return Op0;
12800
12801       CCode = X86::GetOppositeBranchCondition(CCode);
12802       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12803                                   DAG.getConstant(CCode, MVT::i8),
12804                                   Op0.getOperand(1));
12805       if (VT == MVT::i1)
12806         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12807       return SetCC;
12808     }
12809   }
12810   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12811       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12812       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12813
12814     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12815     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12816   }
12817
12818   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12819   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12820   if (X86CC == X86::COND_INVALID)
12821     return SDValue();
12822
12823   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12824   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12825   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12826                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12827   if (VT == MVT::i1)
12828     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12829   return SetCC;
12830 }
12831
12832 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12833 static bool isX86LogicalCmp(SDValue Op) {
12834   unsigned Opc = Op.getNode()->getOpcode();
12835   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12836       Opc == X86ISD::SAHF)
12837     return true;
12838   if (Op.getResNo() == 1 &&
12839       (Opc == X86ISD::ADD ||
12840        Opc == X86ISD::SUB ||
12841        Opc == X86ISD::ADC ||
12842        Opc == X86ISD::SBB ||
12843        Opc == X86ISD::SMUL ||
12844        Opc == X86ISD::UMUL ||
12845        Opc == X86ISD::INC ||
12846        Opc == X86ISD::DEC ||
12847        Opc == X86ISD::OR ||
12848        Opc == X86ISD::XOR ||
12849        Opc == X86ISD::AND))
12850     return true;
12851
12852   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12853     return true;
12854
12855   return false;
12856 }
12857
12858 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12859   if (V.getOpcode() != ISD::TRUNCATE)
12860     return false;
12861
12862   SDValue VOp0 = V.getOperand(0);
12863   unsigned InBits = VOp0.getValueSizeInBits();
12864   unsigned Bits = V.getValueSizeInBits();
12865   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12866 }
12867
12868 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12869   bool addTest = true;
12870   SDValue Cond  = Op.getOperand(0);
12871   SDValue Op1 = Op.getOperand(1);
12872   SDValue Op2 = Op.getOperand(2);
12873   SDLoc DL(Op);
12874   EVT VT = Op1.getValueType();
12875   SDValue CC;
12876
12877   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12878   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12879   // sequence later on.
12880   if (Cond.getOpcode() == ISD::SETCC &&
12881       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12882        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12883       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12884     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12885     int SSECC = translateX86FSETCC(
12886         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12887
12888     if (SSECC != 8) {
12889       if (Subtarget->hasAVX512()) {
12890         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12891                                   DAG.getConstant(SSECC, MVT::i8));
12892         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12893       }
12894       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12895                                 DAG.getConstant(SSECC, MVT::i8));
12896       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12897       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12898       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12899     }
12900   }
12901
12902   if (Cond.getOpcode() == ISD::SETCC) {
12903     SDValue NewCond = LowerSETCC(Cond, DAG);
12904     if (NewCond.getNode())
12905       Cond = NewCond;
12906   }
12907
12908   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12909   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12910   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12911   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12912   if (Cond.getOpcode() == X86ISD::SETCC &&
12913       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12914       isZero(Cond.getOperand(1).getOperand(1))) {
12915     SDValue Cmp = Cond.getOperand(1);
12916
12917     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12918
12919     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12920         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12921       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12922
12923       SDValue CmpOp0 = Cmp.getOperand(0);
12924       // Apply further optimizations for special cases
12925       // (select (x != 0), -1, 0) -> neg & sbb
12926       // (select (x == 0), 0, -1) -> neg & sbb
12927       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12928         if (YC->isNullValue() &&
12929             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12930           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12931           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12932                                     DAG.getConstant(0, CmpOp0.getValueType()),
12933                                     CmpOp0);
12934           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12935                                     DAG.getConstant(X86::COND_B, MVT::i8),
12936                                     SDValue(Neg.getNode(), 1));
12937           return Res;
12938         }
12939
12940       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12941                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12942       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12943
12944       SDValue Res =   // Res = 0 or -1.
12945         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12946                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12947
12948       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12949         Res = DAG.getNOT(DL, Res, Res.getValueType());
12950
12951       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12952       if (!N2C || !N2C->isNullValue())
12953         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12954       return Res;
12955     }
12956   }
12957
12958   // Look past (and (setcc_carry (cmp ...)), 1).
12959   if (Cond.getOpcode() == ISD::AND &&
12960       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12961     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12962     if (C && C->getAPIntValue() == 1)
12963       Cond = Cond.getOperand(0);
12964   }
12965
12966   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12967   // setting operand in place of the X86ISD::SETCC.
12968   unsigned CondOpcode = Cond.getOpcode();
12969   if (CondOpcode == X86ISD::SETCC ||
12970       CondOpcode == X86ISD::SETCC_CARRY) {
12971     CC = Cond.getOperand(0);
12972
12973     SDValue Cmp = Cond.getOperand(1);
12974     unsigned Opc = Cmp.getOpcode();
12975     MVT VT = Op.getSimpleValueType();
12976
12977     bool IllegalFPCMov = false;
12978     if (VT.isFloatingPoint() && !VT.isVector() &&
12979         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12980       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12981
12982     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12983         Opc == X86ISD::BT) { // FIXME
12984       Cond = Cmp;
12985       addTest = false;
12986     }
12987   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12988              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12989              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12990               Cond.getOperand(0).getValueType() != MVT::i8)) {
12991     SDValue LHS = Cond.getOperand(0);
12992     SDValue RHS = Cond.getOperand(1);
12993     unsigned X86Opcode;
12994     unsigned X86Cond;
12995     SDVTList VTs;
12996     switch (CondOpcode) {
12997     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12998     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12999     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13000     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13001     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13002     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13003     default: llvm_unreachable("unexpected overflowing operator");
13004     }
13005     if (CondOpcode == ISD::UMULO)
13006       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13007                           MVT::i32);
13008     else
13009       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13010
13011     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13012
13013     if (CondOpcode == ISD::UMULO)
13014       Cond = X86Op.getValue(2);
13015     else
13016       Cond = X86Op.getValue(1);
13017
13018     CC = DAG.getConstant(X86Cond, MVT::i8);
13019     addTest = false;
13020   }
13021
13022   if (addTest) {
13023     // Look pass the truncate if the high bits are known zero.
13024     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13025         Cond = Cond.getOperand(0);
13026
13027     // We know the result of AND is compared against zero. Try to match
13028     // it to BT.
13029     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13030       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13031       if (NewSetCC.getNode()) {
13032         CC = NewSetCC.getOperand(0);
13033         Cond = NewSetCC.getOperand(1);
13034         addTest = false;
13035       }
13036     }
13037   }
13038
13039   if (addTest) {
13040     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13041     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13042   }
13043
13044   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13045   // a <  b ?  0 : -1 -> RES = setcc_carry
13046   // a >= b ? -1 :  0 -> RES = setcc_carry
13047   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13048   if (Cond.getOpcode() == X86ISD::SUB) {
13049     Cond = ConvertCmpIfNecessary(Cond, DAG);
13050     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13051
13052     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13053         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13054       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13055                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13056       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13057         return DAG.getNOT(DL, Res, Res.getValueType());
13058       return Res;
13059     }
13060   }
13061
13062   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13063   // widen the cmov and push the truncate through. This avoids introducing a new
13064   // branch during isel and doesn't add any extensions.
13065   if (Op.getValueType() == MVT::i8 &&
13066       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13067     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13068     if (T1.getValueType() == T2.getValueType() &&
13069         // Blacklist CopyFromReg to avoid partial register stalls.
13070         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13071       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13072       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13073       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13074     }
13075   }
13076
13077   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13078   // condition is true.
13079   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13080   SDValue Ops[] = { Op2, Op1, CC, Cond };
13081   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13082 }
13083
13084 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13085   MVT VT = Op->getSimpleValueType(0);
13086   SDValue In = Op->getOperand(0);
13087   MVT InVT = In.getSimpleValueType();
13088   SDLoc dl(Op);
13089
13090   unsigned int NumElts = VT.getVectorNumElements();
13091   if (NumElts != 8 && NumElts != 16)
13092     return SDValue();
13093
13094   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13095     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13096
13097   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13098   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13099
13100   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13101   Constant *C = ConstantInt::get(*DAG.getContext(),
13102     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13103
13104   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13105   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13106   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13107                           MachinePointerInfo::getConstantPool(),
13108                           false, false, false, Alignment);
13109   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13110   if (VT.is512BitVector())
13111     return Brcst;
13112   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13113 }
13114
13115 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13116                                 SelectionDAG &DAG) {
13117   MVT VT = Op->getSimpleValueType(0);
13118   SDValue In = Op->getOperand(0);
13119   MVT InVT = In.getSimpleValueType();
13120   SDLoc dl(Op);
13121
13122   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13123     return LowerSIGN_EXTEND_AVX512(Op, DAG);
13124
13125   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13126       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13127       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13128     return SDValue();
13129
13130   if (Subtarget->hasInt256())
13131     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13132
13133   // Optimize vectors in AVX mode
13134   // Sign extend  v8i16 to v8i32 and
13135   //              v4i32 to v4i64
13136   //
13137   // Divide input vector into two parts
13138   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13139   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13140   // concat the vectors to original VT
13141
13142   unsigned NumElems = InVT.getVectorNumElements();
13143   SDValue Undef = DAG.getUNDEF(InVT);
13144
13145   SmallVector<int,8> ShufMask1(NumElems, -1);
13146   for (unsigned i = 0; i != NumElems/2; ++i)
13147     ShufMask1[i] = i;
13148
13149   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13150
13151   SmallVector<int,8> ShufMask2(NumElems, -1);
13152   for (unsigned i = 0; i != NumElems/2; ++i)
13153     ShufMask2[i] = i + NumElems/2;
13154
13155   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13156
13157   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13158                                 VT.getVectorNumElements()/2);
13159
13160   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13161   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13162
13163   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13164 }
13165
13166 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13167 // may emit an illegal shuffle but the expansion is still better than scalar
13168 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13169 // we'll emit a shuffle and a arithmetic shift.
13170 // TODO: It is possible to support ZExt by zeroing the undef values during
13171 // the shuffle phase or after the shuffle.
13172 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13173                                  SelectionDAG &DAG) {
13174   MVT RegVT = Op.getSimpleValueType();
13175   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13176   assert(RegVT.isInteger() &&
13177          "We only custom lower integer vector sext loads.");
13178
13179   // Nothing useful we can do without SSE2 shuffles.
13180   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13181
13182   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13183   SDLoc dl(Ld);
13184   EVT MemVT = Ld->getMemoryVT();
13185   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13186   unsigned RegSz = RegVT.getSizeInBits();
13187
13188   ISD::LoadExtType Ext = Ld->getExtensionType();
13189
13190   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13191          && "Only anyext and sext are currently implemented.");
13192   assert(MemVT != RegVT && "Cannot extend to the same type");
13193   assert(MemVT.isVector() && "Must load a vector from memory");
13194
13195   unsigned NumElems = RegVT.getVectorNumElements();
13196   unsigned MemSz = MemVT.getSizeInBits();
13197   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13198
13199   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13200     // The only way in which we have a legal 256-bit vector result but not the
13201     // integer 256-bit operations needed to directly lower a sextload is if we
13202     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13203     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13204     // correctly legalized. We do this late to allow the canonical form of
13205     // sextload to persist throughout the rest of the DAG combiner -- it wants
13206     // to fold together any extensions it can, and so will fuse a sign_extend
13207     // of an sextload into an sextload targeting a wider value.
13208     SDValue Load;
13209     if (MemSz == 128) {
13210       // Just switch this to a normal load.
13211       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13212                                        "it must be a legal 128-bit vector "
13213                                        "type!");
13214       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13215                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13216                   Ld->isInvariant(), Ld->getAlignment());
13217     } else {
13218       assert(MemSz < 128 &&
13219              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13220       // Do an sext load to a 128-bit vector type. We want to use the same
13221       // number of elements, but elements half as wide. This will end up being
13222       // recursively lowered by this routine, but will succeed as we definitely
13223       // have all the necessary features if we're using AVX1.
13224       EVT HalfEltVT =
13225           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13226       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13227       Load =
13228           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13229                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13230                          Ld->isNonTemporal(), Ld->isInvariant(),
13231                          Ld->getAlignment());
13232     }
13233
13234     // Replace chain users with the new chain.
13235     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13236     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13237
13238     // Finally, do a normal sign-extend to the desired register.
13239     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13240   }
13241
13242   // All sizes must be a power of two.
13243   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13244          "Non-power-of-two elements are not custom lowered!");
13245
13246   // Attempt to load the original value using scalar loads.
13247   // Find the largest scalar type that divides the total loaded size.
13248   MVT SclrLoadTy = MVT::i8;
13249   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13250        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13251     MVT Tp = (MVT::SimpleValueType)tp;
13252     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13253       SclrLoadTy = Tp;
13254     }
13255   }
13256
13257   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13258   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13259       (64 <= MemSz))
13260     SclrLoadTy = MVT::f64;
13261
13262   // Calculate the number of scalar loads that we need to perform
13263   // in order to load our vector from memory.
13264   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13265
13266   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13267          "Can only lower sext loads with a single scalar load!");
13268
13269   unsigned loadRegZize = RegSz;
13270   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13271     loadRegZize /= 2;
13272
13273   // Represent our vector as a sequence of elements which are the
13274   // largest scalar that we can load.
13275   EVT LoadUnitVecVT = EVT::getVectorVT(
13276       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13277
13278   // Represent the data using the same element type that is stored in
13279   // memory. In practice, we ''widen'' MemVT.
13280   EVT WideVecVT =
13281       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13282                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13283
13284   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13285          "Invalid vector type");
13286
13287   // We can't shuffle using an illegal type.
13288   assert(TLI.isTypeLegal(WideVecVT) &&
13289          "We only lower types that form legal widened vector types");
13290
13291   SmallVector<SDValue, 8> Chains;
13292   SDValue Ptr = Ld->getBasePtr();
13293   SDValue Increment =
13294       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13295   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13296
13297   for (unsigned i = 0; i < NumLoads; ++i) {
13298     // Perform a single load.
13299     SDValue ScalarLoad =
13300         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13301                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13302                     Ld->getAlignment());
13303     Chains.push_back(ScalarLoad.getValue(1));
13304     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13305     // another round of DAGCombining.
13306     if (i == 0)
13307       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13308     else
13309       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13310                         ScalarLoad, DAG.getIntPtrConstant(i));
13311
13312     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13313   }
13314
13315   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13316
13317   // Bitcast the loaded value to a vector of the original element type, in
13318   // the size of the target vector type.
13319   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13320   unsigned SizeRatio = RegSz / MemSz;
13321
13322   if (Ext == ISD::SEXTLOAD) {
13323     // If we have SSE4.1 we can directly emit a VSEXT node.
13324     if (Subtarget->hasSSE41()) {
13325       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13326       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13327       return Sext;
13328     }
13329
13330     // Otherwise we'll shuffle the small elements in the high bits of the
13331     // larger type and perform an arithmetic shift. If the shift is not legal
13332     // it's better to scalarize.
13333     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13334            "We can't implement an sext load without a arithmetic right shift!");
13335
13336     // Redistribute the loaded elements into the different locations.
13337     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13338     for (unsigned i = 0; i != NumElems; ++i)
13339       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13340
13341     SDValue Shuff = DAG.getVectorShuffle(
13342         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13343
13344     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13345
13346     // Build the arithmetic shift.
13347     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13348                    MemVT.getVectorElementType().getSizeInBits();
13349     Shuff =
13350         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13351
13352     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13353     return Shuff;
13354   }
13355
13356   // Redistribute the loaded elements into the different locations.
13357   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13358   for (unsigned i = 0; i != NumElems; ++i)
13359     ShuffleVec[i * SizeRatio] = i;
13360
13361   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13362                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13363
13364   // Bitcast to the requested type.
13365   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13366   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13367   return Shuff;
13368 }
13369
13370 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13371 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13372 // from the AND / OR.
13373 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13374   Opc = Op.getOpcode();
13375   if (Opc != ISD::OR && Opc != ISD::AND)
13376     return false;
13377   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13378           Op.getOperand(0).hasOneUse() &&
13379           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13380           Op.getOperand(1).hasOneUse());
13381 }
13382
13383 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13384 // 1 and that the SETCC node has a single use.
13385 static bool isXor1OfSetCC(SDValue Op) {
13386   if (Op.getOpcode() != ISD::XOR)
13387     return false;
13388   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13389   if (N1C && N1C->getAPIntValue() == 1) {
13390     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13391       Op.getOperand(0).hasOneUse();
13392   }
13393   return false;
13394 }
13395
13396 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13397   bool addTest = true;
13398   SDValue Chain = Op.getOperand(0);
13399   SDValue Cond  = Op.getOperand(1);
13400   SDValue Dest  = Op.getOperand(2);
13401   SDLoc dl(Op);
13402   SDValue CC;
13403   bool Inverted = false;
13404
13405   if (Cond.getOpcode() == ISD::SETCC) {
13406     // Check for setcc([su]{add,sub,mul}o == 0).
13407     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13408         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13409         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13410         Cond.getOperand(0).getResNo() == 1 &&
13411         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13412          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13413          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13414          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13415          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13416          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13417       Inverted = true;
13418       Cond = Cond.getOperand(0);
13419     } else {
13420       SDValue NewCond = LowerSETCC(Cond, DAG);
13421       if (NewCond.getNode())
13422         Cond = NewCond;
13423     }
13424   }
13425 #if 0
13426   // FIXME: LowerXALUO doesn't handle these!!
13427   else if (Cond.getOpcode() == X86ISD::ADD  ||
13428            Cond.getOpcode() == X86ISD::SUB  ||
13429            Cond.getOpcode() == X86ISD::SMUL ||
13430            Cond.getOpcode() == X86ISD::UMUL)
13431     Cond = LowerXALUO(Cond, DAG);
13432 #endif
13433
13434   // Look pass (and (setcc_carry (cmp ...)), 1).
13435   if (Cond.getOpcode() == ISD::AND &&
13436       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13437     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13438     if (C && C->getAPIntValue() == 1)
13439       Cond = Cond.getOperand(0);
13440   }
13441
13442   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13443   // setting operand in place of the X86ISD::SETCC.
13444   unsigned CondOpcode = Cond.getOpcode();
13445   if (CondOpcode == X86ISD::SETCC ||
13446       CondOpcode == X86ISD::SETCC_CARRY) {
13447     CC = Cond.getOperand(0);
13448
13449     SDValue Cmp = Cond.getOperand(1);
13450     unsigned Opc = Cmp.getOpcode();
13451     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13452     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13453       Cond = Cmp;
13454       addTest = false;
13455     } else {
13456       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13457       default: break;
13458       case X86::COND_O:
13459       case X86::COND_B:
13460         // These can only come from an arithmetic instruction with overflow,
13461         // e.g. SADDO, UADDO.
13462         Cond = Cond.getNode()->getOperand(1);
13463         addTest = false;
13464         break;
13465       }
13466     }
13467   }
13468   CondOpcode = Cond.getOpcode();
13469   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13470       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13471       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13472        Cond.getOperand(0).getValueType() != MVT::i8)) {
13473     SDValue LHS = Cond.getOperand(0);
13474     SDValue RHS = Cond.getOperand(1);
13475     unsigned X86Opcode;
13476     unsigned X86Cond;
13477     SDVTList VTs;
13478     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13479     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13480     // X86ISD::INC).
13481     switch (CondOpcode) {
13482     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13483     case ISD::SADDO:
13484       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13485         if (C->isOne()) {
13486           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13487           break;
13488         }
13489       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13490     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13491     case ISD::SSUBO:
13492       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13493         if (C->isOne()) {
13494           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13495           break;
13496         }
13497       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13498     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13499     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13500     default: llvm_unreachable("unexpected overflowing operator");
13501     }
13502     if (Inverted)
13503       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13504     if (CondOpcode == ISD::UMULO)
13505       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13506                           MVT::i32);
13507     else
13508       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13509
13510     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13511
13512     if (CondOpcode == ISD::UMULO)
13513       Cond = X86Op.getValue(2);
13514     else
13515       Cond = X86Op.getValue(1);
13516
13517     CC = DAG.getConstant(X86Cond, MVT::i8);
13518     addTest = false;
13519   } else {
13520     unsigned CondOpc;
13521     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13522       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13523       if (CondOpc == ISD::OR) {
13524         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13525         // two branches instead of an explicit OR instruction with a
13526         // separate test.
13527         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13528             isX86LogicalCmp(Cmp)) {
13529           CC = Cond.getOperand(0).getOperand(0);
13530           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13531                               Chain, Dest, CC, Cmp);
13532           CC = Cond.getOperand(1).getOperand(0);
13533           Cond = Cmp;
13534           addTest = false;
13535         }
13536       } else { // ISD::AND
13537         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13538         // two branches instead of an explicit AND instruction with a
13539         // separate test. However, we only do this if this block doesn't
13540         // have a fall-through edge, because this requires an explicit
13541         // jmp when the condition is false.
13542         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13543             isX86LogicalCmp(Cmp) &&
13544             Op.getNode()->hasOneUse()) {
13545           X86::CondCode CCode =
13546             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13547           CCode = X86::GetOppositeBranchCondition(CCode);
13548           CC = DAG.getConstant(CCode, MVT::i8);
13549           SDNode *User = *Op.getNode()->use_begin();
13550           // Look for an unconditional branch following this conditional branch.
13551           // We need this because we need to reverse the successors in order
13552           // to implement FCMP_OEQ.
13553           if (User->getOpcode() == ISD::BR) {
13554             SDValue FalseBB = User->getOperand(1);
13555             SDNode *NewBR =
13556               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13557             assert(NewBR == User);
13558             (void)NewBR;
13559             Dest = FalseBB;
13560
13561             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13562                                 Chain, Dest, CC, Cmp);
13563             X86::CondCode CCode =
13564               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13565             CCode = X86::GetOppositeBranchCondition(CCode);
13566             CC = DAG.getConstant(CCode, MVT::i8);
13567             Cond = Cmp;
13568             addTest = false;
13569           }
13570         }
13571       }
13572     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13573       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13574       // It should be transformed during dag combiner except when the condition
13575       // is set by a arithmetics with overflow node.
13576       X86::CondCode CCode =
13577         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13578       CCode = X86::GetOppositeBranchCondition(CCode);
13579       CC = DAG.getConstant(CCode, MVT::i8);
13580       Cond = Cond.getOperand(0).getOperand(1);
13581       addTest = false;
13582     } else if (Cond.getOpcode() == ISD::SETCC &&
13583                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13584       // For FCMP_OEQ, we can emit
13585       // two branches instead of an explicit AND instruction with a
13586       // separate test. However, we only do this if this block doesn't
13587       // have a fall-through edge, because this requires an explicit
13588       // jmp when the condition is false.
13589       if (Op.getNode()->hasOneUse()) {
13590         SDNode *User = *Op.getNode()->use_begin();
13591         // Look for an unconditional branch following this conditional branch.
13592         // We need this because we need to reverse the successors in order
13593         // to implement FCMP_OEQ.
13594         if (User->getOpcode() == ISD::BR) {
13595           SDValue FalseBB = User->getOperand(1);
13596           SDNode *NewBR =
13597             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13598           assert(NewBR == User);
13599           (void)NewBR;
13600           Dest = FalseBB;
13601
13602           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13603                                     Cond.getOperand(0), Cond.getOperand(1));
13604           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13605           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13606           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13607                               Chain, Dest, CC, Cmp);
13608           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13609           Cond = Cmp;
13610           addTest = false;
13611         }
13612       }
13613     } else if (Cond.getOpcode() == ISD::SETCC &&
13614                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13615       // For FCMP_UNE, we can emit
13616       // two branches instead of an explicit AND instruction with a
13617       // separate test. However, we only do this if this block doesn't
13618       // have a fall-through edge, because this requires an explicit
13619       // jmp when the condition is false.
13620       if (Op.getNode()->hasOneUse()) {
13621         SDNode *User = *Op.getNode()->use_begin();
13622         // Look for an unconditional branch following this conditional branch.
13623         // We need this because we need to reverse the successors in order
13624         // to implement FCMP_UNE.
13625         if (User->getOpcode() == ISD::BR) {
13626           SDValue FalseBB = User->getOperand(1);
13627           SDNode *NewBR =
13628             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13629           assert(NewBR == User);
13630           (void)NewBR;
13631
13632           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13633                                     Cond.getOperand(0), Cond.getOperand(1));
13634           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13635           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13636           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13637                               Chain, Dest, CC, Cmp);
13638           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13639           Cond = Cmp;
13640           addTest = false;
13641           Dest = FalseBB;
13642         }
13643       }
13644     }
13645   }
13646
13647   if (addTest) {
13648     // Look pass the truncate if the high bits are known zero.
13649     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13650         Cond = Cond.getOperand(0);
13651
13652     // We know the result of AND is compared against zero. Try to match
13653     // it to BT.
13654     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13655       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13656       if (NewSetCC.getNode()) {
13657         CC = NewSetCC.getOperand(0);
13658         Cond = NewSetCC.getOperand(1);
13659         addTest = false;
13660       }
13661     }
13662   }
13663
13664   if (addTest) {
13665     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13666     CC = DAG.getConstant(X86Cond, MVT::i8);
13667     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13668   }
13669   Cond = ConvertCmpIfNecessary(Cond, DAG);
13670   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13671                      Chain, Dest, CC, Cond);
13672 }
13673
13674 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13675 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13676 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13677 // that the guard pages used by the OS virtual memory manager are allocated in
13678 // correct sequence.
13679 SDValue
13680 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13681                                            SelectionDAG &DAG) const {
13682   MachineFunction &MF = DAG.getMachineFunction();
13683   bool SplitStack = MF.shouldSplitStack();
13684   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13685                SplitStack;
13686   SDLoc dl(Op);
13687
13688   if (!Lower) {
13689     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13690     SDNode* Node = Op.getNode();
13691
13692     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13693     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13694         " not tell us which reg is the stack pointer!");
13695     EVT VT = Node->getValueType(0);
13696     SDValue Tmp1 = SDValue(Node, 0);
13697     SDValue Tmp2 = SDValue(Node, 1);
13698     SDValue Tmp3 = Node->getOperand(2);
13699     SDValue Chain = Tmp1.getOperand(0);
13700
13701     // Chain the dynamic stack allocation so that it doesn't modify the stack
13702     // pointer when other instructions are using the stack.
13703     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13704         SDLoc(Node));
13705
13706     SDValue Size = Tmp2.getOperand(1);
13707     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13708     Chain = SP.getValue(1);
13709     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13710     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
13711     unsigned StackAlign = TFI.getStackAlignment();
13712     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13713     if (Align > StackAlign)
13714       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13715           DAG.getConstant(-(uint64_t)Align, VT));
13716     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13717
13718     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13719         DAG.getIntPtrConstant(0, true), SDValue(),
13720         SDLoc(Node));
13721
13722     SDValue Ops[2] = { Tmp1, Tmp2 };
13723     return DAG.getMergeValues(Ops, dl);
13724   }
13725
13726   // Get the inputs.
13727   SDValue Chain = Op.getOperand(0);
13728   SDValue Size  = Op.getOperand(1);
13729   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13730   EVT VT = Op.getNode()->getValueType(0);
13731
13732   bool Is64Bit = Subtarget->is64Bit();
13733   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13734
13735   if (SplitStack) {
13736     MachineRegisterInfo &MRI = MF.getRegInfo();
13737
13738     if (Is64Bit) {
13739       // The 64 bit implementation of segmented stacks needs to clobber both r10
13740       // r11. This makes it impossible to use it along with nested parameters.
13741       const Function *F = MF.getFunction();
13742
13743       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13744            I != E; ++I)
13745         if (I->hasNestAttr())
13746           report_fatal_error("Cannot use segmented stacks with functions that "
13747                              "have nested arguments.");
13748     }
13749
13750     const TargetRegisterClass *AddrRegClass =
13751       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13752     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13753     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13754     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13755                                 DAG.getRegister(Vreg, SPTy));
13756     SDValue Ops1[2] = { Value, Chain };
13757     return DAG.getMergeValues(Ops1, dl);
13758   } else {
13759     SDValue Flag;
13760     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13761
13762     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13763     Flag = Chain.getValue(1);
13764     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13765
13766     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13767
13768     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
13769         DAG.getSubtarget().getRegisterInfo());
13770     unsigned SPReg = RegInfo->getStackRegister();
13771     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13772     Chain = SP.getValue(1);
13773
13774     if (Align) {
13775       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13776                        DAG.getConstant(-(uint64_t)Align, VT));
13777       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13778     }
13779
13780     SDValue Ops1[2] = { SP, Chain };
13781     return DAG.getMergeValues(Ops1, dl);
13782   }
13783 }
13784
13785 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13786   MachineFunction &MF = DAG.getMachineFunction();
13787   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13788
13789   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13790   SDLoc DL(Op);
13791
13792   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13793     // vastart just stores the address of the VarArgsFrameIndex slot into the
13794     // memory location argument.
13795     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13796                                    getPointerTy());
13797     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13798                         MachinePointerInfo(SV), false, false, 0);
13799   }
13800
13801   // __va_list_tag:
13802   //   gp_offset         (0 - 6 * 8)
13803   //   fp_offset         (48 - 48 + 8 * 16)
13804   //   overflow_arg_area (point to parameters coming in memory).
13805   //   reg_save_area
13806   SmallVector<SDValue, 8> MemOps;
13807   SDValue FIN = Op.getOperand(1);
13808   // Store gp_offset
13809   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13810                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13811                                                MVT::i32),
13812                                FIN, MachinePointerInfo(SV), false, false, 0);
13813   MemOps.push_back(Store);
13814
13815   // Store fp_offset
13816   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13817                     FIN, DAG.getIntPtrConstant(4));
13818   Store = DAG.getStore(Op.getOperand(0), DL,
13819                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13820                                        MVT::i32),
13821                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13822   MemOps.push_back(Store);
13823
13824   // Store ptr to overflow_arg_area
13825   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13826                     FIN, DAG.getIntPtrConstant(4));
13827   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13828                                     getPointerTy());
13829   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13830                        MachinePointerInfo(SV, 8),
13831                        false, false, 0);
13832   MemOps.push_back(Store);
13833
13834   // Store ptr to reg_save_area.
13835   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13836                     FIN, DAG.getIntPtrConstant(8));
13837   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13838                                     getPointerTy());
13839   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13840                        MachinePointerInfo(SV, 16), false, false, 0);
13841   MemOps.push_back(Store);
13842   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13843 }
13844
13845 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13846   assert(Subtarget->is64Bit() &&
13847          "LowerVAARG only handles 64-bit va_arg!");
13848   assert((Subtarget->isTargetLinux() ||
13849           Subtarget->isTargetDarwin()) &&
13850           "Unhandled target in LowerVAARG");
13851   assert(Op.getNode()->getNumOperands() == 4);
13852   SDValue Chain = Op.getOperand(0);
13853   SDValue SrcPtr = Op.getOperand(1);
13854   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13855   unsigned Align = Op.getConstantOperandVal(3);
13856   SDLoc dl(Op);
13857
13858   EVT ArgVT = Op.getNode()->getValueType(0);
13859   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13860   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13861   uint8_t ArgMode;
13862
13863   // Decide which area this value should be read from.
13864   // TODO: Implement the AMD64 ABI in its entirety. This simple
13865   // selection mechanism works only for the basic types.
13866   if (ArgVT == MVT::f80) {
13867     llvm_unreachable("va_arg for f80 not yet implemented");
13868   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13869     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13870   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13871     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13872   } else {
13873     llvm_unreachable("Unhandled argument type in LowerVAARG");
13874   }
13875
13876   if (ArgMode == 2) {
13877     // Sanity Check: Make sure using fp_offset makes sense.
13878     assert(!DAG.getTarget().Options.UseSoftFloat &&
13879            !(DAG.getMachineFunction()
13880                 .getFunction()->getAttributes()
13881                 .hasAttribute(AttributeSet::FunctionIndex,
13882                               Attribute::NoImplicitFloat)) &&
13883            Subtarget->hasSSE1());
13884   }
13885
13886   // Insert VAARG_64 node into the DAG
13887   // VAARG_64 returns two values: Variable Argument Address, Chain
13888   SmallVector<SDValue, 11> InstOps;
13889   InstOps.push_back(Chain);
13890   InstOps.push_back(SrcPtr);
13891   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13892   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13893   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13894   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13895   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13896                                           VTs, InstOps, MVT::i64,
13897                                           MachinePointerInfo(SV),
13898                                           /*Align=*/0,
13899                                           /*Volatile=*/false,
13900                                           /*ReadMem=*/true,
13901                                           /*WriteMem=*/true);
13902   Chain = VAARG.getValue(1);
13903
13904   // Load the next argument and return it
13905   return DAG.getLoad(ArgVT, dl,
13906                      Chain,
13907                      VAARG,
13908                      MachinePointerInfo(),
13909                      false, false, false, 0);
13910 }
13911
13912 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13913                            SelectionDAG &DAG) {
13914   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13915   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13916   SDValue Chain = Op.getOperand(0);
13917   SDValue DstPtr = Op.getOperand(1);
13918   SDValue SrcPtr = Op.getOperand(2);
13919   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13920   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13921   SDLoc DL(Op);
13922
13923   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13924                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13925                        false,
13926                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13927 }
13928
13929 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13930 // amount is a constant. Takes immediate version of shift as input.
13931 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13932                                           SDValue SrcOp, uint64_t ShiftAmt,
13933                                           SelectionDAG &DAG) {
13934   MVT ElementType = VT.getVectorElementType();
13935
13936   // Fold this packed shift into its first operand if ShiftAmt is 0.
13937   if (ShiftAmt == 0)
13938     return SrcOp;
13939
13940   // Check for ShiftAmt >= element width
13941   if (ShiftAmt >= ElementType.getSizeInBits()) {
13942     if (Opc == X86ISD::VSRAI)
13943       ShiftAmt = ElementType.getSizeInBits() - 1;
13944     else
13945       return DAG.getConstant(0, VT);
13946   }
13947
13948   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13949          && "Unknown target vector shift-by-constant node");
13950
13951   // Fold this packed vector shift into a build vector if SrcOp is a
13952   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13953   if (VT == SrcOp.getSimpleValueType() &&
13954       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13955     SmallVector<SDValue, 8> Elts;
13956     unsigned NumElts = SrcOp->getNumOperands();
13957     ConstantSDNode *ND;
13958
13959     switch(Opc) {
13960     default: llvm_unreachable(nullptr);
13961     case X86ISD::VSHLI:
13962       for (unsigned i=0; i!=NumElts; ++i) {
13963         SDValue CurrentOp = SrcOp->getOperand(i);
13964         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13965           Elts.push_back(CurrentOp);
13966           continue;
13967         }
13968         ND = cast<ConstantSDNode>(CurrentOp);
13969         const APInt &C = ND->getAPIntValue();
13970         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13971       }
13972       break;
13973     case X86ISD::VSRLI:
13974       for (unsigned i=0; i!=NumElts; ++i) {
13975         SDValue CurrentOp = SrcOp->getOperand(i);
13976         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13977           Elts.push_back(CurrentOp);
13978           continue;
13979         }
13980         ND = cast<ConstantSDNode>(CurrentOp);
13981         const APInt &C = ND->getAPIntValue();
13982         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13983       }
13984       break;
13985     case X86ISD::VSRAI:
13986       for (unsigned i=0; i!=NumElts; ++i) {
13987         SDValue CurrentOp = SrcOp->getOperand(i);
13988         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13989           Elts.push_back(CurrentOp);
13990           continue;
13991         }
13992         ND = cast<ConstantSDNode>(CurrentOp);
13993         const APInt &C = ND->getAPIntValue();
13994         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13995       }
13996       break;
13997     }
13998
13999     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14000   }
14001
14002   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14003 }
14004
14005 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14006 // may or may not be a constant. Takes immediate version of shift as input.
14007 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14008                                    SDValue SrcOp, SDValue ShAmt,
14009                                    SelectionDAG &DAG) {
14010   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14011
14012   // Catch shift-by-constant.
14013   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14014     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14015                                       CShAmt->getZExtValue(), DAG);
14016
14017   // Change opcode to non-immediate version
14018   switch (Opc) {
14019     default: llvm_unreachable("Unknown target vector shift node");
14020     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14021     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14022     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14023   }
14024
14025   // Need to build a vector containing shift amount
14026   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14027   SDValue ShOps[4];
14028   ShOps[0] = ShAmt;
14029   ShOps[1] = DAG.getConstant(0, MVT::i32);
14030   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14031   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14032
14033   // The return type has to be a 128-bit type with the same element
14034   // type as the input type.
14035   MVT EltVT = VT.getVectorElementType();
14036   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14037
14038   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14039   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14040 }
14041
14042 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14043   SDLoc dl(Op);
14044   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14045   switch (IntNo) {
14046   default: return SDValue();    // Don't custom lower most intrinsics.
14047   // Comparison intrinsics.
14048   case Intrinsic::x86_sse_comieq_ss:
14049   case Intrinsic::x86_sse_comilt_ss:
14050   case Intrinsic::x86_sse_comile_ss:
14051   case Intrinsic::x86_sse_comigt_ss:
14052   case Intrinsic::x86_sse_comige_ss:
14053   case Intrinsic::x86_sse_comineq_ss:
14054   case Intrinsic::x86_sse_ucomieq_ss:
14055   case Intrinsic::x86_sse_ucomilt_ss:
14056   case Intrinsic::x86_sse_ucomile_ss:
14057   case Intrinsic::x86_sse_ucomigt_ss:
14058   case Intrinsic::x86_sse_ucomige_ss:
14059   case Intrinsic::x86_sse_ucomineq_ss:
14060   case Intrinsic::x86_sse2_comieq_sd:
14061   case Intrinsic::x86_sse2_comilt_sd:
14062   case Intrinsic::x86_sse2_comile_sd:
14063   case Intrinsic::x86_sse2_comigt_sd:
14064   case Intrinsic::x86_sse2_comige_sd:
14065   case Intrinsic::x86_sse2_comineq_sd:
14066   case Intrinsic::x86_sse2_ucomieq_sd:
14067   case Intrinsic::x86_sse2_ucomilt_sd:
14068   case Intrinsic::x86_sse2_ucomile_sd:
14069   case Intrinsic::x86_sse2_ucomigt_sd:
14070   case Intrinsic::x86_sse2_ucomige_sd:
14071   case Intrinsic::x86_sse2_ucomineq_sd: {
14072     unsigned Opc;
14073     ISD::CondCode CC;
14074     switch (IntNo) {
14075     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14076     case Intrinsic::x86_sse_comieq_ss:
14077     case Intrinsic::x86_sse2_comieq_sd:
14078       Opc = X86ISD::COMI;
14079       CC = ISD::SETEQ;
14080       break;
14081     case Intrinsic::x86_sse_comilt_ss:
14082     case Intrinsic::x86_sse2_comilt_sd:
14083       Opc = X86ISD::COMI;
14084       CC = ISD::SETLT;
14085       break;
14086     case Intrinsic::x86_sse_comile_ss:
14087     case Intrinsic::x86_sse2_comile_sd:
14088       Opc = X86ISD::COMI;
14089       CC = ISD::SETLE;
14090       break;
14091     case Intrinsic::x86_sse_comigt_ss:
14092     case Intrinsic::x86_sse2_comigt_sd:
14093       Opc = X86ISD::COMI;
14094       CC = ISD::SETGT;
14095       break;
14096     case Intrinsic::x86_sse_comige_ss:
14097     case Intrinsic::x86_sse2_comige_sd:
14098       Opc = X86ISD::COMI;
14099       CC = ISD::SETGE;
14100       break;
14101     case Intrinsic::x86_sse_comineq_ss:
14102     case Intrinsic::x86_sse2_comineq_sd:
14103       Opc = X86ISD::COMI;
14104       CC = ISD::SETNE;
14105       break;
14106     case Intrinsic::x86_sse_ucomieq_ss:
14107     case Intrinsic::x86_sse2_ucomieq_sd:
14108       Opc = X86ISD::UCOMI;
14109       CC = ISD::SETEQ;
14110       break;
14111     case Intrinsic::x86_sse_ucomilt_ss:
14112     case Intrinsic::x86_sse2_ucomilt_sd:
14113       Opc = X86ISD::UCOMI;
14114       CC = ISD::SETLT;
14115       break;
14116     case Intrinsic::x86_sse_ucomile_ss:
14117     case Intrinsic::x86_sse2_ucomile_sd:
14118       Opc = X86ISD::UCOMI;
14119       CC = ISD::SETLE;
14120       break;
14121     case Intrinsic::x86_sse_ucomigt_ss:
14122     case Intrinsic::x86_sse2_ucomigt_sd:
14123       Opc = X86ISD::UCOMI;
14124       CC = ISD::SETGT;
14125       break;
14126     case Intrinsic::x86_sse_ucomige_ss:
14127     case Intrinsic::x86_sse2_ucomige_sd:
14128       Opc = X86ISD::UCOMI;
14129       CC = ISD::SETGE;
14130       break;
14131     case Intrinsic::x86_sse_ucomineq_ss:
14132     case Intrinsic::x86_sse2_ucomineq_sd:
14133       Opc = X86ISD::UCOMI;
14134       CC = ISD::SETNE;
14135       break;
14136     }
14137
14138     SDValue LHS = Op.getOperand(1);
14139     SDValue RHS = Op.getOperand(2);
14140     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14141     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14142     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
14143     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14144                                 DAG.getConstant(X86CC, MVT::i8), Cond);
14145     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14146   }
14147
14148   // Arithmetic intrinsics.
14149   case Intrinsic::x86_sse2_pmulu_dq:
14150   case Intrinsic::x86_avx2_pmulu_dq:
14151     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14152                        Op.getOperand(1), Op.getOperand(2));
14153
14154   case Intrinsic::x86_sse41_pmuldq:
14155   case Intrinsic::x86_avx2_pmul_dq:
14156     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14157                        Op.getOperand(1), Op.getOperand(2));
14158
14159   case Intrinsic::x86_sse2_pmulhu_w:
14160   case Intrinsic::x86_avx2_pmulhu_w:
14161     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14162                        Op.getOperand(1), Op.getOperand(2));
14163
14164   case Intrinsic::x86_sse2_pmulh_w:
14165   case Intrinsic::x86_avx2_pmulh_w:
14166     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14167                        Op.getOperand(1), Op.getOperand(2));
14168
14169   // SSE2/AVX2 sub with unsigned saturation intrinsics
14170   case Intrinsic::x86_sse2_psubus_b:
14171   case Intrinsic::x86_sse2_psubus_w:
14172   case Intrinsic::x86_avx2_psubus_b:
14173   case Intrinsic::x86_avx2_psubus_w:
14174     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
14175                        Op.getOperand(1), Op.getOperand(2));
14176
14177   // SSE3/AVX horizontal add/sub intrinsics
14178   case Intrinsic::x86_sse3_hadd_ps:
14179   case Intrinsic::x86_sse3_hadd_pd:
14180   case Intrinsic::x86_avx_hadd_ps_256:
14181   case Intrinsic::x86_avx_hadd_pd_256:
14182   case Intrinsic::x86_sse3_hsub_ps:
14183   case Intrinsic::x86_sse3_hsub_pd:
14184   case Intrinsic::x86_avx_hsub_ps_256:
14185   case Intrinsic::x86_avx_hsub_pd_256:
14186   case Intrinsic::x86_ssse3_phadd_w_128:
14187   case Intrinsic::x86_ssse3_phadd_d_128:
14188   case Intrinsic::x86_avx2_phadd_w:
14189   case Intrinsic::x86_avx2_phadd_d:
14190   case Intrinsic::x86_ssse3_phsub_w_128:
14191   case Intrinsic::x86_ssse3_phsub_d_128:
14192   case Intrinsic::x86_avx2_phsub_w:
14193   case Intrinsic::x86_avx2_phsub_d: {
14194     unsigned Opcode;
14195     switch (IntNo) {
14196     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14197     case Intrinsic::x86_sse3_hadd_ps:
14198     case Intrinsic::x86_sse3_hadd_pd:
14199     case Intrinsic::x86_avx_hadd_ps_256:
14200     case Intrinsic::x86_avx_hadd_pd_256:
14201       Opcode = X86ISD::FHADD;
14202       break;
14203     case Intrinsic::x86_sse3_hsub_ps:
14204     case Intrinsic::x86_sse3_hsub_pd:
14205     case Intrinsic::x86_avx_hsub_ps_256:
14206     case Intrinsic::x86_avx_hsub_pd_256:
14207       Opcode = X86ISD::FHSUB;
14208       break;
14209     case Intrinsic::x86_ssse3_phadd_w_128:
14210     case Intrinsic::x86_ssse3_phadd_d_128:
14211     case Intrinsic::x86_avx2_phadd_w:
14212     case Intrinsic::x86_avx2_phadd_d:
14213       Opcode = X86ISD::HADD;
14214       break;
14215     case Intrinsic::x86_ssse3_phsub_w_128:
14216     case Intrinsic::x86_ssse3_phsub_d_128:
14217     case Intrinsic::x86_avx2_phsub_w:
14218     case Intrinsic::x86_avx2_phsub_d:
14219       Opcode = X86ISD::HSUB;
14220       break;
14221     }
14222     return DAG.getNode(Opcode, dl, Op.getValueType(),
14223                        Op.getOperand(1), Op.getOperand(2));
14224   }
14225
14226   // SSE2/SSE41/AVX2 integer max/min intrinsics.
14227   case Intrinsic::x86_sse2_pmaxu_b:
14228   case Intrinsic::x86_sse41_pmaxuw:
14229   case Intrinsic::x86_sse41_pmaxud:
14230   case Intrinsic::x86_avx2_pmaxu_b:
14231   case Intrinsic::x86_avx2_pmaxu_w:
14232   case Intrinsic::x86_avx2_pmaxu_d:
14233   case Intrinsic::x86_sse2_pminu_b:
14234   case Intrinsic::x86_sse41_pminuw:
14235   case Intrinsic::x86_sse41_pminud:
14236   case Intrinsic::x86_avx2_pminu_b:
14237   case Intrinsic::x86_avx2_pminu_w:
14238   case Intrinsic::x86_avx2_pminu_d:
14239   case Intrinsic::x86_sse41_pmaxsb:
14240   case Intrinsic::x86_sse2_pmaxs_w:
14241   case Intrinsic::x86_sse41_pmaxsd:
14242   case Intrinsic::x86_avx2_pmaxs_b:
14243   case Intrinsic::x86_avx2_pmaxs_w:
14244   case Intrinsic::x86_avx2_pmaxs_d:
14245   case Intrinsic::x86_sse41_pminsb:
14246   case Intrinsic::x86_sse2_pmins_w:
14247   case Intrinsic::x86_sse41_pminsd:
14248   case Intrinsic::x86_avx2_pmins_b:
14249   case Intrinsic::x86_avx2_pmins_w:
14250   case Intrinsic::x86_avx2_pmins_d: {
14251     unsigned Opcode;
14252     switch (IntNo) {
14253     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14254     case Intrinsic::x86_sse2_pmaxu_b:
14255     case Intrinsic::x86_sse41_pmaxuw:
14256     case Intrinsic::x86_sse41_pmaxud:
14257     case Intrinsic::x86_avx2_pmaxu_b:
14258     case Intrinsic::x86_avx2_pmaxu_w:
14259     case Intrinsic::x86_avx2_pmaxu_d:
14260       Opcode = X86ISD::UMAX;
14261       break;
14262     case Intrinsic::x86_sse2_pminu_b:
14263     case Intrinsic::x86_sse41_pminuw:
14264     case Intrinsic::x86_sse41_pminud:
14265     case Intrinsic::x86_avx2_pminu_b:
14266     case Intrinsic::x86_avx2_pminu_w:
14267     case Intrinsic::x86_avx2_pminu_d:
14268       Opcode = X86ISD::UMIN;
14269       break;
14270     case Intrinsic::x86_sse41_pmaxsb:
14271     case Intrinsic::x86_sse2_pmaxs_w:
14272     case Intrinsic::x86_sse41_pmaxsd:
14273     case Intrinsic::x86_avx2_pmaxs_b:
14274     case Intrinsic::x86_avx2_pmaxs_w:
14275     case Intrinsic::x86_avx2_pmaxs_d:
14276       Opcode = X86ISD::SMAX;
14277       break;
14278     case Intrinsic::x86_sse41_pminsb:
14279     case Intrinsic::x86_sse2_pmins_w:
14280     case Intrinsic::x86_sse41_pminsd:
14281     case Intrinsic::x86_avx2_pmins_b:
14282     case Intrinsic::x86_avx2_pmins_w:
14283     case Intrinsic::x86_avx2_pmins_d:
14284       Opcode = X86ISD::SMIN;
14285       break;
14286     }
14287     return DAG.getNode(Opcode, dl, Op.getValueType(),
14288                        Op.getOperand(1), Op.getOperand(2));
14289   }
14290
14291   // SSE/SSE2/AVX floating point max/min intrinsics.
14292   case Intrinsic::x86_sse_max_ps:
14293   case Intrinsic::x86_sse2_max_pd:
14294   case Intrinsic::x86_avx_max_ps_256:
14295   case Intrinsic::x86_avx_max_pd_256:
14296   case Intrinsic::x86_sse_min_ps:
14297   case Intrinsic::x86_sse2_min_pd:
14298   case Intrinsic::x86_avx_min_ps_256:
14299   case Intrinsic::x86_avx_min_pd_256: {
14300     unsigned Opcode;
14301     switch (IntNo) {
14302     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14303     case Intrinsic::x86_sse_max_ps:
14304     case Intrinsic::x86_sse2_max_pd:
14305     case Intrinsic::x86_avx_max_ps_256:
14306     case Intrinsic::x86_avx_max_pd_256:
14307       Opcode = X86ISD::FMAX;
14308       break;
14309     case Intrinsic::x86_sse_min_ps:
14310     case Intrinsic::x86_sse2_min_pd:
14311     case Intrinsic::x86_avx_min_ps_256:
14312     case Intrinsic::x86_avx_min_pd_256:
14313       Opcode = X86ISD::FMIN;
14314       break;
14315     }
14316     return DAG.getNode(Opcode, dl, Op.getValueType(),
14317                        Op.getOperand(1), Op.getOperand(2));
14318   }
14319
14320   // AVX2 variable shift intrinsics
14321   case Intrinsic::x86_avx2_psllv_d:
14322   case Intrinsic::x86_avx2_psllv_q:
14323   case Intrinsic::x86_avx2_psllv_d_256:
14324   case Intrinsic::x86_avx2_psllv_q_256:
14325   case Intrinsic::x86_avx2_psrlv_d:
14326   case Intrinsic::x86_avx2_psrlv_q:
14327   case Intrinsic::x86_avx2_psrlv_d_256:
14328   case Intrinsic::x86_avx2_psrlv_q_256:
14329   case Intrinsic::x86_avx2_psrav_d:
14330   case Intrinsic::x86_avx2_psrav_d_256: {
14331     unsigned Opcode;
14332     switch (IntNo) {
14333     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14334     case Intrinsic::x86_avx2_psllv_d:
14335     case Intrinsic::x86_avx2_psllv_q:
14336     case Intrinsic::x86_avx2_psllv_d_256:
14337     case Intrinsic::x86_avx2_psllv_q_256:
14338       Opcode = ISD::SHL;
14339       break;
14340     case Intrinsic::x86_avx2_psrlv_d:
14341     case Intrinsic::x86_avx2_psrlv_q:
14342     case Intrinsic::x86_avx2_psrlv_d_256:
14343     case Intrinsic::x86_avx2_psrlv_q_256:
14344       Opcode = ISD::SRL;
14345       break;
14346     case Intrinsic::x86_avx2_psrav_d:
14347     case Intrinsic::x86_avx2_psrav_d_256:
14348       Opcode = ISD::SRA;
14349       break;
14350     }
14351     return DAG.getNode(Opcode, dl, Op.getValueType(),
14352                        Op.getOperand(1), Op.getOperand(2));
14353   }
14354
14355   case Intrinsic::x86_sse2_packssdw_128:
14356   case Intrinsic::x86_sse2_packsswb_128:
14357   case Intrinsic::x86_avx2_packssdw:
14358   case Intrinsic::x86_avx2_packsswb:
14359     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14360                        Op.getOperand(1), Op.getOperand(2));
14361
14362   case Intrinsic::x86_sse2_packuswb_128:
14363   case Intrinsic::x86_sse41_packusdw:
14364   case Intrinsic::x86_avx2_packuswb:
14365   case Intrinsic::x86_avx2_packusdw:
14366     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14367                        Op.getOperand(1), Op.getOperand(2));
14368
14369   case Intrinsic::x86_ssse3_pshuf_b_128:
14370   case Intrinsic::x86_avx2_pshuf_b:
14371     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14372                        Op.getOperand(1), Op.getOperand(2));
14373
14374   case Intrinsic::x86_sse2_pshuf_d:
14375     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14376                        Op.getOperand(1), Op.getOperand(2));
14377
14378   case Intrinsic::x86_sse2_pshufl_w:
14379     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14380                        Op.getOperand(1), Op.getOperand(2));
14381
14382   case Intrinsic::x86_sse2_pshufh_w:
14383     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14384                        Op.getOperand(1), Op.getOperand(2));
14385
14386   case Intrinsic::x86_ssse3_psign_b_128:
14387   case Intrinsic::x86_ssse3_psign_w_128:
14388   case Intrinsic::x86_ssse3_psign_d_128:
14389   case Intrinsic::x86_avx2_psign_b:
14390   case Intrinsic::x86_avx2_psign_w:
14391   case Intrinsic::x86_avx2_psign_d:
14392     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14393                        Op.getOperand(1), Op.getOperand(2));
14394
14395   case Intrinsic::x86_sse41_insertps:
14396     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14397                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14398
14399   case Intrinsic::x86_avx_vperm2f128_ps_256:
14400   case Intrinsic::x86_avx_vperm2f128_pd_256:
14401   case Intrinsic::x86_avx_vperm2f128_si_256:
14402   case Intrinsic::x86_avx2_vperm2i128:
14403     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14404                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14405
14406   case Intrinsic::x86_avx2_permd:
14407   case Intrinsic::x86_avx2_permps:
14408     // Operands intentionally swapped. Mask is last operand to intrinsic,
14409     // but second operand for node/instruction.
14410     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14411                        Op.getOperand(2), Op.getOperand(1));
14412
14413   case Intrinsic::x86_sse_sqrt_ps:
14414   case Intrinsic::x86_sse2_sqrt_pd:
14415   case Intrinsic::x86_avx_sqrt_ps_256:
14416   case Intrinsic::x86_avx_sqrt_pd_256:
14417     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14418
14419   // ptest and testp intrinsics. The intrinsic these come from are designed to
14420   // return an integer value, not just an instruction so lower it to the ptest
14421   // or testp pattern and a setcc for the result.
14422   case Intrinsic::x86_sse41_ptestz:
14423   case Intrinsic::x86_sse41_ptestc:
14424   case Intrinsic::x86_sse41_ptestnzc:
14425   case Intrinsic::x86_avx_ptestz_256:
14426   case Intrinsic::x86_avx_ptestc_256:
14427   case Intrinsic::x86_avx_ptestnzc_256:
14428   case Intrinsic::x86_avx_vtestz_ps:
14429   case Intrinsic::x86_avx_vtestc_ps:
14430   case Intrinsic::x86_avx_vtestnzc_ps:
14431   case Intrinsic::x86_avx_vtestz_pd:
14432   case Intrinsic::x86_avx_vtestc_pd:
14433   case Intrinsic::x86_avx_vtestnzc_pd:
14434   case Intrinsic::x86_avx_vtestz_ps_256:
14435   case Intrinsic::x86_avx_vtestc_ps_256:
14436   case Intrinsic::x86_avx_vtestnzc_ps_256:
14437   case Intrinsic::x86_avx_vtestz_pd_256:
14438   case Intrinsic::x86_avx_vtestc_pd_256:
14439   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14440     bool IsTestPacked = false;
14441     unsigned X86CC;
14442     switch (IntNo) {
14443     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14444     case Intrinsic::x86_avx_vtestz_ps:
14445     case Intrinsic::x86_avx_vtestz_pd:
14446     case Intrinsic::x86_avx_vtestz_ps_256:
14447     case Intrinsic::x86_avx_vtestz_pd_256:
14448       IsTestPacked = true; // Fallthrough
14449     case Intrinsic::x86_sse41_ptestz:
14450     case Intrinsic::x86_avx_ptestz_256:
14451       // ZF = 1
14452       X86CC = X86::COND_E;
14453       break;
14454     case Intrinsic::x86_avx_vtestc_ps:
14455     case Intrinsic::x86_avx_vtestc_pd:
14456     case Intrinsic::x86_avx_vtestc_ps_256:
14457     case Intrinsic::x86_avx_vtestc_pd_256:
14458       IsTestPacked = true; // Fallthrough
14459     case Intrinsic::x86_sse41_ptestc:
14460     case Intrinsic::x86_avx_ptestc_256:
14461       // CF = 1
14462       X86CC = X86::COND_B;
14463       break;
14464     case Intrinsic::x86_avx_vtestnzc_ps:
14465     case Intrinsic::x86_avx_vtestnzc_pd:
14466     case Intrinsic::x86_avx_vtestnzc_ps_256:
14467     case Intrinsic::x86_avx_vtestnzc_pd_256:
14468       IsTestPacked = true; // Fallthrough
14469     case Intrinsic::x86_sse41_ptestnzc:
14470     case Intrinsic::x86_avx_ptestnzc_256:
14471       // ZF and CF = 0
14472       X86CC = X86::COND_A;
14473       break;
14474     }
14475
14476     SDValue LHS = Op.getOperand(1);
14477     SDValue RHS = Op.getOperand(2);
14478     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14479     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14480     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14481     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14482     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14483   }
14484   case Intrinsic::x86_avx512_kortestz_w:
14485   case Intrinsic::x86_avx512_kortestc_w: {
14486     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14487     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14488     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14489     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14490     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14491     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14492     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14493   }
14494
14495   // SSE/AVX shift intrinsics
14496   case Intrinsic::x86_sse2_psll_w:
14497   case Intrinsic::x86_sse2_psll_d:
14498   case Intrinsic::x86_sse2_psll_q:
14499   case Intrinsic::x86_avx2_psll_w:
14500   case Intrinsic::x86_avx2_psll_d:
14501   case Intrinsic::x86_avx2_psll_q:
14502   case Intrinsic::x86_sse2_psrl_w:
14503   case Intrinsic::x86_sse2_psrl_d:
14504   case Intrinsic::x86_sse2_psrl_q:
14505   case Intrinsic::x86_avx2_psrl_w:
14506   case Intrinsic::x86_avx2_psrl_d:
14507   case Intrinsic::x86_avx2_psrl_q:
14508   case Intrinsic::x86_sse2_psra_w:
14509   case Intrinsic::x86_sse2_psra_d:
14510   case Intrinsic::x86_avx2_psra_w:
14511   case Intrinsic::x86_avx2_psra_d: {
14512     unsigned Opcode;
14513     switch (IntNo) {
14514     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14515     case Intrinsic::x86_sse2_psll_w:
14516     case Intrinsic::x86_sse2_psll_d:
14517     case Intrinsic::x86_sse2_psll_q:
14518     case Intrinsic::x86_avx2_psll_w:
14519     case Intrinsic::x86_avx2_psll_d:
14520     case Intrinsic::x86_avx2_psll_q:
14521       Opcode = X86ISD::VSHL;
14522       break;
14523     case Intrinsic::x86_sse2_psrl_w:
14524     case Intrinsic::x86_sse2_psrl_d:
14525     case Intrinsic::x86_sse2_psrl_q:
14526     case Intrinsic::x86_avx2_psrl_w:
14527     case Intrinsic::x86_avx2_psrl_d:
14528     case Intrinsic::x86_avx2_psrl_q:
14529       Opcode = X86ISD::VSRL;
14530       break;
14531     case Intrinsic::x86_sse2_psra_w:
14532     case Intrinsic::x86_sse2_psra_d:
14533     case Intrinsic::x86_avx2_psra_w:
14534     case Intrinsic::x86_avx2_psra_d:
14535       Opcode = X86ISD::VSRA;
14536       break;
14537     }
14538     return DAG.getNode(Opcode, dl, Op.getValueType(),
14539                        Op.getOperand(1), Op.getOperand(2));
14540   }
14541
14542   // SSE/AVX immediate shift intrinsics
14543   case Intrinsic::x86_sse2_pslli_w:
14544   case Intrinsic::x86_sse2_pslli_d:
14545   case Intrinsic::x86_sse2_pslli_q:
14546   case Intrinsic::x86_avx2_pslli_w:
14547   case Intrinsic::x86_avx2_pslli_d:
14548   case Intrinsic::x86_avx2_pslli_q:
14549   case Intrinsic::x86_sse2_psrli_w:
14550   case Intrinsic::x86_sse2_psrli_d:
14551   case Intrinsic::x86_sse2_psrli_q:
14552   case Intrinsic::x86_avx2_psrli_w:
14553   case Intrinsic::x86_avx2_psrli_d:
14554   case Intrinsic::x86_avx2_psrli_q:
14555   case Intrinsic::x86_sse2_psrai_w:
14556   case Intrinsic::x86_sse2_psrai_d:
14557   case Intrinsic::x86_avx2_psrai_w:
14558   case Intrinsic::x86_avx2_psrai_d: {
14559     unsigned Opcode;
14560     switch (IntNo) {
14561     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14562     case Intrinsic::x86_sse2_pslli_w:
14563     case Intrinsic::x86_sse2_pslli_d:
14564     case Intrinsic::x86_sse2_pslli_q:
14565     case Intrinsic::x86_avx2_pslli_w:
14566     case Intrinsic::x86_avx2_pslli_d:
14567     case Intrinsic::x86_avx2_pslli_q:
14568       Opcode = X86ISD::VSHLI;
14569       break;
14570     case Intrinsic::x86_sse2_psrli_w:
14571     case Intrinsic::x86_sse2_psrli_d:
14572     case Intrinsic::x86_sse2_psrli_q:
14573     case Intrinsic::x86_avx2_psrli_w:
14574     case Intrinsic::x86_avx2_psrli_d:
14575     case Intrinsic::x86_avx2_psrli_q:
14576       Opcode = X86ISD::VSRLI;
14577       break;
14578     case Intrinsic::x86_sse2_psrai_w:
14579     case Intrinsic::x86_sse2_psrai_d:
14580     case Intrinsic::x86_avx2_psrai_w:
14581     case Intrinsic::x86_avx2_psrai_d:
14582       Opcode = X86ISD::VSRAI;
14583       break;
14584     }
14585     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14586                                Op.getOperand(1), Op.getOperand(2), DAG);
14587   }
14588
14589   case Intrinsic::x86_sse42_pcmpistria128:
14590   case Intrinsic::x86_sse42_pcmpestria128:
14591   case Intrinsic::x86_sse42_pcmpistric128:
14592   case Intrinsic::x86_sse42_pcmpestric128:
14593   case Intrinsic::x86_sse42_pcmpistrio128:
14594   case Intrinsic::x86_sse42_pcmpestrio128:
14595   case Intrinsic::x86_sse42_pcmpistris128:
14596   case Intrinsic::x86_sse42_pcmpestris128:
14597   case Intrinsic::x86_sse42_pcmpistriz128:
14598   case Intrinsic::x86_sse42_pcmpestriz128: {
14599     unsigned Opcode;
14600     unsigned X86CC;
14601     switch (IntNo) {
14602     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14603     case Intrinsic::x86_sse42_pcmpistria128:
14604       Opcode = X86ISD::PCMPISTRI;
14605       X86CC = X86::COND_A;
14606       break;
14607     case Intrinsic::x86_sse42_pcmpestria128:
14608       Opcode = X86ISD::PCMPESTRI;
14609       X86CC = X86::COND_A;
14610       break;
14611     case Intrinsic::x86_sse42_pcmpistric128:
14612       Opcode = X86ISD::PCMPISTRI;
14613       X86CC = X86::COND_B;
14614       break;
14615     case Intrinsic::x86_sse42_pcmpestric128:
14616       Opcode = X86ISD::PCMPESTRI;
14617       X86CC = X86::COND_B;
14618       break;
14619     case Intrinsic::x86_sse42_pcmpistrio128:
14620       Opcode = X86ISD::PCMPISTRI;
14621       X86CC = X86::COND_O;
14622       break;
14623     case Intrinsic::x86_sse42_pcmpestrio128:
14624       Opcode = X86ISD::PCMPESTRI;
14625       X86CC = X86::COND_O;
14626       break;
14627     case Intrinsic::x86_sse42_pcmpistris128:
14628       Opcode = X86ISD::PCMPISTRI;
14629       X86CC = X86::COND_S;
14630       break;
14631     case Intrinsic::x86_sse42_pcmpestris128:
14632       Opcode = X86ISD::PCMPESTRI;
14633       X86CC = X86::COND_S;
14634       break;
14635     case Intrinsic::x86_sse42_pcmpistriz128:
14636       Opcode = X86ISD::PCMPISTRI;
14637       X86CC = X86::COND_E;
14638       break;
14639     case Intrinsic::x86_sse42_pcmpestriz128:
14640       Opcode = X86ISD::PCMPESTRI;
14641       X86CC = X86::COND_E;
14642       break;
14643     }
14644     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14645     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14646     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14647     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14648                                 DAG.getConstant(X86CC, MVT::i8),
14649                                 SDValue(PCMP.getNode(), 1));
14650     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14651   }
14652
14653   case Intrinsic::x86_sse42_pcmpistri128:
14654   case Intrinsic::x86_sse42_pcmpestri128: {
14655     unsigned Opcode;
14656     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14657       Opcode = X86ISD::PCMPISTRI;
14658     else
14659       Opcode = X86ISD::PCMPESTRI;
14660
14661     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14662     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14663     return DAG.getNode(Opcode, dl, VTs, NewOps);
14664   }
14665   case Intrinsic::x86_fma_vfmadd_ps:
14666   case Intrinsic::x86_fma_vfmadd_pd:
14667   case Intrinsic::x86_fma_vfmsub_ps:
14668   case Intrinsic::x86_fma_vfmsub_pd:
14669   case Intrinsic::x86_fma_vfnmadd_ps:
14670   case Intrinsic::x86_fma_vfnmadd_pd:
14671   case Intrinsic::x86_fma_vfnmsub_ps:
14672   case Intrinsic::x86_fma_vfnmsub_pd:
14673   case Intrinsic::x86_fma_vfmaddsub_ps:
14674   case Intrinsic::x86_fma_vfmaddsub_pd:
14675   case Intrinsic::x86_fma_vfmsubadd_ps:
14676   case Intrinsic::x86_fma_vfmsubadd_pd:
14677   case Intrinsic::x86_fma_vfmadd_ps_256:
14678   case Intrinsic::x86_fma_vfmadd_pd_256:
14679   case Intrinsic::x86_fma_vfmsub_ps_256:
14680   case Intrinsic::x86_fma_vfmsub_pd_256:
14681   case Intrinsic::x86_fma_vfnmadd_ps_256:
14682   case Intrinsic::x86_fma_vfnmadd_pd_256:
14683   case Intrinsic::x86_fma_vfnmsub_ps_256:
14684   case Intrinsic::x86_fma_vfnmsub_pd_256:
14685   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14686   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14687   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14688   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14689   case Intrinsic::x86_fma_vfmadd_ps_512:
14690   case Intrinsic::x86_fma_vfmadd_pd_512:
14691   case Intrinsic::x86_fma_vfmsub_ps_512:
14692   case Intrinsic::x86_fma_vfmsub_pd_512:
14693   case Intrinsic::x86_fma_vfnmadd_ps_512:
14694   case Intrinsic::x86_fma_vfnmadd_pd_512:
14695   case Intrinsic::x86_fma_vfnmsub_ps_512:
14696   case Intrinsic::x86_fma_vfnmsub_pd_512:
14697   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14698   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14699   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14700   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14701     unsigned Opc;
14702     switch (IntNo) {
14703     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14704     case Intrinsic::x86_fma_vfmadd_ps:
14705     case Intrinsic::x86_fma_vfmadd_pd:
14706     case Intrinsic::x86_fma_vfmadd_ps_256:
14707     case Intrinsic::x86_fma_vfmadd_pd_256:
14708     case Intrinsic::x86_fma_vfmadd_ps_512:
14709     case Intrinsic::x86_fma_vfmadd_pd_512:
14710       Opc = X86ISD::FMADD;
14711       break;
14712     case Intrinsic::x86_fma_vfmsub_ps:
14713     case Intrinsic::x86_fma_vfmsub_pd:
14714     case Intrinsic::x86_fma_vfmsub_ps_256:
14715     case Intrinsic::x86_fma_vfmsub_pd_256:
14716     case Intrinsic::x86_fma_vfmsub_ps_512:
14717     case Intrinsic::x86_fma_vfmsub_pd_512:
14718       Opc = X86ISD::FMSUB;
14719       break;
14720     case Intrinsic::x86_fma_vfnmadd_ps:
14721     case Intrinsic::x86_fma_vfnmadd_pd:
14722     case Intrinsic::x86_fma_vfnmadd_ps_256:
14723     case Intrinsic::x86_fma_vfnmadd_pd_256:
14724     case Intrinsic::x86_fma_vfnmadd_ps_512:
14725     case Intrinsic::x86_fma_vfnmadd_pd_512:
14726       Opc = X86ISD::FNMADD;
14727       break;
14728     case Intrinsic::x86_fma_vfnmsub_ps:
14729     case Intrinsic::x86_fma_vfnmsub_pd:
14730     case Intrinsic::x86_fma_vfnmsub_ps_256:
14731     case Intrinsic::x86_fma_vfnmsub_pd_256:
14732     case Intrinsic::x86_fma_vfnmsub_ps_512:
14733     case Intrinsic::x86_fma_vfnmsub_pd_512:
14734       Opc = X86ISD::FNMSUB;
14735       break;
14736     case Intrinsic::x86_fma_vfmaddsub_ps:
14737     case Intrinsic::x86_fma_vfmaddsub_pd:
14738     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14739     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14740     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14741     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14742       Opc = X86ISD::FMADDSUB;
14743       break;
14744     case Intrinsic::x86_fma_vfmsubadd_ps:
14745     case Intrinsic::x86_fma_vfmsubadd_pd:
14746     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14747     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14748     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14749     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14750       Opc = X86ISD::FMSUBADD;
14751       break;
14752     }
14753
14754     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14755                        Op.getOperand(2), Op.getOperand(3));
14756   }
14757   }
14758 }
14759
14760 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14761                               SDValue Src, SDValue Mask, SDValue Base,
14762                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14763                               const X86Subtarget * Subtarget) {
14764   SDLoc dl(Op);
14765   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14766   assert(C && "Invalid scale type");
14767   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14768   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14769                              Index.getSimpleValueType().getVectorNumElements());
14770   SDValue MaskInReg;
14771   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14772   if (MaskC)
14773     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14774   else
14775     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14776   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14777   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14778   SDValue Segment = DAG.getRegister(0, MVT::i32);
14779   if (Src.getOpcode() == ISD::UNDEF)
14780     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14781   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14782   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14783   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14784   return DAG.getMergeValues(RetOps, dl);
14785 }
14786
14787 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14788                                SDValue Src, SDValue Mask, SDValue Base,
14789                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14790   SDLoc dl(Op);
14791   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14792   assert(C && "Invalid scale type");
14793   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14794   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14795   SDValue Segment = DAG.getRegister(0, MVT::i32);
14796   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14797                              Index.getSimpleValueType().getVectorNumElements());
14798   SDValue MaskInReg;
14799   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14800   if (MaskC)
14801     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14802   else
14803     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14804   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14805   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14806   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14807   return SDValue(Res, 1);
14808 }
14809
14810 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14811                                SDValue Mask, SDValue Base, SDValue Index,
14812                                SDValue ScaleOp, SDValue Chain) {
14813   SDLoc dl(Op);
14814   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14815   assert(C && "Invalid scale type");
14816   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14817   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14818   SDValue Segment = DAG.getRegister(0, MVT::i32);
14819   EVT MaskVT =
14820     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14821   SDValue MaskInReg;
14822   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14823   if (MaskC)
14824     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14825   else
14826     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14827   //SDVTList VTs = DAG.getVTList(MVT::Other);
14828   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14829   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14830   return SDValue(Res, 0);
14831 }
14832
14833 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14834 // read performance monitor counters (x86_rdpmc).
14835 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14836                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14837                               SmallVectorImpl<SDValue> &Results) {
14838   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14839   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14840   SDValue LO, HI;
14841
14842   // The ECX register is used to select the index of the performance counter
14843   // to read.
14844   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14845                                    N->getOperand(2));
14846   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14847
14848   // Reads the content of a 64-bit performance counter and returns it in the
14849   // registers EDX:EAX.
14850   if (Subtarget->is64Bit()) {
14851     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14852     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14853                             LO.getValue(2));
14854   } else {
14855     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14856     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14857                             LO.getValue(2));
14858   }
14859   Chain = HI.getValue(1);
14860
14861   if (Subtarget->is64Bit()) {
14862     // The EAX register is loaded with the low-order 32 bits. The EDX register
14863     // is loaded with the supported high-order bits of the counter.
14864     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14865                               DAG.getConstant(32, MVT::i8));
14866     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14867     Results.push_back(Chain);
14868     return;
14869   }
14870
14871   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14872   SDValue Ops[] = { LO, HI };
14873   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14874   Results.push_back(Pair);
14875   Results.push_back(Chain);
14876 }
14877
14878 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14879 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14880 // also used to custom lower READCYCLECOUNTER nodes.
14881 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14882                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14883                               SmallVectorImpl<SDValue> &Results) {
14884   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14885   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14886   SDValue LO, HI;
14887
14888   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14889   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14890   // and the EAX register is loaded with the low-order 32 bits.
14891   if (Subtarget->is64Bit()) {
14892     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14893     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14894                             LO.getValue(2));
14895   } else {
14896     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14897     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14898                             LO.getValue(2));
14899   }
14900   SDValue Chain = HI.getValue(1);
14901
14902   if (Opcode == X86ISD::RDTSCP_DAG) {
14903     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14904
14905     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14906     // the ECX register. Add 'ecx' explicitly to the chain.
14907     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14908                                      HI.getValue(2));
14909     // Explicitly store the content of ECX at the location passed in input
14910     // to the 'rdtscp' intrinsic.
14911     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14912                          MachinePointerInfo(), false, false, 0);
14913   }
14914
14915   if (Subtarget->is64Bit()) {
14916     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14917     // the EAX register is loaded with the low-order 32 bits.
14918     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14919                               DAG.getConstant(32, MVT::i8));
14920     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14921     Results.push_back(Chain);
14922     return;
14923   }
14924
14925   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14926   SDValue Ops[] = { LO, HI };
14927   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14928   Results.push_back(Pair);
14929   Results.push_back(Chain);
14930 }
14931
14932 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14933                                      SelectionDAG &DAG) {
14934   SmallVector<SDValue, 2> Results;
14935   SDLoc DL(Op);
14936   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14937                           Results);
14938   return DAG.getMergeValues(Results, DL);
14939 }
14940
14941 enum IntrinsicType {
14942   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14943 };
14944
14945 struct IntrinsicData {
14946   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14947     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14948   IntrinsicType Type;
14949   unsigned      Opc0;
14950   unsigned      Opc1;
14951 };
14952
14953 std::map < unsigned, IntrinsicData> IntrMap;
14954 static void InitIntinsicsMap() {
14955   static bool Initialized = false;
14956   if (Initialized) 
14957     return;
14958   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14959                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14960   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14961                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14962   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14963                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14964   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14965                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14966   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14967                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14968   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14969                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14970   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14971                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14972   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14973                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14974   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14975                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14976
14977   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14978                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14979   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14980                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14981   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14982                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14983   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14984                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14985   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14986                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14987   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14988                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14989   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14990                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14991   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14992                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14993    
14994   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14995                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14996                                                         X86::VGATHERPF1QPSm)));
14997   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14998                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14999                                                         X86::VGATHERPF1QPDm)));
15000   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
15001                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
15002                                                         X86::VGATHERPF1DPDm)));
15003   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
15004                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
15005                                                         X86::VGATHERPF1DPSm)));
15006   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
15007                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
15008                                                         X86::VSCATTERPF1QPSm)));
15009   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
15010                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
15011                                                         X86::VSCATTERPF1QPDm)));
15012   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
15013                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
15014                                                         X86::VSCATTERPF1DPDm)));
15015   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
15016                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
15017                                                         X86::VSCATTERPF1DPSm)));
15018   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
15019                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15020   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
15021                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15022   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
15023                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15024   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
15025                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15026   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
15027                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15028   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
15029                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15030   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
15031                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
15032   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
15033                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
15034   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
15035                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
15036   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
15037                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
15038   Initialized = true;
15039 }
15040
15041 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15042                                       SelectionDAG &DAG) {
15043   InitIntinsicsMap();
15044   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15045   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
15046   if (itr == IntrMap.end())
15047     return SDValue();
15048
15049   SDLoc dl(Op);
15050   IntrinsicData Intr = itr->second;
15051   switch(Intr.Type) {
15052   case RDSEED:
15053   case RDRAND: {
15054     // Emit the node with the right value type.
15055     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15056     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
15057
15058     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15059     // Otherwise return the value from Rand, which is always 0, casted to i32.
15060     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15061                       DAG.getConstant(1, Op->getValueType(1)),
15062                       DAG.getConstant(X86::COND_B, MVT::i32),
15063                       SDValue(Result.getNode(), 1) };
15064     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15065                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15066                                   Ops);
15067
15068     // Return { result, isValid, chain }.
15069     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15070                        SDValue(Result.getNode(), 2));
15071   }
15072   case GATHER: {
15073   //gather(v1, mask, index, base, scale);
15074     SDValue Chain = Op.getOperand(0);
15075     SDValue Src   = Op.getOperand(2);
15076     SDValue Base  = Op.getOperand(3);
15077     SDValue Index = Op.getOperand(4);
15078     SDValue Mask  = Op.getOperand(5);
15079     SDValue Scale = Op.getOperand(6);
15080     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15081                           Subtarget);
15082   }
15083   case SCATTER: {
15084   //scatter(base, mask, index, v1, scale);
15085     SDValue Chain = Op.getOperand(0);
15086     SDValue Base  = Op.getOperand(2);
15087     SDValue Mask  = Op.getOperand(3);
15088     SDValue Index = Op.getOperand(4);
15089     SDValue Src   = Op.getOperand(5);
15090     SDValue Scale = Op.getOperand(6);
15091     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15092   }
15093   case PREFETCH: {
15094     SDValue Hint = Op.getOperand(6);
15095     unsigned HintVal;
15096     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15097         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15098       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15099     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
15100     SDValue Chain = Op.getOperand(0);
15101     SDValue Mask  = Op.getOperand(2);
15102     SDValue Index = Op.getOperand(3);
15103     SDValue Base  = Op.getOperand(4);
15104     SDValue Scale = Op.getOperand(5);
15105     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15106   }
15107   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15108   case RDTSC: {
15109     SmallVector<SDValue, 2> Results;
15110     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
15111     return DAG.getMergeValues(Results, dl);
15112   }
15113   // Read Performance Monitoring Counters.
15114   case RDPMC: {
15115     SmallVector<SDValue, 2> Results;
15116     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15117     return DAG.getMergeValues(Results, dl);
15118   }
15119   // XTEST intrinsics.
15120   case XTEST: {
15121     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15122     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
15123     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15124                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15125                                 InTrans);
15126     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15127     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15128                        Ret, SDValue(InTrans.getNode(), 1));
15129   }
15130   }
15131   llvm_unreachable("Unknown Intrinsic Type");
15132 }
15133
15134 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15135                                            SelectionDAG &DAG) const {
15136   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15137   MFI->setReturnAddressIsTaken(true);
15138
15139   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15140     return SDValue();
15141
15142   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15143   SDLoc dl(Op);
15144   EVT PtrVT = getPointerTy();
15145
15146   if (Depth > 0) {
15147     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15148     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15149         DAG.getSubtarget().getRegisterInfo());
15150     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15151     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15152                        DAG.getNode(ISD::ADD, dl, PtrVT,
15153                                    FrameAddr, Offset),
15154                        MachinePointerInfo(), false, false, false, 0);
15155   }
15156
15157   // Just load the return address.
15158   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15159   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15160                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15161 }
15162
15163 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15164   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15165   MFI->setFrameAddressIsTaken(true);
15166
15167   EVT VT = Op.getValueType();
15168   SDLoc dl(Op);  // FIXME probably not meaningful
15169   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15170   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15171       DAG.getSubtarget().getRegisterInfo());
15172   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15173   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15174           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15175          "Invalid Frame Register!");
15176   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15177   while (Depth--)
15178     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15179                             MachinePointerInfo(),
15180                             false, false, false, 0);
15181   return FrameAddr;
15182 }
15183
15184 // FIXME? Maybe this could be a TableGen attribute on some registers and
15185 // this table could be generated automatically from RegInfo.
15186 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15187                                               EVT VT) const {
15188   unsigned Reg = StringSwitch<unsigned>(RegName)
15189                        .Case("esp", X86::ESP)
15190                        .Case("rsp", X86::RSP)
15191                        .Default(0);
15192   if (Reg)
15193     return Reg;
15194   report_fatal_error("Invalid register name global variable");
15195 }
15196
15197 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15198                                                      SelectionDAG &DAG) const {
15199   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15200       DAG.getSubtarget().getRegisterInfo());
15201   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15202 }
15203
15204 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15205   SDValue Chain     = Op.getOperand(0);
15206   SDValue Offset    = Op.getOperand(1);
15207   SDValue Handler   = Op.getOperand(2);
15208   SDLoc dl      (Op);
15209
15210   EVT PtrVT = getPointerTy();
15211   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15212       DAG.getSubtarget().getRegisterInfo());
15213   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15214   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15215           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15216          "Invalid Frame Register!");
15217   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15218   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15219
15220   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15221                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15222   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15223   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15224                        false, false, 0);
15225   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15226
15227   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15228                      DAG.getRegister(StoreAddrReg, PtrVT));
15229 }
15230
15231 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15232                                                SelectionDAG &DAG) const {
15233   SDLoc DL(Op);
15234   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15235                      DAG.getVTList(MVT::i32, MVT::Other),
15236                      Op.getOperand(0), Op.getOperand(1));
15237 }
15238
15239 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15240                                                 SelectionDAG &DAG) const {
15241   SDLoc DL(Op);
15242   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15243                      Op.getOperand(0), Op.getOperand(1));
15244 }
15245
15246 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15247   return Op.getOperand(0);
15248 }
15249
15250 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15251                                                 SelectionDAG &DAG) const {
15252   SDValue Root = Op.getOperand(0);
15253   SDValue Trmp = Op.getOperand(1); // trampoline
15254   SDValue FPtr = Op.getOperand(2); // nested function
15255   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15256   SDLoc dl (Op);
15257
15258   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15259   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15260
15261   if (Subtarget->is64Bit()) {
15262     SDValue OutChains[6];
15263
15264     // Large code-model.
15265     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15266     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15267
15268     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15269     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15270
15271     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15272
15273     // Load the pointer to the nested function into R11.
15274     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15275     SDValue Addr = Trmp;
15276     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15277                                 Addr, MachinePointerInfo(TrmpAddr),
15278                                 false, false, 0);
15279
15280     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15281                        DAG.getConstant(2, MVT::i64));
15282     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15283                                 MachinePointerInfo(TrmpAddr, 2),
15284                                 false, false, 2);
15285
15286     // Load the 'nest' parameter value into R10.
15287     // R10 is specified in X86CallingConv.td
15288     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15289     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15290                        DAG.getConstant(10, MVT::i64));
15291     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15292                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15293                                 false, false, 0);
15294
15295     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15296                        DAG.getConstant(12, MVT::i64));
15297     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15298                                 MachinePointerInfo(TrmpAddr, 12),
15299                                 false, false, 2);
15300
15301     // Jump to the nested function.
15302     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15303     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15304                        DAG.getConstant(20, MVT::i64));
15305     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15306                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15307                                 false, false, 0);
15308
15309     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15310     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15311                        DAG.getConstant(22, MVT::i64));
15312     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15313                                 MachinePointerInfo(TrmpAddr, 22),
15314                                 false, false, 0);
15315
15316     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15317   } else {
15318     const Function *Func =
15319       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15320     CallingConv::ID CC = Func->getCallingConv();
15321     unsigned NestReg;
15322
15323     switch (CC) {
15324     default:
15325       llvm_unreachable("Unsupported calling convention");
15326     case CallingConv::C:
15327     case CallingConv::X86_StdCall: {
15328       // Pass 'nest' parameter in ECX.
15329       // Must be kept in sync with X86CallingConv.td
15330       NestReg = X86::ECX;
15331
15332       // Check that ECX wasn't needed by an 'inreg' parameter.
15333       FunctionType *FTy = Func->getFunctionType();
15334       const AttributeSet &Attrs = Func->getAttributes();
15335
15336       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15337         unsigned InRegCount = 0;
15338         unsigned Idx = 1;
15339
15340         for (FunctionType::param_iterator I = FTy->param_begin(),
15341              E = FTy->param_end(); I != E; ++I, ++Idx)
15342           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15343             // FIXME: should only count parameters that are lowered to integers.
15344             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15345
15346         if (InRegCount > 2) {
15347           report_fatal_error("Nest register in use - reduce number of inreg"
15348                              " parameters!");
15349         }
15350       }
15351       break;
15352     }
15353     case CallingConv::X86_FastCall:
15354     case CallingConv::X86_ThisCall:
15355     case CallingConv::Fast:
15356       // Pass 'nest' parameter in EAX.
15357       // Must be kept in sync with X86CallingConv.td
15358       NestReg = X86::EAX;
15359       break;
15360     }
15361
15362     SDValue OutChains[4];
15363     SDValue Addr, Disp;
15364
15365     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15366                        DAG.getConstant(10, MVT::i32));
15367     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15368
15369     // This is storing the opcode for MOV32ri.
15370     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15371     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15372     OutChains[0] = DAG.getStore(Root, dl,
15373                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15374                                 Trmp, MachinePointerInfo(TrmpAddr),
15375                                 false, false, 0);
15376
15377     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15378                        DAG.getConstant(1, MVT::i32));
15379     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15380                                 MachinePointerInfo(TrmpAddr, 1),
15381                                 false, false, 1);
15382
15383     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15384     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15385                        DAG.getConstant(5, MVT::i32));
15386     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15387                                 MachinePointerInfo(TrmpAddr, 5),
15388                                 false, false, 1);
15389
15390     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15391                        DAG.getConstant(6, MVT::i32));
15392     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15393                                 MachinePointerInfo(TrmpAddr, 6),
15394                                 false, false, 1);
15395
15396     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15397   }
15398 }
15399
15400 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15401                                             SelectionDAG &DAG) const {
15402   /*
15403    The rounding mode is in bits 11:10 of FPSR, and has the following
15404    settings:
15405      00 Round to nearest
15406      01 Round to -inf
15407      10 Round to +inf
15408      11 Round to 0
15409
15410   FLT_ROUNDS, on the other hand, expects the following:
15411     -1 Undefined
15412      0 Round to 0
15413      1 Round to nearest
15414      2 Round to +inf
15415      3 Round to -inf
15416
15417   To perform the conversion, we do:
15418     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15419   */
15420
15421   MachineFunction &MF = DAG.getMachineFunction();
15422   const TargetMachine &TM = MF.getTarget();
15423   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15424   unsigned StackAlignment = TFI.getStackAlignment();
15425   MVT VT = Op.getSimpleValueType();
15426   SDLoc DL(Op);
15427
15428   // Save FP Control Word to stack slot
15429   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15430   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15431
15432   MachineMemOperand *MMO =
15433    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15434                            MachineMemOperand::MOStore, 2, 2);
15435
15436   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15437   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15438                                           DAG.getVTList(MVT::Other),
15439                                           Ops, MVT::i16, MMO);
15440
15441   // Load FP Control Word from stack slot
15442   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15443                             MachinePointerInfo(), false, false, false, 0);
15444
15445   // Transform as necessary
15446   SDValue CWD1 =
15447     DAG.getNode(ISD::SRL, DL, MVT::i16,
15448                 DAG.getNode(ISD::AND, DL, MVT::i16,
15449                             CWD, DAG.getConstant(0x800, MVT::i16)),
15450                 DAG.getConstant(11, MVT::i8));
15451   SDValue CWD2 =
15452     DAG.getNode(ISD::SRL, DL, MVT::i16,
15453                 DAG.getNode(ISD::AND, DL, MVT::i16,
15454                             CWD, DAG.getConstant(0x400, MVT::i16)),
15455                 DAG.getConstant(9, MVT::i8));
15456
15457   SDValue RetVal =
15458     DAG.getNode(ISD::AND, DL, MVT::i16,
15459                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15460                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15461                             DAG.getConstant(1, MVT::i16)),
15462                 DAG.getConstant(3, MVT::i16));
15463
15464   return DAG.getNode((VT.getSizeInBits() < 16 ?
15465                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15466 }
15467
15468 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15469   MVT VT = Op.getSimpleValueType();
15470   EVT OpVT = VT;
15471   unsigned NumBits = VT.getSizeInBits();
15472   SDLoc dl(Op);
15473
15474   Op = Op.getOperand(0);
15475   if (VT == MVT::i8) {
15476     // Zero extend to i32 since there is not an i8 bsr.
15477     OpVT = MVT::i32;
15478     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15479   }
15480
15481   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15482   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15483   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15484
15485   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15486   SDValue Ops[] = {
15487     Op,
15488     DAG.getConstant(NumBits+NumBits-1, OpVT),
15489     DAG.getConstant(X86::COND_E, MVT::i8),
15490     Op.getValue(1)
15491   };
15492   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15493
15494   // Finally xor with NumBits-1.
15495   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15496
15497   if (VT == MVT::i8)
15498     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15499   return Op;
15500 }
15501
15502 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15503   MVT VT = Op.getSimpleValueType();
15504   EVT OpVT = VT;
15505   unsigned NumBits = VT.getSizeInBits();
15506   SDLoc dl(Op);
15507
15508   Op = Op.getOperand(0);
15509   if (VT == MVT::i8) {
15510     // Zero extend to i32 since there is not an i8 bsr.
15511     OpVT = MVT::i32;
15512     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15513   }
15514
15515   // Issue a bsr (scan bits in reverse).
15516   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15517   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15518
15519   // And xor with NumBits-1.
15520   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15521
15522   if (VT == MVT::i8)
15523     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15524   return Op;
15525 }
15526
15527 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15528   MVT VT = Op.getSimpleValueType();
15529   unsigned NumBits = VT.getSizeInBits();
15530   SDLoc dl(Op);
15531   Op = Op.getOperand(0);
15532
15533   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15534   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15535   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15536
15537   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15538   SDValue Ops[] = {
15539     Op,
15540     DAG.getConstant(NumBits, VT),
15541     DAG.getConstant(X86::COND_E, MVT::i8),
15542     Op.getValue(1)
15543   };
15544   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15545 }
15546
15547 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15548 // ones, and then concatenate the result back.
15549 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15550   MVT VT = Op.getSimpleValueType();
15551
15552   assert(VT.is256BitVector() && VT.isInteger() &&
15553          "Unsupported value type for operation");
15554
15555   unsigned NumElems = VT.getVectorNumElements();
15556   SDLoc dl(Op);
15557
15558   // Extract the LHS vectors
15559   SDValue LHS = Op.getOperand(0);
15560   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15561   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15562
15563   // Extract the RHS vectors
15564   SDValue RHS = Op.getOperand(1);
15565   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15566   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15567
15568   MVT EltVT = VT.getVectorElementType();
15569   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15570
15571   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15572                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15573                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15574 }
15575
15576 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15577   assert(Op.getSimpleValueType().is256BitVector() &&
15578          Op.getSimpleValueType().isInteger() &&
15579          "Only handle AVX 256-bit vector integer operation");
15580   return Lower256IntArith(Op, DAG);
15581 }
15582
15583 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15584   assert(Op.getSimpleValueType().is256BitVector() &&
15585          Op.getSimpleValueType().isInteger() &&
15586          "Only handle AVX 256-bit vector integer operation");
15587   return Lower256IntArith(Op, DAG);
15588 }
15589
15590 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15591                         SelectionDAG &DAG) {
15592   SDLoc dl(Op);
15593   MVT VT = Op.getSimpleValueType();
15594
15595   // Decompose 256-bit ops into smaller 128-bit ops.
15596   if (VT.is256BitVector() && !Subtarget->hasInt256())
15597     return Lower256IntArith(Op, DAG);
15598
15599   SDValue A = Op.getOperand(0);
15600   SDValue B = Op.getOperand(1);
15601
15602   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15603   if (VT == MVT::v4i32) {
15604     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15605            "Should not custom lower when pmuldq is available!");
15606
15607     // Extract the odd parts.
15608     static const int UnpackMask[] = { 1, -1, 3, -1 };
15609     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15610     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15611
15612     // Multiply the even parts.
15613     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15614     // Now multiply odd parts.
15615     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15616
15617     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15618     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15619
15620     // Merge the two vectors back together with a shuffle. This expands into 2
15621     // shuffles.
15622     static const int ShufMask[] = { 0, 4, 2, 6 };
15623     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15624   }
15625
15626   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15627          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15628
15629   //  Ahi = psrlqi(a, 32);
15630   //  Bhi = psrlqi(b, 32);
15631   //
15632   //  AloBlo = pmuludq(a, b);
15633   //  AloBhi = pmuludq(a, Bhi);
15634   //  AhiBlo = pmuludq(Ahi, b);
15635
15636   //  AloBhi = psllqi(AloBhi, 32);
15637   //  AhiBlo = psllqi(AhiBlo, 32);
15638   //  return AloBlo + AloBhi + AhiBlo;
15639
15640   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15641   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15642
15643   // Bit cast to 32-bit vectors for MULUDQ
15644   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15645                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15646   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15647   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15648   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15649   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15650
15651   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15652   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15653   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15654
15655   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15656   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15657
15658   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15659   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15660 }
15661
15662 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15663   assert(Subtarget->isTargetWin64() && "Unexpected target");
15664   EVT VT = Op.getValueType();
15665   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15666          "Unexpected return type for lowering");
15667
15668   RTLIB::Libcall LC;
15669   bool isSigned;
15670   switch (Op->getOpcode()) {
15671   default: llvm_unreachable("Unexpected request for libcall!");
15672   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15673   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15674   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15675   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15676   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15677   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15678   }
15679
15680   SDLoc dl(Op);
15681   SDValue InChain = DAG.getEntryNode();
15682
15683   TargetLowering::ArgListTy Args;
15684   TargetLowering::ArgListEntry Entry;
15685   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15686     EVT ArgVT = Op->getOperand(i).getValueType();
15687     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15688            "Unexpected argument type for lowering");
15689     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15690     Entry.Node = StackPtr;
15691     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15692                            false, false, 16);
15693     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15694     Entry.Ty = PointerType::get(ArgTy,0);
15695     Entry.isSExt = false;
15696     Entry.isZExt = false;
15697     Args.push_back(Entry);
15698   }
15699
15700   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15701                                          getPointerTy());
15702
15703   TargetLowering::CallLoweringInfo CLI(DAG);
15704   CLI.setDebugLoc(dl).setChain(InChain)
15705     .setCallee(getLibcallCallingConv(LC),
15706                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15707                Callee, std::move(Args), 0)
15708     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15709
15710   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15711   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15712 }
15713
15714 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15715                              SelectionDAG &DAG) {
15716   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15717   EVT VT = Op0.getValueType();
15718   SDLoc dl(Op);
15719
15720   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15721          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15722
15723   // PMULxD operations multiply each even value (starting at 0) of LHS with
15724   // the related value of RHS and produce a widen result.
15725   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15726   // => <2 x i64> <ae|cg>
15727   //
15728   // In other word, to have all the results, we need to perform two PMULxD:
15729   // 1. one with the even values.
15730   // 2. one with the odd values.
15731   // To achieve #2, with need to place the odd values at an even position.
15732   //
15733   // Place the odd value at an even position (basically, shift all values 1
15734   // step to the left):
15735   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15736   // <a|b|c|d> => <b|undef|d|undef>
15737   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15738   // <e|f|g|h> => <f|undef|h|undef>
15739   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15740
15741   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15742   // ints.
15743   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15744   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15745   unsigned Opcode =
15746       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15747   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15748   // => <2 x i64> <ae|cg>
15749   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15750                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15751   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15752   // => <2 x i64> <bf|dh>
15753   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15754                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15755
15756   // Shuffle it back into the right order.
15757   SDValue Highs, Lows;
15758   if (VT == MVT::v8i32) {
15759     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15760     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15761     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15762     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15763   } else {
15764     const int HighMask[] = {1, 5, 3, 7};
15765     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15766     const int LowMask[] = {1, 4, 2, 6};
15767     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15768   }
15769
15770   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15771   // unsigned multiply.
15772   if (IsSigned && !Subtarget->hasSSE41()) {
15773     SDValue ShAmt =
15774         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15775     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15776                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15777     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15778                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15779
15780     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15781     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15782   }
15783
15784   // The first result of MUL_LOHI is actually the low value, followed by the
15785   // high value.
15786   SDValue Ops[] = {Lows, Highs};
15787   return DAG.getMergeValues(Ops, dl);
15788 }
15789
15790 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15791                                          const X86Subtarget *Subtarget) {
15792   MVT VT = Op.getSimpleValueType();
15793   SDLoc dl(Op);
15794   SDValue R = Op.getOperand(0);
15795   SDValue Amt = Op.getOperand(1);
15796
15797   // Optimize shl/srl/sra with constant shift amount.
15798   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15799     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15800       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15801
15802       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15803           (Subtarget->hasInt256() &&
15804            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15805           (Subtarget->hasAVX512() &&
15806            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15807         if (Op.getOpcode() == ISD::SHL)
15808           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15809                                             DAG);
15810         if (Op.getOpcode() == ISD::SRL)
15811           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15812                                             DAG);
15813         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15814           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15815                                             DAG);
15816       }
15817
15818       if (VT == MVT::v16i8) {
15819         if (Op.getOpcode() == ISD::SHL) {
15820           // Make a large shift.
15821           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15822                                                    MVT::v8i16, R, ShiftAmt,
15823                                                    DAG);
15824           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15825           // Zero out the rightmost bits.
15826           SmallVector<SDValue, 16> V(16,
15827                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15828                                                      MVT::i8));
15829           return DAG.getNode(ISD::AND, dl, VT, SHL,
15830                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15831         }
15832         if (Op.getOpcode() == ISD::SRL) {
15833           // Make a large shift.
15834           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15835                                                    MVT::v8i16, R, ShiftAmt,
15836                                                    DAG);
15837           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15838           // Zero out the leftmost bits.
15839           SmallVector<SDValue, 16> V(16,
15840                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15841                                                      MVT::i8));
15842           return DAG.getNode(ISD::AND, dl, VT, SRL,
15843                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15844         }
15845         if (Op.getOpcode() == ISD::SRA) {
15846           if (ShiftAmt == 7) {
15847             // R s>> 7  ===  R s< 0
15848             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15849             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15850           }
15851
15852           // R s>> a === ((R u>> a) ^ m) - m
15853           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15854           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15855                                                          MVT::i8));
15856           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15857           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15858           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15859           return Res;
15860         }
15861         llvm_unreachable("Unknown shift opcode.");
15862       }
15863
15864       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15865         if (Op.getOpcode() == ISD::SHL) {
15866           // Make a large shift.
15867           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15868                                                    MVT::v16i16, R, ShiftAmt,
15869                                                    DAG);
15870           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15871           // Zero out the rightmost bits.
15872           SmallVector<SDValue, 32> V(32,
15873                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15874                                                      MVT::i8));
15875           return DAG.getNode(ISD::AND, dl, VT, SHL,
15876                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15877         }
15878         if (Op.getOpcode() == ISD::SRL) {
15879           // Make a large shift.
15880           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15881                                                    MVT::v16i16, R, ShiftAmt,
15882                                                    DAG);
15883           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15884           // Zero out the leftmost bits.
15885           SmallVector<SDValue, 32> V(32,
15886                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15887                                                      MVT::i8));
15888           return DAG.getNode(ISD::AND, dl, VT, SRL,
15889                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15890         }
15891         if (Op.getOpcode() == ISD::SRA) {
15892           if (ShiftAmt == 7) {
15893             // R s>> 7  ===  R s< 0
15894             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15895             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15896           }
15897
15898           // R s>> a === ((R u>> a) ^ m) - m
15899           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15900           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15901                                                          MVT::i8));
15902           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15903           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15904           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15905           return Res;
15906         }
15907         llvm_unreachable("Unknown shift opcode.");
15908       }
15909     }
15910   }
15911
15912   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15913   if (!Subtarget->is64Bit() &&
15914       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15915       Amt.getOpcode() == ISD::BITCAST &&
15916       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15917     Amt = Amt.getOperand(0);
15918     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15919                      VT.getVectorNumElements();
15920     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15921     uint64_t ShiftAmt = 0;
15922     for (unsigned i = 0; i != Ratio; ++i) {
15923       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15924       if (!C)
15925         return SDValue();
15926       // 6 == Log2(64)
15927       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15928     }
15929     // Check remaining shift amounts.
15930     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15931       uint64_t ShAmt = 0;
15932       for (unsigned j = 0; j != Ratio; ++j) {
15933         ConstantSDNode *C =
15934           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15935         if (!C)
15936           return SDValue();
15937         // 6 == Log2(64)
15938         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15939       }
15940       if (ShAmt != ShiftAmt)
15941         return SDValue();
15942     }
15943     switch (Op.getOpcode()) {
15944     default:
15945       llvm_unreachable("Unknown shift opcode!");
15946     case ISD::SHL:
15947       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15948                                         DAG);
15949     case ISD::SRL:
15950       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15951                                         DAG);
15952     case ISD::SRA:
15953       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15954                                         DAG);
15955     }
15956   }
15957
15958   return SDValue();
15959 }
15960
15961 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15962                                         const X86Subtarget* Subtarget) {
15963   MVT VT = Op.getSimpleValueType();
15964   SDLoc dl(Op);
15965   SDValue R = Op.getOperand(0);
15966   SDValue Amt = Op.getOperand(1);
15967
15968   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15969       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15970       (Subtarget->hasInt256() &&
15971        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15972         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15973        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15974     SDValue BaseShAmt;
15975     EVT EltVT = VT.getVectorElementType();
15976
15977     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15978       unsigned NumElts = VT.getVectorNumElements();
15979       unsigned i, j;
15980       for (i = 0; i != NumElts; ++i) {
15981         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15982           continue;
15983         break;
15984       }
15985       for (j = i; j != NumElts; ++j) {
15986         SDValue Arg = Amt.getOperand(j);
15987         if (Arg.getOpcode() == ISD::UNDEF) continue;
15988         if (Arg != Amt.getOperand(i))
15989           break;
15990       }
15991       if (i != NumElts && j == NumElts)
15992         BaseShAmt = Amt.getOperand(i);
15993     } else {
15994       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15995         Amt = Amt.getOperand(0);
15996       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15997                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15998         SDValue InVec = Amt.getOperand(0);
15999         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16000           unsigned NumElts = InVec.getValueType().getVectorNumElements();
16001           unsigned i = 0;
16002           for (; i != NumElts; ++i) {
16003             SDValue Arg = InVec.getOperand(i);
16004             if (Arg.getOpcode() == ISD::UNDEF) continue;
16005             BaseShAmt = Arg;
16006             break;
16007           }
16008         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16009            if (ConstantSDNode *C =
16010                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16011              unsigned SplatIdx =
16012                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16013              if (C->getZExtValue() == SplatIdx)
16014                BaseShAmt = InVec.getOperand(1);
16015            }
16016         }
16017         if (!BaseShAmt.getNode())
16018           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16019                                   DAG.getIntPtrConstant(0));
16020       }
16021     }
16022
16023     if (BaseShAmt.getNode()) {
16024       if (EltVT.bitsGT(MVT::i32))
16025         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16026       else if (EltVT.bitsLT(MVT::i32))
16027         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16028
16029       switch (Op.getOpcode()) {
16030       default:
16031         llvm_unreachable("Unknown shift opcode!");
16032       case ISD::SHL:
16033         switch (VT.SimpleTy) {
16034         default: return SDValue();
16035         case MVT::v2i64:
16036         case MVT::v4i32:
16037         case MVT::v8i16:
16038         case MVT::v4i64:
16039         case MVT::v8i32:
16040         case MVT::v16i16:
16041         case MVT::v16i32:
16042         case MVT::v8i64:
16043           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16044         }
16045       case ISD::SRA:
16046         switch (VT.SimpleTy) {
16047         default: return SDValue();
16048         case MVT::v4i32:
16049         case MVT::v8i16:
16050         case MVT::v8i32:
16051         case MVT::v16i16:
16052         case MVT::v16i32:
16053         case MVT::v8i64:
16054           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16055         }
16056       case ISD::SRL:
16057         switch (VT.SimpleTy) {
16058         default: return SDValue();
16059         case MVT::v2i64:
16060         case MVT::v4i32:
16061         case MVT::v8i16:
16062         case MVT::v4i64:
16063         case MVT::v8i32:
16064         case MVT::v16i16:
16065         case MVT::v16i32:
16066         case MVT::v8i64:
16067           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16068         }
16069       }
16070     }
16071   }
16072
16073   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16074   if (!Subtarget->is64Bit() &&
16075       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16076       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16077       Amt.getOpcode() == ISD::BITCAST &&
16078       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16079     Amt = Amt.getOperand(0);
16080     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16081                      VT.getVectorNumElements();
16082     std::vector<SDValue> Vals(Ratio);
16083     for (unsigned i = 0; i != Ratio; ++i)
16084       Vals[i] = Amt.getOperand(i);
16085     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16086       for (unsigned j = 0; j != Ratio; ++j)
16087         if (Vals[j] != Amt.getOperand(i + j))
16088           return SDValue();
16089     }
16090     switch (Op.getOpcode()) {
16091     default:
16092       llvm_unreachable("Unknown shift opcode!");
16093     case ISD::SHL:
16094       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16095     case ISD::SRL:
16096       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16097     case ISD::SRA:
16098       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16099     }
16100   }
16101
16102   return SDValue();
16103 }
16104
16105 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16106                           SelectionDAG &DAG) {
16107   MVT VT = Op.getSimpleValueType();
16108   SDLoc dl(Op);
16109   SDValue R = Op.getOperand(0);
16110   SDValue Amt = Op.getOperand(1);
16111   SDValue V;
16112
16113   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16114   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16115
16116   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16117   if (V.getNode())
16118     return V;
16119
16120   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16121   if (V.getNode())
16122       return V;
16123
16124   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16125     return Op;
16126   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16127   if (Subtarget->hasInt256()) {
16128     if (Op.getOpcode() == ISD::SRL &&
16129         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16130          VT == MVT::v4i64 || VT == MVT::v8i32))
16131       return Op;
16132     if (Op.getOpcode() == ISD::SHL &&
16133         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16134          VT == MVT::v4i64 || VT == MVT::v8i32))
16135       return Op;
16136     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16137       return Op;
16138   }
16139
16140   // If possible, lower this packed shift into a vector multiply instead of
16141   // expanding it into a sequence of scalar shifts.
16142   // Do this only if the vector shift count is a constant build_vector.
16143   if (Op.getOpcode() == ISD::SHL && 
16144       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16145        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16146       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16147     SmallVector<SDValue, 8> Elts;
16148     EVT SVT = VT.getScalarType();
16149     unsigned SVTBits = SVT.getSizeInBits();
16150     const APInt &One = APInt(SVTBits, 1);
16151     unsigned NumElems = VT.getVectorNumElements();
16152
16153     for (unsigned i=0; i !=NumElems; ++i) {
16154       SDValue Op = Amt->getOperand(i);
16155       if (Op->getOpcode() == ISD::UNDEF) {
16156         Elts.push_back(Op);
16157         continue;
16158       }
16159
16160       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16161       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16162       uint64_t ShAmt = C.getZExtValue();
16163       if (ShAmt >= SVTBits) {
16164         Elts.push_back(DAG.getUNDEF(SVT));
16165         continue;
16166       }
16167       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16168     }
16169     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16170     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16171   }
16172
16173   // Lower SHL with variable shift amount.
16174   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16175     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16176
16177     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16178     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16179     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16180     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16181   }
16182
16183   // If possible, lower this shift as a sequence of two shifts by
16184   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16185   // Example:
16186   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16187   //
16188   // Could be rewritten as:
16189   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16190   //
16191   // The advantage is that the two shifts from the example would be
16192   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16193   // the vector shift into four scalar shifts plus four pairs of vector
16194   // insert/extract.
16195   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16196       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16197     unsigned TargetOpcode = X86ISD::MOVSS;
16198     bool CanBeSimplified;
16199     // The splat value for the first packed shift (the 'X' from the example).
16200     SDValue Amt1 = Amt->getOperand(0);
16201     // The splat value for the second packed shift (the 'Y' from the example).
16202     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16203                                         Amt->getOperand(2);
16204
16205     // See if it is possible to replace this node with a sequence of
16206     // two shifts followed by a MOVSS/MOVSD
16207     if (VT == MVT::v4i32) {
16208       // Check if it is legal to use a MOVSS.
16209       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16210                         Amt2 == Amt->getOperand(3);
16211       if (!CanBeSimplified) {
16212         // Otherwise, check if we can still simplify this node using a MOVSD.
16213         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16214                           Amt->getOperand(2) == Amt->getOperand(3);
16215         TargetOpcode = X86ISD::MOVSD;
16216         Amt2 = Amt->getOperand(2);
16217       }
16218     } else {
16219       // Do similar checks for the case where the machine value type
16220       // is MVT::v8i16.
16221       CanBeSimplified = Amt1 == Amt->getOperand(1);
16222       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16223         CanBeSimplified = Amt2 == Amt->getOperand(i);
16224
16225       if (!CanBeSimplified) {
16226         TargetOpcode = X86ISD::MOVSD;
16227         CanBeSimplified = true;
16228         Amt2 = Amt->getOperand(4);
16229         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16230           CanBeSimplified = Amt1 == Amt->getOperand(i);
16231         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16232           CanBeSimplified = Amt2 == Amt->getOperand(j);
16233       }
16234     }
16235     
16236     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16237         isa<ConstantSDNode>(Amt2)) {
16238       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16239       EVT CastVT = MVT::v4i32;
16240       SDValue Splat1 = 
16241         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16242       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16243       SDValue Splat2 = 
16244         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16245       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16246       if (TargetOpcode == X86ISD::MOVSD)
16247         CastVT = MVT::v2i64;
16248       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16249       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16250       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16251                                             BitCast1, DAG);
16252       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16253     }
16254   }
16255
16256   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16257     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16258
16259     // a = a << 5;
16260     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16261     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16262
16263     // Turn 'a' into a mask suitable for VSELECT
16264     SDValue VSelM = DAG.getConstant(0x80, VT);
16265     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16266     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16267
16268     SDValue CM1 = DAG.getConstant(0x0f, VT);
16269     SDValue CM2 = DAG.getConstant(0x3f, VT);
16270
16271     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16272     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16273     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16274     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16275     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16276
16277     // a += a
16278     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16279     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16280     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16281
16282     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16283     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16284     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16285     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16286     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16287
16288     // a += a
16289     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16290     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16291     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16292
16293     // return VSELECT(r, r+r, a);
16294     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16295                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16296     return R;
16297   }
16298
16299   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16300   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16301   // solution better.
16302   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16303     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16304     unsigned ExtOpc =
16305         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16306     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16307     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16308     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16309                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16310     }
16311
16312   // Decompose 256-bit shifts into smaller 128-bit shifts.
16313   if (VT.is256BitVector()) {
16314     unsigned NumElems = VT.getVectorNumElements();
16315     MVT EltVT = VT.getVectorElementType();
16316     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16317
16318     // Extract the two vectors
16319     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16320     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16321
16322     // Recreate the shift amount vectors
16323     SDValue Amt1, Amt2;
16324     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16325       // Constant shift amount
16326       SmallVector<SDValue, 4> Amt1Csts;
16327       SmallVector<SDValue, 4> Amt2Csts;
16328       for (unsigned i = 0; i != NumElems/2; ++i)
16329         Amt1Csts.push_back(Amt->getOperand(i));
16330       for (unsigned i = NumElems/2; i != NumElems; ++i)
16331         Amt2Csts.push_back(Amt->getOperand(i));
16332
16333       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16334       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16335     } else {
16336       // Variable shift amount
16337       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16338       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16339     }
16340
16341     // Issue new vector shifts for the smaller types
16342     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16343     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16344
16345     // Concatenate the result back
16346     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16347   }
16348
16349   return SDValue();
16350 }
16351
16352 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16353   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16354   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16355   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16356   // has only one use.
16357   SDNode *N = Op.getNode();
16358   SDValue LHS = N->getOperand(0);
16359   SDValue RHS = N->getOperand(1);
16360   unsigned BaseOp = 0;
16361   unsigned Cond = 0;
16362   SDLoc DL(Op);
16363   switch (Op.getOpcode()) {
16364   default: llvm_unreachable("Unknown ovf instruction!");
16365   case ISD::SADDO:
16366     // A subtract of one will be selected as a INC. Note that INC doesn't
16367     // set CF, so we can't do this for UADDO.
16368     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16369       if (C->isOne()) {
16370         BaseOp = X86ISD::INC;
16371         Cond = X86::COND_O;
16372         break;
16373       }
16374     BaseOp = X86ISD::ADD;
16375     Cond = X86::COND_O;
16376     break;
16377   case ISD::UADDO:
16378     BaseOp = X86ISD::ADD;
16379     Cond = X86::COND_B;
16380     break;
16381   case ISD::SSUBO:
16382     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16383     // set CF, so we can't do this for USUBO.
16384     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16385       if (C->isOne()) {
16386         BaseOp = X86ISD::DEC;
16387         Cond = X86::COND_O;
16388         break;
16389       }
16390     BaseOp = X86ISD::SUB;
16391     Cond = X86::COND_O;
16392     break;
16393   case ISD::USUBO:
16394     BaseOp = X86ISD::SUB;
16395     Cond = X86::COND_B;
16396     break;
16397   case ISD::SMULO:
16398     BaseOp = X86ISD::SMUL;
16399     Cond = X86::COND_O;
16400     break;
16401   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16402     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16403                                  MVT::i32);
16404     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16405
16406     SDValue SetCC =
16407       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16408                   DAG.getConstant(X86::COND_O, MVT::i32),
16409                   SDValue(Sum.getNode(), 2));
16410
16411     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16412   }
16413   }
16414
16415   // Also sets EFLAGS.
16416   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16417   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16418
16419   SDValue SetCC =
16420     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16421                 DAG.getConstant(Cond, MVT::i32),
16422                 SDValue(Sum.getNode(), 1));
16423
16424   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16425 }
16426
16427 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16428                                                   SelectionDAG &DAG) const {
16429   SDLoc dl(Op);
16430   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16431   MVT VT = Op.getSimpleValueType();
16432
16433   if (!Subtarget->hasSSE2() || !VT.isVector())
16434     return SDValue();
16435
16436   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16437                       ExtraVT.getScalarType().getSizeInBits();
16438
16439   switch (VT.SimpleTy) {
16440     default: return SDValue();
16441     case MVT::v8i32:
16442     case MVT::v16i16:
16443       if (!Subtarget->hasFp256())
16444         return SDValue();
16445       if (!Subtarget->hasInt256()) {
16446         // needs to be split
16447         unsigned NumElems = VT.getVectorNumElements();
16448
16449         // Extract the LHS vectors
16450         SDValue LHS = Op.getOperand(0);
16451         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16452         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16453
16454         MVT EltVT = VT.getVectorElementType();
16455         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16456
16457         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16458         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16459         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16460                                    ExtraNumElems/2);
16461         SDValue Extra = DAG.getValueType(ExtraVT);
16462
16463         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16464         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16465
16466         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16467       }
16468       // fall through
16469     case MVT::v4i32:
16470     case MVT::v8i16: {
16471       SDValue Op0 = Op.getOperand(0);
16472       SDValue Op00 = Op0.getOperand(0);
16473       SDValue Tmp1;
16474       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16475       if (Op0.getOpcode() == ISD::BITCAST &&
16476           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16477         // (sext (vzext x)) -> (vsext x)
16478         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16479         if (Tmp1.getNode()) {
16480           EVT ExtraEltVT = ExtraVT.getVectorElementType();
16481           // This folding is only valid when the in-reg type is a vector of i8,
16482           // i16, or i32.
16483           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16484               ExtraEltVT == MVT::i32) {
16485             SDValue Tmp1Op0 = Tmp1.getOperand(0);
16486             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16487                    "This optimization is invalid without a VZEXT.");
16488             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16489           }
16490           Op0 = Tmp1;
16491         }
16492       }
16493
16494       // If the above didn't work, then just use Shift-Left + Shift-Right.
16495       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16496                                         DAG);
16497       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16498                                         DAG);
16499     }
16500   }
16501 }
16502
16503 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16504                                  SelectionDAG &DAG) {
16505   SDLoc dl(Op);
16506   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16507     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16508   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16509     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16510
16511   // The only fence that needs an instruction is a sequentially-consistent
16512   // cross-thread fence.
16513   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16514     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16515     // no-sse2). There isn't any reason to disable it if the target processor
16516     // supports it.
16517     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16518       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16519
16520     SDValue Chain = Op.getOperand(0);
16521     SDValue Zero = DAG.getConstant(0, MVT::i32);
16522     SDValue Ops[] = {
16523       DAG.getRegister(X86::ESP, MVT::i32), // Base
16524       DAG.getTargetConstant(1, MVT::i8),   // Scale
16525       DAG.getRegister(0, MVT::i32),        // Index
16526       DAG.getTargetConstant(0, MVT::i32),  // Disp
16527       DAG.getRegister(0, MVT::i32),        // Segment.
16528       Zero,
16529       Chain
16530     };
16531     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16532     return SDValue(Res, 0);
16533   }
16534
16535   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16536   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16537 }
16538
16539 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16540                              SelectionDAG &DAG) {
16541   MVT T = Op.getSimpleValueType();
16542   SDLoc DL(Op);
16543   unsigned Reg = 0;
16544   unsigned size = 0;
16545   switch(T.SimpleTy) {
16546   default: llvm_unreachable("Invalid value type!");
16547   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16548   case MVT::i16: Reg = X86::AX;  size = 2; break;
16549   case MVT::i32: Reg = X86::EAX; size = 4; break;
16550   case MVT::i64:
16551     assert(Subtarget->is64Bit() && "Node not type legal!");
16552     Reg = X86::RAX; size = 8;
16553     break;
16554   }
16555   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16556                                   Op.getOperand(2), SDValue());
16557   SDValue Ops[] = { cpIn.getValue(0),
16558                     Op.getOperand(1),
16559                     Op.getOperand(3),
16560                     DAG.getTargetConstant(size, MVT::i8),
16561                     cpIn.getValue(1) };
16562   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16563   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16564   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16565                                            Ops, T, MMO);
16566
16567   SDValue cpOut =
16568     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16569   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16570                                       MVT::i32, cpOut.getValue(2));
16571   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16572                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16573
16574   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16575   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16576   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16577   return SDValue();
16578 }
16579
16580 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16581                             SelectionDAG &DAG) {
16582   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16583   MVT DstVT = Op.getSimpleValueType();
16584
16585   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16586     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16587     if (DstVT != MVT::f64)
16588       // This conversion needs to be expanded.
16589       return SDValue();
16590
16591     SDValue InVec = Op->getOperand(0);
16592     SDLoc dl(Op);
16593     unsigned NumElts = SrcVT.getVectorNumElements();
16594     EVT SVT = SrcVT.getVectorElementType();
16595
16596     // Widen the vector in input in the case of MVT::v2i32.
16597     // Example: from MVT::v2i32 to MVT::v4i32.
16598     SmallVector<SDValue, 16> Elts;
16599     for (unsigned i = 0, e = NumElts; i != e; ++i)
16600       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16601                                  DAG.getIntPtrConstant(i)));
16602
16603     // Explicitly mark the extra elements as Undef.
16604     SDValue Undef = DAG.getUNDEF(SVT);
16605     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16606       Elts.push_back(Undef);
16607
16608     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16609     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16610     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16611     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16612                        DAG.getIntPtrConstant(0));
16613   }
16614
16615   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16616          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16617   assert((DstVT == MVT::i64 ||
16618           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16619          "Unexpected custom BITCAST");
16620   // i64 <=> MMX conversions are Legal.
16621   if (SrcVT==MVT::i64 && DstVT.isVector())
16622     return Op;
16623   if (DstVT==MVT::i64 && SrcVT.isVector())
16624     return Op;
16625   // MMX <=> MMX conversions are Legal.
16626   if (SrcVT.isVector() && DstVT.isVector())
16627     return Op;
16628   // All other conversions need to be expanded.
16629   return SDValue();
16630 }
16631
16632 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16633   SDNode *Node = Op.getNode();
16634   SDLoc dl(Node);
16635   EVT T = Node->getValueType(0);
16636   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16637                               DAG.getConstant(0, T), Node->getOperand(2));
16638   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16639                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16640                        Node->getOperand(0),
16641                        Node->getOperand(1), negOp,
16642                        cast<AtomicSDNode>(Node)->getMemOperand(),
16643                        cast<AtomicSDNode>(Node)->getOrdering(),
16644                        cast<AtomicSDNode>(Node)->getSynchScope());
16645 }
16646
16647 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16648   SDNode *Node = Op.getNode();
16649   SDLoc dl(Node);
16650   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16651
16652   // Convert seq_cst store -> xchg
16653   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16654   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16655   //        (The only way to get a 16-byte store is cmpxchg16b)
16656   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16657   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16658       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16659     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16660                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16661                                  Node->getOperand(0),
16662                                  Node->getOperand(1), Node->getOperand(2),
16663                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16664                                  cast<AtomicSDNode>(Node)->getOrdering(),
16665                                  cast<AtomicSDNode>(Node)->getSynchScope());
16666     return Swap.getValue(1);
16667   }
16668   // Other atomic stores have a simple pattern.
16669   return Op;
16670 }
16671
16672 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16673   EVT VT = Op.getNode()->getSimpleValueType(0);
16674
16675   // Let legalize expand this if it isn't a legal type yet.
16676   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16677     return SDValue();
16678
16679   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16680
16681   unsigned Opc;
16682   bool ExtraOp = false;
16683   switch (Op.getOpcode()) {
16684   default: llvm_unreachable("Invalid code");
16685   case ISD::ADDC: Opc = X86ISD::ADD; break;
16686   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16687   case ISD::SUBC: Opc = X86ISD::SUB; break;
16688   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16689   }
16690
16691   if (!ExtraOp)
16692     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16693                        Op.getOperand(1));
16694   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16695                      Op.getOperand(1), Op.getOperand(2));
16696 }
16697
16698 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16699                             SelectionDAG &DAG) {
16700   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16701
16702   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16703   // which returns the values as { float, float } (in XMM0) or
16704   // { double, double } (which is returned in XMM0, XMM1).
16705   SDLoc dl(Op);
16706   SDValue Arg = Op.getOperand(0);
16707   EVT ArgVT = Arg.getValueType();
16708   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16709
16710   TargetLowering::ArgListTy Args;
16711   TargetLowering::ArgListEntry Entry;
16712
16713   Entry.Node = Arg;
16714   Entry.Ty = ArgTy;
16715   Entry.isSExt = false;
16716   Entry.isZExt = false;
16717   Args.push_back(Entry);
16718
16719   bool isF64 = ArgVT == MVT::f64;
16720   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16721   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16722   // the results are returned via SRet in memory.
16723   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16724   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16725   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16726
16727   Type *RetTy = isF64
16728     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16729     : (Type*)VectorType::get(ArgTy, 4);
16730
16731   TargetLowering::CallLoweringInfo CLI(DAG);
16732   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16733     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16734
16735   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16736
16737   if (isF64)
16738     // Returned in xmm0 and xmm1.
16739     return CallResult.first;
16740
16741   // Returned in bits 0:31 and 32:64 xmm0.
16742   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16743                                CallResult.first, DAG.getIntPtrConstant(0));
16744   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16745                                CallResult.first, DAG.getIntPtrConstant(1));
16746   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16747   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16748 }
16749
16750 /// LowerOperation - Provide custom lowering hooks for some operations.
16751 ///
16752 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16753   switch (Op.getOpcode()) {
16754   default: llvm_unreachable("Should not custom lower this!");
16755   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16756   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16757   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16758     return LowerCMP_SWAP(Op, Subtarget, DAG);
16759   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16760   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16761   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16762   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16763   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16764   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16765   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16766   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16767   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16768   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16769   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16770   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16771   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16772   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16773   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16774   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16775   case ISD::SHL_PARTS:
16776   case ISD::SRA_PARTS:
16777   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16778   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16779   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16780   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16781   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16782   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16783   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16784   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16785   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16786   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16787   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16788   case ISD::FABS:               return LowerFABS(Op, DAG);
16789   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16790   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16791   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16792   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16793   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16794   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16795   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16796   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16797   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16798   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16799   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16800   case ISD::INTRINSIC_VOID:
16801   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16802   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16803   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16804   case ISD::FRAME_TO_ARGS_OFFSET:
16805                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16806   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16807   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16808   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16809   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16810   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16811   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16812   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16813   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16814   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16815   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16816   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16817   case ISD::UMUL_LOHI:
16818   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16819   case ISD::SRA:
16820   case ISD::SRL:
16821   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16822   case ISD::SADDO:
16823   case ISD::UADDO:
16824   case ISD::SSUBO:
16825   case ISD::USUBO:
16826   case ISD::SMULO:
16827   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16828   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16829   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16830   case ISD::ADDC:
16831   case ISD::ADDE:
16832   case ISD::SUBC:
16833   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16834   case ISD::ADD:                return LowerADD(Op, DAG);
16835   case ISD::SUB:                return LowerSUB(Op, DAG);
16836   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16837   }
16838 }
16839
16840 static void ReplaceATOMIC_LOAD(SDNode *Node,
16841                                SmallVectorImpl<SDValue> &Results,
16842                                SelectionDAG &DAG) {
16843   SDLoc dl(Node);
16844   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16845
16846   // Convert wide load -> cmpxchg8b/cmpxchg16b
16847   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16848   //        (The only way to get a 16-byte load is cmpxchg16b)
16849   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16850   SDValue Zero = DAG.getConstant(0, VT);
16851   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16852   SDValue Swap =
16853       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16854                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16855                            cast<AtomicSDNode>(Node)->getMemOperand(),
16856                            cast<AtomicSDNode>(Node)->getOrdering(),
16857                            cast<AtomicSDNode>(Node)->getOrdering(),
16858                            cast<AtomicSDNode>(Node)->getSynchScope());
16859   Results.push_back(Swap.getValue(0));
16860   Results.push_back(Swap.getValue(2));
16861 }
16862
16863 /// ReplaceNodeResults - Replace a node with an illegal result type
16864 /// with a new node built out of custom code.
16865 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16866                                            SmallVectorImpl<SDValue>&Results,
16867                                            SelectionDAG &DAG) const {
16868   SDLoc dl(N);
16869   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16870   switch (N->getOpcode()) {
16871   default:
16872     llvm_unreachable("Do not know how to custom type legalize this operation!");
16873   case ISD::SIGN_EXTEND_INREG:
16874   case ISD::ADDC:
16875   case ISD::ADDE:
16876   case ISD::SUBC:
16877   case ISD::SUBE:
16878     // We don't want to expand or promote these.
16879     return;
16880   case ISD::SDIV:
16881   case ISD::UDIV:
16882   case ISD::SREM:
16883   case ISD::UREM:
16884   case ISD::SDIVREM:
16885   case ISD::UDIVREM: {
16886     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16887     Results.push_back(V);
16888     return;
16889   }
16890   case ISD::FP_TO_SINT:
16891   case ISD::FP_TO_UINT: {
16892     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16893
16894     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16895       return;
16896
16897     std::pair<SDValue,SDValue> Vals =
16898         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16899     SDValue FIST = Vals.first, StackSlot = Vals.second;
16900     if (FIST.getNode()) {
16901       EVT VT = N->getValueType(0);
16902       // Return a load from the stack slot.
16903       if (StackSlot.getNode())
16904         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16905                                       MachinePointerInfo(),
16906                                       false, false, false, 0));
16907       else
16908         Results.push_back(FIST);
16909     }
16910     return;
16911   }
16912   case ISD::UINT_TO_FP: {
16913     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16914     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16915         N->getValueType(0) != MVT::v2f32)
16916       return;
16917     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16918                                  N->getOperand(0));
16919     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16920                                      MVT::f64);
16921     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16922     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16923                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16924     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16925     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16926     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16927     return;
16928   }
16929   case ISD::FP_ROUND: {
16930     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16931         return;
16932     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16933     Results.push_back(V);
16934     return;
16935   }
16936   case ISD::INTRINSIC_W_CHAIN: {
16937     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16938     switch (IntNo) {
16939     default : llvm_unreachable("Do not know how to custom type "
16940                                "legalize this intrinsic operation!");
16941     case Intrinsic::x86_rdtsc:
16942       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16943                                      Results);
16944     case Intrinsic::x86_rdtscp:
16945       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16946                                      Results);
16947     case Intrinsic::x86_rdpmc:
16948       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16949     }
16950   }
16951   case ISD::READCYCLECOUNTER: {
16952     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16953                                    Results);
16954   }
16955   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16956     EVT T = N->getValueType(0);
16957     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16958     bool Regs64bit = T == MVT::i128;
16959     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16960     SDValue cpInL, cpInH;
16961     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16962                         DAG.getConstant(0, HalfT));
16963     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16964                         DAG.getConstant(1, HalfT));
16965     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16966                              Regs64bit ? X86::RAX : X86::EAX,
16967                              cpInL, SDValue());
16968     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16969                              Regs64bit ? X86::RDX : X86::EDX,
16970                              cpInH, cpInL.getValue(1));
16971     SDValue swapInL, swapInH;
16972     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16973                           DAG.getConstant(0, HalfT));
16974     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16975                           DAG.getConstant(1, HalfT));
16976     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16977                                Regs64bit ? X86::RBX : X86::EBX,
16978                                swapInL, cpInH.getValue(1));
16979     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16980                                Regs64bit ? X86::RCX : X86::ECX,
16981                                swapInH, swapInL.getValue(1));
16982     SDValue Ops[] = { swapInH.getValue(0),
16983                       N->getOperand(1),
16984                       swapInH.getValue(1) };
16985     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16986     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16987     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16988                                   X86ISD::LCMPXCHG8_DAG;
16989     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16990     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16991                                         Regs64bit ? X86::RAX : X86::EAX,
16992                                         HalfT, Result.getValue(1));
16993     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16994                                         Regs64bit ? X86::RDX : X86::EDX,
16995                                         HalfT, cpOutL.getValue(2));
16996     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16997
16998     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16999                                         MVT::i32, cpOutH.getValue(2));
17000     SDValue Success =
17001         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17002                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17003     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17004
17005     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17006     Results.push_back(Success);
17007     Results.push_back(EFLAGS.getValue(1));
17008     return;
17009   }
17010   case ISD::ATOMIC_SWAP:
17011   case ISD::ATOMIC_LOAD_ADD:
17012   case ISD::ATOMIC_LOAD_SUB:
17013   case ISD::ATOMIC_LOAD_AND:
17014   case ISD::ATOMIC_LOAD_OR:
17015   case ISD::ATOMIC_LOAD_XOR:
17016   case ISD::ATOMIC_LOAD_NAND:
17017   case ISD::ATOMIC_LOAD_MIN:
17018   case ISD::ATOMIC_LOAD_MAX:
17019   case ISD::ATOMIC_LOAD_UMIN:
17020   case ISD::ATOMIC_LOAD_UMAX:
17021     // Delegate to generic TypeLegalization. Situations we can really handle
17022     // should have already been dealt with by X86AtomicExpandPass.cpp.
17023     break;
17024   case ISD::ATOMIC_LOAD: {
17025     ReplaceATOMIC_LOAD(N, Results, DAG);
17026     return;
17027   }
17028   case ISD::BITCAST: {
17029     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17030     EVT DstVT = N->getValueType(0);
17031     EVT SrcVT = N->getOperand(0)->getValueType(0);
17032
17033     if (SrcVT != MVT::f64 ||
17034         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17035       return;
17036
17037     unsigned NumElts = DstVT.getVectorNumElements();
17038     EVT SVT = DstVT.getVectorElementType();
17039     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17040     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17041                                    MVT::v2f64, N->getOperand(0));
17042     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17043
17044     if (ExperimentalVectorWideningLegalization) {
17045       // If we are legalizing vectors by widening, we already have the desired
17046       // legal vector type, just return it.
17047       Results.push_back(ToVecInt);
17048       return;
17049     }
17050
17051     SmallVector<SDValue, 8> Elts;
17052     for (unsigned i = 0, e = NumElts; i != e; ++i)
17053       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17054                                    ToVecInt, DAG.getIntPtrConstant(i)));
17055
17056     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17057   }
17058   }
17059 }
17060
17061 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17062   switch (Opcode) {
17063   default: return nullptr;
17064   case X86ISD::BSF:                return "X86ISD::BSF";
17065   case X86ISD::BSR:                return "X86ISD::BSR";
17066   case X86ISD::SHLD:               return "X86ISD::SHLD";
17067   case X86ISD::SHRD:               return "X86ISD::SHRD";
17068   case X86ISD::FAND:               return "X86ISD::FAND";
17069   case X86ISD::FANDN:              return "X86ISD::FANDN";
17070   case X86ISD::FOR:                return "X86ISD::FOR";
17071   case X86ISD::FXOR:               return "X86ISD::FXOR";
17072   case X86ISD::FSRL:               return "X86ISD::FSRL";
17073   case X86ISD::FILD:               return "X86ISD::FILD";
17074   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17075   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17076   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17077   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17078   case X86ISD::FLD:                return "X86ISD::FLD";
17079   case X86ISD::FST:                return "X86ISD::FST";
17080   case X86ISD::CALL:               return "X86ISD::CALL";
17081   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17082   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17083   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17084   case X86ISD::BT:                 return "X86ISD::BT";
17085   case X86ISD::CMP:                return "X86ISD::CMP";
17086   case X86ISD::COMI:               return "X86ISD::COMI";
17087   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17088   case X86ISD::CMPM:               return "X86ISD::CMPM";
17089   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17090   case X86ISD::SETCC:              return "X86ISD::SETCC";
17091   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17092   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17093   case X86ISD::CMOV:               return "X86ISD::CMOV";
17094   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17095   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17096   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17097   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17098   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17099   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17100   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17101   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17102   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17103   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17104   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17105   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17106   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17107   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17108   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17109   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
17110   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17111   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17112   case X86ISD::HADD:               return "X86ISD::HADD";
17113   case X86ISD::HSUB:               return "X86ISD::HSUB";
17114   case X86ISD::FHADD:              return "X86ISD::FHADD";
17115   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17116   case X86ISD::UMAX:               return "X86ISD::UMAX";
17117   case X86ISD::UMIN:               return "X86ISD::UMIN";
17118   case X86ISD::SMAX:               return "X86ISD::SMAX";
17119   case X86ISD::SMIN:               return "X86ISD::SMIN";
17120   case X86ISD::FMAX:               return "X86ISD::FMAX";
17121   case X86ISD::FMIN:               return "X86ISD::FMIN";
17122   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17123   case X86ISD::FMINC:              return "X86ISD::FMINC";
17124   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17125   case X86ISD::FRCP:               return "X86ISD::FRCP";
17126   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17127   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17128   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17129   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17130   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17131   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17132   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17133   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17134   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17135   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17136   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17137   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17138   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17139   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17140   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17141   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17142   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17143   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17144   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17145   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17146   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17147   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17148   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17149   case X86ISD::VSHL:               return "X86ISD::VSHL";
17150   case X86ISD::VSRL:               return "X86ISD::VSRL";
17151   case X86ISD::VSRA:               return "X86ISD::VSRA";
17152   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17153   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17154   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17155   case X86ISD::CMPP:               return "X86ISD::CMPP";
17156   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17157   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17158   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17159   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17160   case X86ISD::ADD:                return "X86ISD::ADD";
17161   case X86ISD::SUB:                return "X86ISD::SUB";
17162   case X86ISD::ADC:                return "X86ISD::ADC";
17163   case X86ISD::SBB:                return "X86ISD::SBB";
17164   case X86ISD::SMUL:               return "X86ISD::SMUL";
17165   case X86ISD::UMUL:               return "X86ISD::UMUL";
17166   case X86ISD::INC:                return "X86ISD::INC";
17167   case X86ISD::DEC:                return "X86ISD::DEC";
17168   case X86ISD::OR:                 return "X86ISD::OR";
17169   case X86ISD::XOR:                return "X86ISD::XOR";
17170   case X86ISD::AND:                return "X86ISD::AND";
17171   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17172   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17173   case X86ISD::PTEST:              return "X86ISD::PTEST";
17174   case X86ISD::TESTP:              return "X86ISD::TESTP";
17175   case X86ISD::TESTM:              return "X86ISD::TESTM";
17176   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17177   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17178   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17179   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17180   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17181   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17182   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17183   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17184   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17185   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17186   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17187   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17188   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17189   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17190   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17191   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17192   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17193   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17194   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17195   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17196   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17197   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17198   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17199   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17200   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17201   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
17202   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17203   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17204   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17205   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17206   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17207   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17208   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17209   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17210   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17211   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17212   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17213   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17214   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17215   case X86ISD::SAHF:               return "X86ISD::SAHF";
17216   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17217   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17218   case X86ISD::FMADD:              return "X86ISD::FMADD";
17219   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17220   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17221   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17222   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17223   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17224   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17225   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17226   case X86ISD::XTEST:              return "X86ISD::XTEST";
17227   }
17228 }
17229
17230 // isLegalAddressingMode - Return true if the addressing mode represented
17231 // by AM is legal for this target, for a load/store of the specified type.
17232 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17233                                               Type *Ty) const {
17234   // X86 supports extremely general addressing modes.
17235   CodeModel::Model M = getTargetMachine().getCodeModel();
17236   Reloc::Model R = getTargetMachine().getRelocationModel();
17237
17238   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17239   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17240     return false;
17241
17242   if (AM.BaseGV) {
17243     unsigned GVFlags =
17244       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17245
17246     // If a reference to this global requires an extra load, we can't fold it.
17247     if (isGlobalStubReference(GVFlags))
17248       return false;
17249
17250     // If BaseGV requires a register for the PIC base, we cannot also have a
17251     // BaseReg specified.
17252     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17253       return false;
17254
17255     // If lower 4G is not available, then we must use rip-relative addressing.
17256     if ((M != CodeModel::Small || R != Reloc::Static) &&
17257         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17258       return false;
17259   }
17260
17261   switch (AM.Scale) {
17262   case 0:
17263   case 1:
17264   case 2:
17265   case 4:
17266   case 8:
17267     // These scales always work.
17268     break;
17269   case 3:
17270   case 5:
17271   case 9:
17272     // These scales are formed with basereg+scalereg.  Only accept if there is
17273     // no basereg yet.
17274     if (AM.HasBaseReg)
17275       return false;
17276     break;
17277   default:  // Other stuff never works.
17278     return false;
17279   }
17280
17281   return true;
17282 }
17283
17284 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17285   unsigned Bits = Ty->getScalarSizeInBits();
17286
17287   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17288   // particularly cheaper than those without.
17289   if (Bits == 8)
17290     return false;
17291
17292   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17293   // variable shifts just as cheap as scalar ones.
17294   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17295     return false;
17296
17297   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17298   // fully general vector.
17299   return true;
17300 }
17301
17302 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17303   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17304     return false;
17305   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17306   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17307   return NumBits1 > NumBits2;
17308 }
17309
17310 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17311   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17312     return false;
17313
17314   if (!isTypeLegal(EVT::getEVT(Ty1)))
17315     return false;
17316
17317   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17318
17319   // Assuming the caller doesn't have a zeroext or signext return parameter,
17320   // truncation all the way down to i1 is valid.
17321   return true;
17322 }
17323
17324 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17325   return isInt<32>(Imm);
17326 }
17327
17328 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17329   // Can also use sub to handle negated immediates.
17330   return isInt<32>(Imm);
17331 }
17332
17333 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17334   if (!VT1.isInteger() || !VT2.isInteger())
17335     return false;
17336   unsigned NumBits1 = VT1.getSizeInBits();
17337   unsigned NumBits2 = VT2.getSizeInBits();
17338   return NumBits1 > NumBits2;
17339 }
17340
17341 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17342   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17343   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17344 }
17345
17346 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17347   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17348   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17349 }
17350
17351 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17352   EVT VT1 = Val.getValueType();
17353   if (isZExtFree(VT1, VT2))
17354     return true;
17355
17356   if (Val.getOpcode() != ISD::LOAD)
17357     return false;
17358
17359   if (!VT1.isSimple() || !VT1.isInteger() ||
17360       !VT2.isSimple() || !VT2.isInteger())
17361     return false;
17362
17363   switch (VT1.getSimpleVT().SimpleTy) {
17364   default: break;
17365   case MVT::i8:
17366   case MVT::i16:
17367   case MVT::i32:
17368     // X86 has 8, 16, and 32-bit zero-extending loads.
17369     return true;
17370   }
17371
17372   return false;
17373 }
17374
17375 bool
17376 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17377   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17378     return false;
17379
17380   VT = VT.getScalarType();
17381
17382   if (!VT.isSimple())
17383     return false;
17384
17385   switch (VT.getSimpleVT().SimpleTy) {
17386   case MVT::f32:
17387   case MVT::f64:
17388     return true;
17389   default:
17390     break;
17391   }
17392
17393   return false;
17394 }
17395
17396 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17397   // i16 instructions are longer (0x66 prefix) and potentially slower.
17398   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17399 }
17400
17401 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17402 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17403 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17404 /// are assumed to be legal.
17405 bool
17406 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17407                                       EVT VT) const {
17408   if (!VT.isSimple())
17409     return false;
17410
17411   MVT SVT = VT.getSimpleVT();
17412
17413   // Very little shuffling can be done for 64-bit vectors right now.
17414   if (VT.getSizeInBits() == 64)
17415     return false;
17416
17417   // If this is a single-input shuffle with no 128 bit lane crossings we can
17418   // lower it into pshufb.
17419   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17420       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17421     bool isLegal = true;
17422     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17423       if (M[I] >= (int)SVT.getVectorNumElements() ||
17424           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17425         isLegal = false;
17426         break;
17427       }
17428     }
17429     if (isLegal)
17430       return true;
17431   }
17432
17433   // FIXME: blends, shifts.
17434   return (SVT.getVectorNumElements() == 2 ||
17435           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17436           isMOVLMask(M, SVT) ||
17437           isMOVHLPSMask(M, SVT) ||
17438           isSHUFPMask(M, SVT) ||
17439           isPSHUFDMask(M, SVT) ||
17440           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17441           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17442           isPALIGNRMask(M, SVT, Subtarget) ||
17443           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17444           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17445           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17446           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17447           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17448 }
17449
17450 bool
17451 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17452                                           EVT VT) const {
17453   if (!VT.isSimple())
17454     return false;
17455
17456   MVT SVT = VT.getSimpleVT();
17457   unsigned NumElts = SVT.getVectorNumElements();
17458   // FIXME: This collection of masks seems suspect.
17459   if (NumElts == 2)
17460     return true;
17461   if (NumElts == 4 && SVT.is128BitVector()) {
17462     return (isMOVLMask(Mask, SVT)  ||
17463             isCommutedMOVLMask(Mask, SVT, true) ||
17464             isSHUFPMask(Mask, SVT) ||
17465             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17466   }
17467   return false;
17468 }
17469
17470 //===----------------------------------------------------------------------===//
17471 //                           X86 Scheduler Hooks
17472 //===----------------------------------------------------------------------===//
17473
17474 /// Utility function to emit xbegin specifying the start of an RTM region.
17475 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17476                                      const TargetInstrInfo *TII) {
17477   DebugLoc DL = MI->getDebugLoc();
17478
17479   const BasicBlock *BB = MBB->getBasicBlock();
17480   MachineFunction::iterator I = MBB;
17481   ++I;
17482
17483   // For the v = xbegin(), we generate
17484   //
17485   // thisMBB:
17486   //  xbegin sinkMBB
17487   //
17488   // mainMBB:
17489   //  eax = -1
17490   //
17491   // sinkMBB:
17492   //  v = eax
17493
17494   MachineBasicBlock *thisMBB = MBB;
17495   MachineFunction *MF = MBB->getParent();
17496   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17497   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17498   MF->insert(I, mainMBB);
17499   MF->insert(I, sinkMBB);
17500
17501   // Transfer the remainder of BB and its successor edges to sinkMBB.
17502   sinkMBB->splice(sinkMBB->begin(), MBB,
17503                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17504   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17505
17506   // thisMBB:
17507   //  xbegin sinkMBB
17508   //  # fallthrough to mainMBB
17509   //  # abortion to sinkMBB
17510   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17511   thisMBB->addSuccessor(mainMBB);
17512   thisMBB->addSuccessor(sinkMBB);
17513
17514   // mainMBB:
17515   //  EAX = -1
17516   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17517   mainMBB->addSuccessor(sinkMBB);
17518
17519   // sinkMBB:
17520   // EAX is live into the sinkMBB
17521   sinkMBB->addLiveIn(X86::EAX);
17522   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17523           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17524     .addReg(X86::EAX);
17525
17526   MI->eraseFromParent();
17527   return sinkMBB;
17528 }
17529
17530 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17531 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17532 // in the .td file.
17533 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17534                                        const TargetInstrInfo *TII) {
17535   unsigned Opc;
17536   switch (MI->getOpcode()) {
17537   default: llvm_unreachable("illegal opcode!");
17538   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17539   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17540   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17541   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17542   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17543   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17544   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17545   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17546   }
17547
17548   DebugLoc dl = MI->getDebugLoc();
17549   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17550
17551   unsigned NumArgs = MI->getNumOperands();
17552   for (unsigned i = 1; i < NumArgs; ++i) {
17553     MachineOperand &Op = MI->getOperand(i);
17554     if (!(Op.isReg() && Op.isImplicit()))
17555       MIB.addOperand(Op);
17556   }
17557   if (MI->hasOneMemOperand())
17558     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17559
17560   BuildMI(*BB, MI, dl,
17561     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17562     .addReg(X86::XMM0);
17563
17564   MI->eraseFromParent();
17565   return BB;
17566 }
17567
17568 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17569 // defs in an instruction pattern
17570 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17571                                        const TargetInstrInfo *TII) {
17572   unsigned Opc;
17573   switch (MI->getOpcode()) {
17574   default: llvm_unreachable("illegal opcode!");
17575   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17576   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17577   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17578   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17579   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17580   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17581   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17582   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17583   }
17584
17585   DebugLoc dl = MI->getDebugLoc();
17586   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17587
17588   unsigned NumArgs = MI->getNumOperands(); // remove the results
17589   for (unsigned i = 1; i < NumArgs; ++i) {
17590     MachineOperand &Op = MI->getOperand(i);
17591     if (!(Op.isReg() && Op.isImplicit()))
17592       MIB.addOperand(Op);
17593   }
17594   if (MI->hasOneMemOperand())
17595     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17596
17597   BuildMI(*BB, MI, dl,
17598     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17599     .addReg(X86::ECX);
17600
17601   MI->eraseFromParent();
17602   return BB;
17603 }
17604
17605 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17606                                        const TargetInstrInfo *TII,
17607                                        const X86Subtarget* Subtarget) {
17608   DebugLoc dl = MI->getDebugLoc();
17609
17610   // Address into RAX/EAX, other two args into ECX, EDX.
17611   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17612   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17613   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17614   for (int i = 0; i < X86::AddrNumOperands; ++i)
17615     MIB.addOperand(MI->getOperand(i));
17616
17617   unsigned ValOps = X86::AddrNumOperands;
17618   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17619     .addReg(MI->getOperand(ValOps).getReg());
17620   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17621     .addReg(MI->getOperand(ValOps+1).getReg());
17622
17623   // The instruction doesn't actually take any operands though.
17624   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17625
17626   MI->eraseFromParent(); // The pseudo is gone now.
17627   return BB;
17628 }
17629
17630 MachineBasicBlock *
17631 X86TargetLowering::EmitVAARG64WithCustomInserter(
17632                    MachineInstr *MI,
17633                    MachineBasicBlock *MBB) const {
17634   // Emit va_arg instruction on X86-64.
17635
17636   // Operands to this pseudo-instruction:
17637   // 0  ) Output        : destination address (reg)
17638   // 1-5) Input         : va_list address (addr, i64mem)
17639   // 6  ) ArgSize       : Size (in bytes) of vararg type
17640   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17641   // 8  ) Align         : Alignment of type
17642   // 9  ) EFLAGS (implicit-def)
17643
17644   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17645   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17646
17647   unsigned DestReg = MI->getOperand(0).getReg();
17648   MachineOperand &Base = MI->getOperand(1);
17649   MachineOperand &Scale = MI->getOperand(2);
17650   MachineOperand &Index = MI->getOperand(3);
17651   MachineOperand &Disp = MI->getOperand(4);
17652   MachineOperand &Segment = MI->getOperand(5);
17653   unsigned ArgSize = MI->getOperand(6).getImm();
17654   unsigned ArgMode = MI->getOperand(7).getImm();
17655   unsigned Align = MI->getOperand(8).getImm();
17656
17657   // Memory Reference
17658   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17659   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17660   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17661
17662   // Machine Information
17663   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17664   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17665   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17666   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17667   DebugLoc DL = MI->getDebugLoc();
17668
17669   // struct va_list {
17670   //   i32   gp_offset
17671   //   i32   fp_offset
17672   //   i64   overflow_area (address)
17673   //   i64   reg_save_area (address)
17674   // }
17675   // sizeof(va_list) = 24
17676   // alignment(va_list) = 8
17677
17678   unsigned TotalNumIntRegs = 6;
17679   unsigned TotalNumXMMRegs = 8;
17680   bool UseGPOffset = (ArgMode == 1);
17681   bool UseFPOffset = (ArgMode == 2);
17682   unsigned MaxOffset = TotalNumIntRegs * 8 +
17683                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17684
17685   /* Align ArgSize to a multiple of 8 */
17686   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17687   bool NeedsAlign = (Align > 8);
17688
17689   MachineBasicBlock *thisMBB = MBB;
17690   MachineBasicBlock *overflowMBB;
17691   MachineBasicBlock *offsetMBB;
17692   MachineBasicBlock *endMBB;
17693
17694   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17695   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17696   unsigned OffsetReg = 0;
17697
17698   if (!UseGPOffset && !UseFPOffset) {
17699     // If we only pull from the overflow region, we don't create a branch.
17700     // We don't need to alter control flow.
17701     OffsetDestReg = 0; // unused
17702     OverflowDestReg = DestReg;
17703
17704     offsetMBB = nullptr;
17705     overflowMBB = thisMBB;
17706     endMBB = thisMBB;
17707   } else {
17708     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17709     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17710     // If not, pull from overflow_area. (branch to overflowMBB)
17711     //
17712     //       thisMBB
17713     //         |     .
17714     //         |        .
17715     //     offsetMBB   overflowMBB
17716     //         |        .
17717     //         |     .
17718     //        endMBB
17719
17720     // Registers for the PHI in endMBB
17721     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17722     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17723
17724     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17725     MachineFunction *MF = MBB->getParent();
17726     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17727     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17728     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17729
17730     MachineFunction::iterator MBBIter = MBB;
17731     ++MBBIter;
17732
17733     // Insert the new basic blocks
17734     MF->insert(MBBIter, offsetMBB);
17735     MF->insert(MBBIter, overflowMBB);
17736     MF->insert(MBBIter, endMBB);
17737
17738     // Transfer the remainder of MBB and its successor edges to endMBB.
17739     endMBB->splice(endMBB->begin(), thisMBB,
17740                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17741     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17742
17743     // Make offsetMBB and overflowMBB successors of thisMBB
17744     thisMBB->addSuccessor(offsetMBB);
17745     thisMBB->addSuccessor(overflowMBB);
17746
17747     // endMBB is a successor of both offsetMBB and overflowMBB
17748     offsetMBB->addSuccessor(endMBB);
17749     overflowMBB->addSuccessor(endMBB);
17750
17751     // Load the offset value into a register
17752     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17753     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17754       .addOperand(Base)
17755       .addOperand(Scale)
17756       .addOperand(Index)
17757       .addDisp(Disp, UseFPOffset ? 4 : 0)
17758       .addOperand(Segment)
17759       .setMemRefs(MMOBegin, MMOEnd);
17760
17761     // Check if there is enough room left to pull this argument.
17762     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17763       .addReg(OffsetReg)
17764       .addImm(MaxOffset + 8 - ArgSizeA8);
17765
17766     // Branch to "overflowMBB" if offset >= max
17767     // Fall through to "offsetMBB" otherwise
17768     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17769       .addMBB(overflowMBB);
17770   }
17771
17772   // In offsetMBB, emit code to use the reg_save_area.
17773   if (offsetMBB) {
17774     assert(OffsetReg != 0);
17775
17776     // Read the reg_save_area address.
17777     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17778     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17779       .addOperand(Base)
17780       .addOperand(Scale)
17781       .addOperand(Index)
17782       .addDisp(Disp, 16)
17783       .addOperand(Segment)
17784       .setMemRefs(MMOBegin, MMOEnd);
17785
17786     // Zero-extend the offset
17787     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17788       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17789         .addImm(0)
17790         .addReg(OffsetReg)
17791         .addImm(X86::sub_32bit);
17792
17793     // Add the offset to the reg_save_area to get the final address.
17794     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17795       .addReg(OffsetReg64)
17796       .addReg(RegSaveReg);
17797
17798     // Compute the offset for the next argument
17799     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17800     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17801       .addReg(OffsetReg)
17802       .addImm(UseFPOffset ? 16 : 8);
17803
17804     // Store it back into the va_list.
17805     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17806       .addOperand(Base)
17807       .addOperand(Scale)
17808       .addOperand(Index)
17809       .addDisp(Disp, UseFPOffset ? 4 : 0)
17810       .addOperand(Segment)
17811       .addReg(NextOffsetReg)
17812       .setMemRefs(MMOBegin, MMOEnd);
17813
17814     // Jump to endMBB
17815     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17816       .addMBB(endMBB);
17817   }
17818
17819   //
17820   // Emit code to use overflow area
17821   //
17822
17823   // Load the overflow_area address into a register.
17824   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17825   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17826     .addOperand(Base)
17827     .addOperand(Scale)
17828     .addOperand(Index)
17829     .addDisp(Disp, 8)
17830     .addOperand(Segment)
17831     .setMemRefs(MMOBegin, MMOEnd);
17832
17833   // If we need to align it, do so. Otherwise, just copy the address
17834   // to OverflowDestReg.
17835   if (NeedsAlign) {
17836     // Align the overflow address
17837     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17838     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17839
17840     // aligned_addr = (addr + (align-1)) & ~(align-1)
17841     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17842       .addReg(OverflowAddrReg)
17843       .addImm(Align-1);
17844
17845     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17846       .addReg(TmpReg)
17847       .addImm(~(uint64_t)(Align-1));
17848   } else {
17849     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17850       .addReg(OverflowAddrReg);
17851   }
17852
17853   // Compute the next overflow address after this argument.
17854   // (the overflow address should be kept 8-byte aligned)
17855   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17856   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17857     .addReg(OverflowDestReg)
17858     .addImm(ArgSizeA8);
17859
17860   // Store the new overflow address.
17861   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17862     .addOperand(Base)
17863     .addOperand(Scale)
17864     .addOperand(Index)
17865     .addDisp(Disp, 8)
17866     .addOperand(Segment)
17867     .addReg(NextAddrReg)
17868     .setMemRefs(MMOBegin, MMOEnd);
17869
17870   // If we branched, emit the PHI to the front of endMBB.
17871   if (offsetMBB) {
17872     BuildMI(*endMBB, endMBB->begin(), DL,
17873             TII->get(X86::PHI), DestReg)
17874       .addReg(OffsetDestReg).addMBB(offsetMBB)
17875       .addReg(OverflowDestReg).addMBB(overflowMBB);
17876   }
17877
17878   // Erase the pseudo instruction
17879   MI->eraseFromParent();
17880
17881   return endMBB;
17882 }
17883
17884 MachineBasicBlock *
17885 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17886                                                  MachineInstr *MI,
17887                                                  MachineBasicBlock *MBB) const {
17888   // Emit code to save XMM registers to the stack. The ABI says that the
17889   // number of registers to save is given in %al, so it's theoretically
17890   // possible to do an indirect jump trick to avoid saving all of them,
17891   // however this code takes a simpler approach and just executes all
17892   // of the stores if %al is non-zero. It's less code, and it's probably
17893   // easier on the hardware branch predictor, and stores aren't all that
17894   // expensive anyway.
17895
17896   // Create the new basic blocks. One block contains all the XMM stores,
17897   // and one block is the final destination regardless of whether any
17898   // stores were performed.
17899   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17900   MachineFunction *F = MBB->getParent();
17901   MachineFunction::iterator MBBIter = MBB;
17902   ++MBBIter;
17903   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17904   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17905   F->insert(MBBIter, XMMSaveMBB);
17906   F->insert(MBBIter, EndMBB);
17907
17908   // Transfer the remainder of MBB and its successor edges to EndMBB.
17909   EndMBB->splice(EndMBB->begin(), MBB,
17910                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17911   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17912
17913   // The original block will now fall through to the XMM save block.
17914   MBB->addSuccessor(XMMSaveMBB);
17915   // The XMMSaveMBB will fall through to the end block.
17916   XMMSaveMBB->addSuccessor(EndMBB);
17917
17918   // Now add the instructions.
17919   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17920   DebugLoc DL = MI->getDebugLoc();
17921
17922   unsigned CountReg = MI->getOperand(0).getReg();
17923   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17924   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17925
17926   if (!Subtarget->isTargetWin64()) {
17927     // If %al is 0, branch around the XMM save block.
17928     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17929     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17930     MBB->addSuccessor(EndMBB);
17931   }
17932
17933   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17934   // that was just emitted, but clearly shouldn't be "saved".
17935   assert((MI->getNumOperands() <= 3 ||
17936           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17937           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17938          && "Expected last argument to be EFLAGS");
17939   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17940   // In the XMM save block, save all the XMM argument registers.
17941   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17942     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17943     MachineMemOperand *MMO =
17944       F->getMachineMemOperand(
17945           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17946         MachineMemOperand::MOStore,
17947         /*Size=*/16, /*Align=*/16);
17948     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17949       .addFrameIndex(RegSaveFrameIndex)
17950       .addImm(/*Scale=*/1)
17951       .addReg(/*IndexReg=*/0)
17952       .addImm(/*Disp=*/Offset)
17953       .addReg(/*Segment=*/0)
17954       .addReg(MI->getOperand(i).getReg())
17955       .addMemOperand(MMO);
17956   }
17957
17958   MI->eraseFromParent();   // The pseudo instruction is gone now.
17959
17960   return EndMBB;
17961 }
17962
17963 // The EFLAGS operand of SelectItr might be missing a kill marker
17964 // because there were multiple uses of EFLAGS, and ISel didn't know
17965 // which to mark. Figure out whether SelectItr should have had a
17966 // kill marker, and set it if it should. Returns the correct kill
17967 // marker value.
17968 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17969                                      MachineBasicBlock* BB,
17970                                      const TargetRegisterInfo* TRI) {
17971   // Scan forward through BB for a use/def of EFLAGS.
17972   MachineBasicBlock::iterator miI(std::next(SelectItr));
17973   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17974     const MachineInstr& mi = *miI;
17975     if (mi.readsRegister(X86::EFLAGS))
17976       return false;
17977     if (mi.definesRegister(X86::EFLAGS))
17978       break; // Should have kill-flag - update below.
17979   }
17980
17981   // If we hit the end of the block, check whether EFLAGS is live into a
17982   // successor.
17983   if (miI == BB->end()) {
17984     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17985                                           sEnd = BB->succ_end();
17986          sItr != sEnd; ++sItr) {
17987       MachineBasicBlock* succ = *sItr;
17988       if (succ->isLiveIn(X86::EFLAGS))
17989         return false;
17990     }
17991   }
17992
17993   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17994   // out. SelectMI should have a kill flag on EFLAGS.
17995   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17996   return true;
17997 }
17998
17999 MachineBasicBlock *
18000 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18001                                      MachineBasicBlock *BB) const {
18002   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18003   DebugLoc DL = MI->getDebugLoc();
18004
18005   // To "insert" a SELECT_CC instruction, we actually have to insert the
18006   // diamond control-flow pattern.  The incoming instruction knows the
18007   // destination vreg to set, the condition code register to branch on, the
18008   // true/false values to select between, and a branch opcode to use.
18009   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18010   MachineFunction::iterator It = BB;
18011   ++It;
18012
18013   //  thisMBB:
18014   //  ...
18015   //   TrueVal = ...
18016   //   cmpTY ccX, r1, r2
18017   //   bCC copy1MBB
18018   //   fallthrough --> copy0MBB
18019   MachineBasicBlock *thisMBB = BB;
18020   MachineFunction *F = BB->getParent();
18021   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18022   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18023   F->insert(It, copy0MBB);
18024   F->insert(It, sinkMBB);
18025
18026   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18027   // live into the sink and copy blocks.
18028   const TargetRegisterInfo *TRI =
18029       BB->getParent()->getSubtarget().getRegisterInfo();
18030   if (!MI->killsRegister(X86::EFLAGS) &&
18031       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18032     copy0MBB->addLiveIn(X86::EFLAGS);
18033     sinkMBB->addLiveIn(X86::EFLAGS);
18034   }
18035
18036   // Transfer the remainder of BB and its successor edges to sinkMBB.
18037   sinkMBB->splice(sinkMBB->begin(), BB,
18038                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18039   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18040
18041   // Add the true and fallthrough blocks as its successors.
18042   BB->addSuccessor(copy0MBB);
18043   BB->addSuccessor(sinkMBB);
18044
18045   // Create the conditional branch instruction.
18046   unsigned Opc =
18047     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18048   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18049
18050   //  copy0MBB:
18051   //   %FalseValue = ...
18052   //   # fallthrough to sinkMBB
18053   copy0MBB->addSuccessor(sinkMBB);
18054
18055   //  sinkMBB:
18056   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18057   //  ...
18058   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18059           TII->get(X86::PHI), MI->getOperand(0).getReg())
18060     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18061     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18062
18063   MI->eraseFromParent();   // The pseudo instruction is gone now.
18064   return sinkMBB;
18065 }
18066
18067 MachineBasicBlock *
18068 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18069                                         bool Is64Bit) const {
18070   MachineFunction *MF = BB->getParent();
18071   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18072   DebugLoc DL = MI->getDebugLoc();
18073   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18074
18075   assert(MF->shouldSplitStack());
18076
18077   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18078   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18079
18080   // BB:
18081   //  ... [Till the alloca]
18082   // If stacklet is not large enough, jump to mallocMBB
18083   //
18084   // bumpMBB:
18085   //  Allocate by subtracting from RSP
18086   //  Jump to continueMBB
18087   //
18088   // mallocMBB:
18089   //  Allocate by call to runtime
18090   //
18091   // continueMBB:
18092   //  ...
18093   //  [rest of original BB]
18094   //
18095
18096   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18097   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18098   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18099
18100   MachineRegisterInfo &MRI = MF->getRegInfo();
18101   const TargetRegisterClass *AddrRegClass =
18102     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18103
18104   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18105     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18106     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18107     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18108     sizeVReg = MI->getOperand(1).getReg(),
18109     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18110
18111   MachineFunction::iterator MBBIter = BB;
18112   ++MBBIter;
18113
18114   MF->insert(MBBIter, bumpMBB);
18115   MF->insert(MBBIter, mallocMBB);
18116   MF->insert(MBBIter, continueMBB);
18117
18118   continueMBB->splice(continueMBB->begin(), BB,
18119                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18120   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18121
18122   // Add code to the main basic block to check if the stack limit has been hit,
18123   // and if so, jump to mallocMBB otherwise to bumpMBB.
18124   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18125   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18126     .addReg(tmpSPVReg).addReg(sizeVReg);
18127   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18128     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18129     .addReg(SPLimitVReg);
18130   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18131
18132   // bumpMBB simply decreases the stack pointer, since we know the current
18133   // stacklet has enough space.
18134   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18135     .addReg(SPLimitVReg);
18136   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18137     .addReg(SPLimitVReg);
18138   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18139
18140   // Calls into a routine in libgcc to allocate more space from the heap.
18141   const uint32_t *RegMask = MF->getTarget()
18142                                 .getSubtargetImpl()
18143                                 ->getRegisterInfo()
18144                                 ->getCallPreservedMask(CallingConv::C);
18145   if (Is64Bit) {
18146     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18147       .addReg(sizeVReg);
18148     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18149       .addExternalSymbol("__morestack_allocate_stack_space")
18150       .addRegMask(RegMask)
18151       .addReg(X86::RDI, RegState::Implicit)
18152       .addReg(X86::RAX, RegState::ImplicitDefine);
18153   } else {
18154     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18155       .addImm(12);
18156     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18157     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18158       .addExternalSymbol("__morestack_allocate_stack_space")
18159       .addRegMask(RegMask)
18160       .addReg(X86::EAX, RegState::ImplicitDefine);
18161   }
18162
18163   if (!Is64Bit)
18164     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18165       .addImm(16);
18166
18167   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18168     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18169   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18170
18171   // Set up the CFG correctly.
18172   BB->addSuccessor(bumpMBB);
18173   BB->addSuccessor(mallocMBB);
18174   mallocMBB->addSuccessor(continueMBB);
18175   bumpMBB->addSuccessor(continueMBB);
18176
18177   // Take care of the PHI nodes.
18178   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18179           MI->getOperand(0).getReg())
18180     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18181     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18182
18183   // Delete the original pseudo instruction.
18184   MI->eraseFromParent();
18185
18186   // And we're done.
18187   return continueMBB;
18188 }
18189
18190 MachineBasicBlock *
18191 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18192                                         MachineBasicBlock *BB) const {
18193   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18194   DebugLoc DL = MI->getDebugLoc();
18195
18196   assert(!Subtarget->isTargetMacho());
18197
18198   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18199   // non-trivial part is impdef of ESP.
18200
18201   if (Subtarget->isTargetWin64()) {
18202     if (Subtarget->isTargetCygMing()) {
18203       // ___chkstk(Mingw64):
18204       // Clobbers R10, R11, RAX and EFLAGS.
18205       // Updates RSP.
18206       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18207         .addExternalSymbol("___chkstk")
18208         .addReg(X86::RAX, RegState::Implicit)
18209         .addReg(X86::RSP, RegState::Implicit)
18210         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18211         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18212         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18213     } else {
18214       // __chkstk(MSVCRT): does not update stack pointer.
18215       // Clobbers R10, R11 and EFLAGS.
18216       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18217         .addExternalSymbol("__chkstk")
18218         .addReg(X86::RAX, RegState::Implicit)
18219         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18220       // RAX has the offset to be subtracted from RSP.
18221       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18222         .addReg(X86::RSP)
18223         .addReg(X86::RAX);
18224     }
18225   } else {
18226     const char *StackProbeSymbol =
18227       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18228
18229     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18230       .addExternalSymbol(StackProbeSymbol)
18231       .addReg(X86::EAX, RegState::Implicit)
18232       .addReg(X86::ESP, RegState::Implicit)
18233       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18234       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18235       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18236   }
18237
18238   MI->eraseFromParent();   // The pseudo instruction is gone now.
18239   return BB;
18240 }
18241
18242 MachineBasicBlock *
18243 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18244                                       MachineBasicBlock *BB) const {
18245   // This is pretty easy.  We're taking the value that we received from
18246   // our load from the relocation, sticking it in either RDI (x86-64)
18247   // or EAX and doing an indirect call.  The return value will then
18248   // be in the normal return register.
18249   MachineFunction *F = BB->getParent();
18250   const X86InstrInfo *TII =
18251       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18252   DebugLoc DL = MI->getDebugLoc();
18253
18254   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18255   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18256
18257   // Get a register mask for the lowered call.
18258   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18259   // proper register mask.
18260   const uint32_t *RegMask = F->getTarget()
18261                                 .getSubtargetImpl()
18262                                 ->getRegisterInfo()
18263                                 ->getCallPreservedMask(CallingConv::C);
18264   if (Subtarget->is64Bit()) {
18265     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18266                                       TII->get(X86::MOV64rm), X86::RDI)
18267     .addReg(X86::RIP)
18268     .addImm(0).addReg(0)
18269     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18270                       MI->getOperand(3).getTargetFlags())
18271     .addReg(0);
18272     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18273     addDirectMem(MIB, X86::RDI);
18274     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18275   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18276     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18277                                       TII->get(X86::MOV32rm), X86::EAX)
18278     .addReg(0)
18279     .addImm(0).addReg(0)
18280     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18281                       MI->getOperand(3).getTargetFlags())
18282     .addReg(0);
18283     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18284     addDirectMem(MIB, X86::EAX);
18285     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18286   } else {
18287     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18288                                       TII->get(X86::MOV32rm), X86::EAX)
18289     .addReg(TII->getGlobalBaseReg(F))
18290     .addImm(0).addReg(0)
18291     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18292                       MI->getOperand(3).getTargetFlags())
18293     .addReg(0);
18294     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18295     addDirectMem(MIB, X86::EAX);
18296     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18297   }
18298
18299   MI->eraseFromParent(); // The pseudo instruction is gone now.
18300   return BB;
18301 }
18302
18303 MachineBasicBlock *
18304 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18305                                     MachineBasicBlock *MBB) const {
18306   DebugLoc DL = MI->getDebugLoc();
18307   MachineFunction *MF = MBB->getParent();
18308   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18309   MachineRegisterInfo &MRI = MF->getRegInfo();
18310
18311   const BasicBlock *BB = MBB->getBasicBlock();
18312   MachineFunction::iterator I = MBB;
18313   ++I;
18314
18315   // Memory Reference
18316   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18317   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18318
18319   unsigned DstReg;
18320   unsigned MemOpndSlot = 0;
18321
18322   unsigned CurOp = 0;
18323
18324   DstReg = MI->getOperand(CurOp++).getReg();
18325   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18326   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18327   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18328   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18329
18330   MemOpndSlot = CurOp;
18331
18332   MVT PVT = getPointerTy();
18333   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18334          "Invalid Pointer Size!");
18335
18336   // For v = setjmp(buf), we generate
18337   //
18338   // thisMBB:
18339   //  buf[LabelOffset] = restoreMBB
18340   //  SjLjSetup restoreMBB
18341   //
18342   // mainMBB:
18343   //  v_main = 0
18344   //
18345   // sinkMBB:
18346   //  v = phi(main, restore)
18347   //
18348   // restoreMBB:
18349   //  v_restore = 1
18350
18351   MachineBasicBlock *thisMBB = MBB;
18352   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18353   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18354   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18355   MF->insert(I, mainMBB);
18356   MF->insert(I, sinkMBB);
18357   MF->push_back(restoreMBB);
18358
18359   MachineInstrBuilder MIB;
18360
18361   // Transfer the remainder of BB and its successor edges to sinkMBB.
18362   sinkMBB->splice(sinkMBB->begin(), MBB,
18363                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18364   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18365
18366   // thisMBB:
18367   unsigned PtrStoreOpc = 0;
18368   unsigned LabelReg = 0;
18369   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18370   Reloc::Model RM = MF->getTarget().getRelocationModel();
18371   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18372                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18373
18374   // Prepare IP either in reg or imm.
18375   if (!UseImmLabel) {
18376     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18377     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18378     LabelReg = MRI.createVirtualRegister(PtrRC);
18379     if (Subtarget->is64Bit()) {
18380       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18381               .addReg(X86::RIP)
18382               .addImm(0)
18383               .addReg(0)
18384               .addMBB(restoreMBB)
18385               .addReg(0);
18386     } else {
18387       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18388       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18389               .addReg(XII->getGlobalBaseReg(MF))
18390               .addImm(0)
18391               .addReg(0)
18392               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18393               .addReg(0);
18394     }
18395   } else
18396     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18397   // Store IP
18398   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18399   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18400     if (i == X86::AddrDisp)
18401       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18402     else
18403       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18404   }
18405   if (!UseImmLabel)
18406     MIB.addReg(LabelReg);
18407   else
18408     MIB.addMBB(restoreMBB);
18409   MIB.setMemRefs(MMOBegin, MMOEnd);
18410   // Setup
18411   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18412           .addMBB(restoreMBB);
18413
18414   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18415       MF->getSubtarget().getRegisterInfo());
18416   MIB.addRegMask(RegInfo->getNoPreservedMask());
18417   thisMBB->addSuccessor(mainMBB);
18418   thisMBB->addSuccessor(restoreMBB);
18419
18420   // mainMBB:
18421   //  EAX = 0
18422   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18423   mainMBB->addSuccessor(sinkMBB);
18424
18425   // sinkMBB:
18426   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18427           TII->get(X86::PHI), DstReg)
18428     .addReg(mainDstReg).addMBB(mainMBB)
18429     .addReg(restoreDstReg).addMBB(restoreMBB);
18430
18431   // restoreMBB:
18432   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18433   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18434   restoreMBB->addSuccessor(sinkMBB);
18435
18436   MI->eraseFromParent();
18437   return sinkMBB;
18438 }
18439
18440 MachineBasicBlock *
18441 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18442                                      MachineBasicBlock *MBB) const {
18443   DebugLoc DL = MI->getDebugLoc();
18444   MachineFunction *MF = MBB->getParent();
18445   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18446   MachineRegisterInfo &MRI = MF->getRegInfo();
18447
18448   // Memory Reference
18449   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18450   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18451
18452   MVT PVT = getPointerTy();
18453   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18454          "Invalid Pointer Size!");
18455
18456   const TargetRegisterClass *RC =
18457     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18458   unsigned Tmp = MRI.createVirtualRegister(RC);
18459   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18460   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18461       MF->getSubtarget().getRegisterInfo());
18462   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18463   unsigned SP = RegInfo->getStackRegister();
18464
18465   MachineInstrBuilder MIB;
18466
18467   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18468   const int64_t SPOffset = 2 * PVT.getStoreSize();
18469
18470   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18471   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18472
18473   // Reload FP
18474   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18475   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18476     MIB.addOperand(MI->getOperand(i));
18477   MIB.setMemRefs(MMOBegin, MMOEnd);
18478   // Reload IP
18479   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18480   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18481     if (i == X86::AddrDisp)
18482       MIB.addDisp(MI->getOperand(i), LabelOffset);
18483     else
18484       MIB.addOperand(MI->getOperand(i));
18485   }
18486   MIB.setMemRefs(MMOBegin, MMOEnd);
18487   // Reload SP
18488   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18489   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18490     if (i == X86::AddrDisp)
18491       MIB.addDisp(MI->getOperand(i), SPOffset);
18492     else
18493       MIB.addOperand(MI->getOperand(i));
18494   }
18495   MIB.setMemRefs(MMOBegin, MMOEnd);
18496   // Jump
18497   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18498
18499   MI->eraseFromParent();
18500   return MBB;
18501 }
18502
18503 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18504 // accumulator loops. Writing back to the accumulator allows the coalescer
18505 // to remove extra copies in the loop.   
18506 MachineBasicBlock *
18507 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18508                                  MachineBasicBlock *MBB) const {
18509   MachineOperand &AddendOp = MI->getOperand(3);
18510
18511   // Bail out early if the addend isn't a register - we can't switch these.
18512   if (!AddendOp.isReg())
18513     return MBB;
18514
18515   MachineFunction &MF = *MBB->getParent();
18516   MachineRegisterInfo &MRI = MF.getRegInfo();
18517
18518   // Check whether the addend is defined by a PHI:
18519   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18520   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18521   if (!AddendDef.isPHI())
18522     return MBB;
18523
18524   // Look for the following pattern:
18525   // loop:
18526   //   %addend = phi [%entry, 0], [%loop, %result]
18527   //   ...
18528   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18529
18530   // Replace with:
18531   //   loop:
18532   //   %addend = phi [%entry, 0], [%loop, %result]
18533   //   ...
18534   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18535
18536   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18537     assert(AddendDef.getOperand(i).isReg());
18538     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18539     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18540     if (&PHISrcInst == MI) {
18541       // Found a matching instruction.
18542       unsigned NewFMAOpc = 0;
18543       switch (MI->getOpcode()) {
18544         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18545         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18546         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18547         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18548         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18549         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18550         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18551         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18552         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18553         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18554         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18555         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18556         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18557         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18558         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18559         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18560         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18561         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18562         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18563         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18564         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18565         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18566         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18567         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18568         default: llvm_unreachable("Unrecognized FMA variant.");
18569       }
18570
18571       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18572       MachineInstrBuilder MIB =
18573         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18574         .addOperand(MI->getOperand(0))
18575         .addOperand(MI->getOperand(3))
18576         .addOperand(MI->getOperand(2))
18577         .addOperand(MI->getOperand(1));
18578       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18579       MI->eraseFromParent();
18580     }
18581   }
18582
18583   return MBB;
18584 }
18585
18586 MachineBasicBlock *
18587 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18588                                                MachineBasicBlock *BB) const {
18589   switch (MI->getOpcode()) {
18590   default: llvm_unreachable("Unexpected instr type to insert");
18591   case X86::TAILJMPd64:
18592   case X86::TAILJMPr64:
18593   case X86::TAILJMPm64:
18594     llvm_unreachable("TAILJMP64 would not be touched here.");
18595   case X86::TCRETURNdi64:
18596   case X86::TCRETURNri64:
18597   case X86::TCRETURNmi64:
18598     return BB;
18599   case X86::WIN_ALLOCA:
18600     return EmitLoweredWinAlloca(MI, BB);
18601   case X86::SEG_ALLOCA_32:
18602     return EmitLoweredSegAlloca(MI, BB, false);
18603   case X86::SEG_ALLOCA_64:
18604     return EmitLoweredSegAlloca(MI, BB, true);
18605   case X86::TLSCall_32:
18606   case X86::TLSCall_64:
18607     return EmitLoweredTLSCall(MI, BB);
18608   case X86::CMOV_GR8:
18609   case X86::CMOV_FR32:
18610   case X86::CMOV_FR64:
18611   case X86::CMOV_V4F32:
18612   case X86::CMOV_V2F64:
18613   case X86::CMOV_V2I64:
18614   case X86::CMOV_V8F32:
18615   case X86::CMOV_V4F64:
18616   case X86::CMOV_V4I64:
18617   case X86::CMOV_V16F32:
18618   case X86::CMOV_V8F64:
18619   case X86::CMOV_V8I64:
18620   case X86::CMOV_GR16:
18621   case X86::CMOV_GR32:
18622   case X86::CMOV_RFP32:
18623   case X86::CMOV_RFP64:
18624   case X86::CMOV_RFP80:
18625     return EmitLoweredSelect(MI, BB);
18626
18627   case X86::FP32_TO_INT16_IN_MEM:
18628   case X86::FP32_TO_INT32_IN_MEM:
18629   case X86::FP32_TO_INT64_IN_MEM:
18630   case X86::FP64_TO_INT16_IN_MEM:
18631   case X86::FP64_TO_INT32_IN_MEM:
18632   case X86::FP64_TO_INT64_IN_MEM:
18633   case X86::FP80_TO_INT16_IN_MEM:
18634   case X86::FP80_TO_INT32_IN_MEM:
18635   case X86::FP80_TO_INT64_IN_MEM: {
18636     MachineFunction *F = BB->getParent();
18637     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
18638     DebugLoc DL = MI->getDebugLoc();
18639
18640     // Change the floating point control register to use "round towards zero"
18641     // mode when truncating to an integer value.
18642     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18643     addFrameReference(BuildMI(*BB, MI, DL,
18644                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18645
18646     // Load the old value of the high byte of the control word...
18647     unsigned OldCW =
18648       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18649     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18650                       CWFrameIdx);
18651
18652     // Set the high part to be round to zero...
18653     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18654       .addImm(0xC7F);
18655
18656     // Reload the modified control word now...
18657     addFrameReference(BuildMI(*BB, MI, DL,
18658                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18659
18660     // Restore the memory image of control word to original value
18661     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18662       .addReg(OldCW);
18663
18664     // Get the X86 opcode to use.
18665     unsigned Opc;
18666     switch (MI->getOpcode()) {
18667     default: llvm_unreachable("illegal opcode!");
18668     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18669     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18670     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18671     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18672     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18673     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18674     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18675     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18676     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18677     }
18678
18679     X86AddressMode AM;
18680     MachineOperand &Op = MI->getOperand(0);
18681     if (Op.isReg()) {
18682       AM.BaseType = X86AddressMode::RegBase;
18683       AM.Base.Reg = Op.getReg();
18684     } else {
18685       AM.BaseType = X86AddressMode::FrameIndexBase;
18686       AM.Base.FrameIndex = Op.getIndex();
18687     }
18688     Op = MI->getOperand(1);
18689     if (Op.isImm())
18690       AM.Scale = Op.getImm();
18691     Op = MI->getOperand(2);
18692     if (Op.isImm())
18693       AM.IndexReg = Op.getImm();
18694     Op = MI->getOperand(3);
18695     if (Op.isGlobal()) {
18696       AM.GV = Op.getGlobal();
18697     } else {
18698       AM.Disp = Op.getImm();
18699     }
18700     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18701                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18702
18703     // Reload the original control word now.
18704     addFrameReference(BuildMI(*BB, MI, DL,
18705                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18706
18707     MI->eraseFromParent();   // The pseudo instruction is gone now.
18708     return BB;
18709   }
18710     // String/text processing lowering.
18711   case X86::PCMPISTRM128REG:
18712   case X86::VPCMPISTRM128REG:
18713   case X86::PCMPISTRM128MEM:
18714   case X86::VPCMPISTRM128MEM:
18715   case X86::PCMPESTRM128REG:
18716   case X86::VPCMPESTRM128REG:
18717   case X86::PCMPESTRM128MEM:
18718   case X86::VPCMPESTRM128MEM:
18719     assert(Subtarget->hasSSE42() &&
18720            "Target must have SSE4.2 or AVX features enabled");
18721     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18722
18723   // String/text processing lowering.
18724   case X86::PCMPISTRIREG:
18725   case X86::VPCMPISTRIREG:
18726   case X86::PCMPISTRIMEM:
18727   case X86::VPCMPISTRIMEM:
18728   case X86::PCMPESTRIREG:
18729   case X86::VPCMPESTRIREG:
18730   case X86::PCMPESTRIMEM:
18731   case X86::VPCMPESTRIMEM:
18732     assert(Subtarget->hasSSE42() &&
18733            "Target must have SSE4.2 or AVX features enabled");
18734     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18735
18736   // Thread synchronization.
18737   case X86::MONITOR:
18738     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
18739                        Subtarget);
18740
18741   // xbegin
18742   case X86::XBEGIN:
18743     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18744
18745   case X86::VASTART_SAVE_XMM_REGS:
18746     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18747
18748   case X86::VAARG_64:
18749     return EmitVAARG64WithCustomInserter(MI, BB);
18750
18751   case X86::EH_SjLj_SetJmp32:
18752   case X86::EH_SjLj_SetJmp64:
18753     return emitEHSjLjSetJmp(MI, BB);
18754
18755   case X86::EH_SjLj_LongJmp32:
18756   case X86::EH_SjLj_LongJmp64:
18757     return emitEHSjLjLongJmp(MI, BB);
18758
18759   case TargetOpcode::STACKMAP:
18760   case TargetOpcode::PATCHPOINT:
18761     return emitPatchPoint(MI, BB);
18762
18763   case X86::VFMADDPDr213r:
18764   case X86::VFMADDPSr213r:
18765   case X86::VFMADDSDr213r:
18766   case X86::VFMADDSSr213r:
18767   case X86::VFMSUBPDr213r:
18768   case X86::VFMSUBPSr213r:
18769   case X86::VFMSUBSDr213r:
18770   case X86::VFMSUBSSr213r:
18771   case X86::VFNMADDPDr213r:
18772   case X86::VFNMADDPSr213r:
18773   case X86::VFNMADDSDr213r:
18774   case X86::VFNMADDSSr213r:
18775   case X86::VFNMSUBPDr213r:
18776   case X86::VFNMSUBPSr213r:
18777   case X86::VFNMSUBSDr213r:
18778   case X86::VFNMSUBSSr213r:
18779   case X86::VFMADDPDr213rY:
18780   case X86::VFMADDPSr213rY:
18781   case X86::VFMSUBPDr213rY:
18782   case X86::VFMSUBPSr213rY:
18783   case X86::VFNMADDPDr213rY:
18784   case X86::VFNMADDPSr213rY:
18785   case X86::VFNMSUBPDr213rY:
18786   case X86::VFNMSUBPSr213rY:
18787     return emitFMA3Instr(MI, BB);
18788   }
18789 }
18790
18791 //===----------------------------------------------------------------------===//
18792 //                           X86 Optimization Hooks
18793 //===----------------------------------------------------------------------===//
18794
18795 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18796                                                       APInt &KnownZero,
18797                                                       APInt &KnownOne,
18798                                                       const SelectionDAG &DAG,
18799                                                       unsigned Depth) const {
18800   unsigned BitWidth = KnownZero.getBitWidth();
18801   unsigned Opc = Op.getOpcode();
18802   assert((Opc >= ISD::BUILTIN_OP_END ||
18803           Opc == ISD::INTRINSIC_WO_CHAIN ||
18804           Opc == ISD::INTRINSIC_W_CHAIN ||
18805           Opc == ISD::INTRINSIC_VOID) &&
18806          "Should use MaskedValueIsZero if you don't know whether Op"
18807          " is a target node!");
18808
18809   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18810   switch (Opc) {
18811   default: break;
18812   case X86ISD::ADD:
18813   case X86ISD::SUB:
18814   case X86ISD::ADC:
18815   case X86ISD::SBB:
18816   case X86ISD::SMUL:
18817   case X86ISD::UMUL:
18818   case X86ISD::INC:
18819   case X86ISD::DEC:
18820   case X86ISD::OR:
18821   case X86ISD::XOR:
18822   case X86ISD::AND:
18823     // These nodes' second result is a boolean.
18824     if (Op.getResNo() == 0)
18825       break;
18826     // Fallthrough
18827   case X86ISD::SETCC:
18828     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18829     break;
18830   case ISD::INTRINSIC_WO_CHAIN: {
18831     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18832     unsigned NumLoBits = 0;
18833     switch (IntId) {
18834     default: break;
18835     case Intrinsic::x86_sse_movmsk_ps:
18836     case Intrinsic::x86_avx_movmsk_ps_256:
18837     case Intrinsic::x86_sse2_movmsk_pd:
18838     case Intrinsic::x86_avx_movmsk_pd_256:
18839     case Intrinsic::x86_mmx_pmovmskb:
18840     case Intrinsic::x86_sse2_pmovmskb_128:
18841     case Intrinsic::x86_avx2_pmovmskb: {
18842       // High bits of movmskp{s|d}, pmovmskb are known zero.
18843       switch (IntId) {
18844         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18845         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18846         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18847         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18848         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18849         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18850         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18851         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18852       }
18853       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18854       break;
18855     }
18856     }
18857     break;
18858   }
18859   }
18860 }
18861
18862 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18863   SDValue Op,
18864   const SelectionDAG &,
18865   unsigned Depth) const {
18866   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18867   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18868     return Op.getValueType().getScalarType().getSizeInBits();
18869
18870   // Fallback case.
18871   return 1;
18872 }
18873
18874 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18875 /// node is a GlobalAddress + offset.
18876 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18877                                        const GlobalValue* &GA,
18878                                        int64_t &Offset) const {
18879   if (N->getOpcode() == X86ISD::Wrapper) {
18880     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18881       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18882       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18883       return true;
18884     }
18885   }
18886   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18887 }
18888
18889 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18890 /// same as extracting the high 128-bit part of 256-bit vector and then
18891 /// inserting the result into the low part of a new 256-bit vector
18892 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18893   EVT VT = SVOp->getValueType(0);
18894   unsigned NumElems = VT.getVectorNumElements();
18895
18896   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18897   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18898     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18899         SVOp->getMaskElt(j) >= 0)
18900       return false;
18901
18902   return true;
18903 }
18904
18905 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18906 /// same as extracting the low 128-bit part of 256-bit vector and then
18907 /// inserting the result into the high part of a new 256-bit vector
18908 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18909   EVT VT = SVOp->getValueType(0);
18910   unsigned NumElems = VT.getVectorNumElements();
18911
18912   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18913   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18914     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18915         SVOp->getMaskElt(j) >= 0)
18916       return false;
18917
18918   return true;
18919 }
18920
18921 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18922 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18923                                         TargetLowering::DAGCombinerInfo &DCI,
18924                                         const X86Subtarget* Subtarget) {
18925   SDLoc dl(N);
18926   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18927   SDValue V1 = SVOp->getOperand(0);
18928   SDValue V2 = SVOp->getOperand(1);
18929   EVT VT = SVOp->getValueType(0);
18930   unsigned NumElems = VT.getVectorNumElements();
18931
18932   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18933       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18934     //
18935     //                   0,0,0,...
18936     //                      |
18937     //    V      UNDEF    BUILD_VECTOR    UNDEF
18938     //     \      /           \           /
18939     //  CONCAT_VECTOR         CONCAT_VECTOR
18940     //         \                  /
18941     //          \                /
18942     //          RESULT: V + zero extended
18943     //
18944     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18945         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18946         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18947       return SDValue();
18948
18949     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18950       return SDValue();
18951
18952     // To match the shuffle mask, the first half of the mask should
18953     // be exactly the first vector, and all the rest a splat with the
18954     // first element of the second one.
18955     for (unsigned i = 0; i != NumElems/2; ++i)
18956       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18957           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18958         return SDValue();
18959
18960     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18961     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18962       if (Ld->hasNUsesOfValue(1, 0)) {
18963         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18964         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18965         SDValue ResNode =
18966           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18967                                   Ld->getMemoryVT(),
18968                                   Ld->getPointerInfo(),
18969                                   Ld->getAlignment(),
18970                                   false/*isVolatile*/, true/*ReadMem*/,
18971                                   false/*WriteMem*/);
18972
18973         // Make sure the newly-created LOAD is in the same position as Ld in
18974         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18975         // and update uses of Ld's output chain to use the TokenFactor.
18976         if (Ld->hasAnyUseOfValue(1)) {
18977           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18978                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18979           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18980           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18981                                  SDValue(ResNode.getNode(), 1));
18982         }
18983
18984         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18985       }
18986     }
18987
18988     // Emit a zeroed vector and insert the desired subvector on its
18989     // first half.
18990     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18991     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18992     return DCI.CombineTo(N, InsV);
18993   }
18994
18995   //===--------------------------------------------------------------------===//
18996   // Combine some shuffles into subvector extracts and inserts:
18997   //
18998
18999   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19000   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19001     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19002     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19003     return DCI.CombineTo(N, InsV);
19004   }
19005
19006   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19007   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19008     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19009     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19010     return DCI.CombineTo(N, InsV);
19011   }
19012
19013   return SDValue();
19014 }
19015
19016 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19017 /// possible.
19018 ///
19019 /// This is the leaf of the recursive combinine below. When we have found some
19020 /// chain of single-use x86 shuffle instructions and accumulated the combined
19021 /// shuffle mask represented by them, this will try to pattern match that mask
19022 /// into either a single instruction if there is a special purpose instruction
19023 /// for this operation, or into a PSHUFB instruction which is a fully general
19024 /// instruction but should only be used to replace chains over a certain depth.
19025 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19026                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19027                                    TargetLowering::DAGCombinerInfo &DCI,
19028                                    const X86Subtarget *Subtarget) {
19029   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19030
19031   // Find the operand that enters the chain. Note that multiple uses are OK
19032   // here, we're not going to remove the operand we find.
19033   SDValue Input = Op.getOperand(0);
19034   while (Input.getOpcode() == ISD::BITCAST)
19035     Input = Input.getOperand(0);
19036
19037   MVT VT = Input.getSimpleValueType();
19038   MVT RootVT = Root.getSimpleValueType();
19039   SDLoc DL(Root);
19040
19041   // Just remove no-op shuffle masks.
19042   if (Mask.size() == 1) {
19043     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19044                   /*AddTo*/ true);
19045     return true;
19046   }
19047
19048   // Use the float domain if the operand type is a floating point type.
19049   bool FloatDomain = VT.isFloatingPoint();
19050
19051   // If we don't have access to VEX encodings, the generic PSHUF instructions
19052   // are preferable to some of the specialized forms despite requiring one more
19053   // byte to encode because they can implicitly copy.
19054   //
19055   // IF we *do* have VEX encodings, than we can use shorter, more specific
19056   // shuffle instructions freely as they can copy due to the extra register
19057   // operand.
19058   if (Subtarget->hasAVX()) {
19059     // We have both floating point and integer variants of shuffles that dup
19060     // either the low or high half of the vector.
19061     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19062       bool Lo = Mask.equals(0, 0);
19063       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19064                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19065       if (Depth == 1 && Root->getOpcode() == Shuffle)
19066         return false; // Nothing to do!
19067       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19068       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19069       DCI.AddToWorklist(Op.getNode());
19070       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19071       DCI.AddToWorklist(Op.getNode());
19072       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19073                     /*AddTo*/ true);
19074       return true;
19075     }
19076
19077     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19078
19079     // For the integer domain we have specialized instructions for duplicating
19080     // any element size from the low or high half.
19081     if (!FloatDomain &&
19082         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19083          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19084          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19085          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19086          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19087                      15))) {
19088       bool Lo = Mask[0] == 0;
19089       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19090       if (Depth == 1 && Root->getOpcode() == Shuffle)
19091         return false; // Nothing to do!
19092       MVT ShuffleVT;
19093       switch (Mask.size()) {
19094       case 4: ShuffleVT = MVT::v4i32; break;
19095       case 8: ShuffleVT = MVT::v8i16; break;
19096       case 16: ShuffleVT = MVT::v16i8; break;
19097       };
19098       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19099       DCI.AddToWorklist(Op.getNode());
19100       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19101       DCI.AddToWorklist(Op.getNode());
19102       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19103                     /*AddTo*/ true);
19104       return true;
19105     }
19106   }
19107
19108   // Don't try to re-form single instruction chains under any circumstances now
19109   // that we've done encoding canonicalization for them.
19110   if (Depth < 2)
19111     return false;
19112
19113   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19114   // can replace them with a single PSHUFB instruction profitably. Intel's
19115   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19116   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19117   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19118     SmallVector<SDValue, 16> PSHUFBMask;
19119     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19120     int Ratio = 16 / Mask.size();
19121     for (unsigned i = 0; i < 16; ++i) {
19122       int M = Ratio * Mask[i / Ratio] + i % Ratio;
19123       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19124     }
19125     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19126     DCI.AddToWorklist(Op.getNode());
19127     SDValue PSHUFBMaskOp =
19128         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19129     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19130     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19131     DCI.AddToWorklist(Op.getNode());
19132     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19133                   /*AddTo*/ true);
19134     return true;
19135   }
19136
19137   // Failed to find any combines.
19138   return false;
19139 }
19140
19141 /// \brief Fully generic combining of x86 shuffle instructions.
19142 ///
19143 /// This should be the last combine run over the x86 shuffle instructions. Once
19144 /// they have been fully optimized, this will recursively consdier all chains
19145 /// of single-use shuffle instructions, build a generic model of the cumulative
19146 /// shuffle operation, and check for simpler instructions which implement this
19147 /// operation. We use this primarily for two purposes:
19148 ///
19149 /// 1) Collapse generic shuffles to specialized single instructions when
19150 ///    equivalent. In most cases, this is just an encoding size win, but
19151 ///    sometimes we will collapse multiple generic shuffles into a single
19152 ///    special-purpose shuffle.
19153 /// 2) Look for sequences of shuffle instructions with 3 or more total
19154 ///    instructions, and replace them with the slightly more expensive SSSE3
19155 ///    PSHUFB instruction if available. We do this as the last combining step
19156 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19157 ///    a suitable short sequence of other instructions. The PHUFB will either
19158 ///    use a register or have to read from memory and so is slightly (but only
19159 ///    slightly) more expensive than the other shuffle instructions.
19160 ///
19161 /// Because this is inherently a quadratic operation (for each shuffle in
19162 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19163 /// This should never be an issue in practice as the shuffle lowering doesn't
19164 /// produce sequences of more than 8 instructions.
19165 ///
19166 /// FIXME: We will currently miss some cases where the redundant shuffling
19167 /// would simplify under the threshold for PSHUFB formation because of
19168 /// combine-ordering. To fix this, we should do the redundant instruction
19169 /// combining in this recursive walk.
19170 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19171                                           ArrayRef<int> IncomingMask, int Depth,
19172                                           bool HasPSHUFB, SelectionDAG &DAG,
19173                                           TargetLowering::DAGCombinerInfo &DCI,
19174                                           const X86Subtarget *Subtarget) {
19175   // Bound the depth of our recursive combine because this is ultimately
19176   // quadratic in nature.
19177   if (Depth > 8)
19178     return false;
19179
19180   // Directly rip through bitcasts to find the underlying operand.
19181   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19182     Op = Op.getOperand(0);
19183
19184   MVT VT = Op.getSimpleValueType();
19185   if (!VT.isVector())
19186     return false; // Bail if we hit a non-vector.
19187   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19188   // version should be added.
19189   if (VT.getSizeInBits() != 128)
19190     return false;
19191
19192   assert(Root.getSimpleValueType().isVector() &&
19193          "Shuffles operate on vector types!");
19194   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19195          "Can only combine shuffles of the same vector register size.");
19196
19197   if (!isTargetShuffle(Op.getOpcode()))
19198     return false;
19199   SmallVector<int, 16> OpMask;
19200   bool IsUnary;
19201   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19202   // We only can combine unary shuffles which we can decode the mask for.
19203   if (!HaveMask || !IsUnary)
19204     return false;
19205
19206   assert(VT.getVectorNumElements() == OpMask.size() &&
19207          "Different mask size from vector size!");
19208
19209   SmallVector<int, 16> Mask;
19210   Mask.reserve(std::max(OpMask.size(), IncomingMask.size()));
19211
19212   // Merge this shuffle operation's mask into our accumulated mask. This is
19213   // a bit tricky as the shuffle may have a different size from the root.
19214   if (OpMask.size() == IncomingMask.size()) {
19215     for (int M : IncomingMask)
19216       Mask.push_back(OpMask[M]);
19217   } else if (OpMask.size() < IncomingMask.size()) {
19218     assert(IncomingMask.size() % OpMask.size() == 0 &&
19219            "The smaller number of elements must divide the larger.");
19220     int Ratio = IncomingMask.size() / OpMask.size();
19221     for (int M : IncomingMask)
19222       Mask.push_back(Ratio * OpMask[M / Ratio] + M % Ratio);
19223   } else {
19224     assert(OpMask.size() > IncomingMask.size() && "All other cases handled!");
19225     assert(OpMask.size() % IncomingMask.size() == 0 &&
19226            "The smaller number of elements must divide the larger.");
19227     int Ratio = OpMask.size() / IncomingMask.size();
19228     for (int i = 0, e = OpMask.size(); i < e; ++i)
19229       Mask.push_back(OpMask[Ratio * IncomingMask[i / Ratio] + i % Ratio]);
19230   }
19231
19232   // See if we can recurse into the operand to combine more things.
19233   switch (Op.getOpcode()) {
19234     case X86ISD::PSHUFB:
19235       HasPSHUFB = true;
19236     case X86ISD::PSHUFD:
19237     case X86ISD::PSHUFHW:
19238     case X86ISD::PSHUFLW:
19239       if (Op.getOperand(0).hasOneUse() &&
19240           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19241                                         HasPSHUFB, DAG, DCI, Subtarget))
19242         return true;
19243       break;
19244
19245     case X86ISD::UNPCKL:
19246     case X86ISD::UNPCKH:
19247       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19248       // We can't check for single use, we have to check that this shuffle is the only user.
19249       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19250           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19251                                         HasPSHUFB, DAG, DCI, Subtarget))
19252           return true;
19253       break;
19254   }
19255
19256   // Minor canonicalization of the accumulated shuffle mask to make it easier
19257   // to match below. All this does is detect masks with squential pairs of
19258   // elements, and shrink them to the half-width mask. It does this in a loop
19259   // so it will reduce the size of the mask to the minimal width mask which
19260   // performs an equivalent shuffle.
19261   while (Mask.size() > 1) {
19262     SmallVector<int, 16> NewMask;
19263     for (int i = 0, e = Mask.size()/2; i < e; ++i) {
19264       if (Mask[2*i] % 2 != 0 || Mask[2*i] != Mask[2*i + 1] + 1) {
19265         NewMask.clear();
19266         break;
19267       }
19268       NewMask.push_back(Mask[2*i] / 2);
19269     }
19270     if (NewMask.empty())
19271       break;
19272     Mask.swap(NewMask);
19273   }
19274
19275   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19276                                 Subtarget);
19277 }
19278
19279 /// \brief Get the PSHUF-style mask from PSHUF node.
19280 ///
19281 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19282 /// PSHUF-style masks that can be reused with such instructions.
19283 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19284   SmallVector<int, 4> Mask;
19285   bool IsUnary;
19286   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19287   (void)HaveMask;
19288   assert(HaveMask);
19289
19290   switch (N.getOpcode()) {
19291   case X86ISD::PSHUFD:
19292     return Mask;
19293   case X86ISD::PSHUFLW:
19294     Mask.resize(4);
19295     return Mask;
19296   case X86ISD::PSHUFHW:
19297     Mask.erase(Mask.begin(), Mask.begin() + 4);
19298     for (int &M : Mask)
19299       M -= 4;
19300     return Mask;
19301   default:
19302     llvm_unreachable("No valid shuffle instruction found!");
19303   }
19304 }
19305
19306 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19307 ///
19308 /// We walk up the chain and look for a combinable shuffle, skipping over
19309 /// shuffles that we could hoist this shuffle's transformation past without
19310 /// altering anything.
19311 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19312                                          SelectionDAG &DAG,
19313                                          TargetLowering::DAGCombinerInfo &DCI) {
19314   assert(N.getOpcode() == X86ISD::PSHUFD &&
19315          "Called with something other than an x86 128-bit half shuffle!");
19316   SDLoc DL(N);
19317
19318   // Walk up a single-use chain looking for a combinable shuffle.
19319   SDValue V = N.getOperand(0);
19320   for (; V.hasOneUse(); V = V.getOperand(0)) {
19321     switch (V.getOpcode()) {
19322     default:
19323       return false; // Nothing combined!
19324
19325     case ISD::BITCAST:
19326       // Skip bitcasts as we always know the type for the target specific
19327       // instructions.
19328       continue;
19329
19330     case X86ISD::PSHUFD:
19331       // Found another dword shuffle.
19332       break;
19333
19334     case X86ISD::PSHUFLW:
19335       // Check that the low words (being shuffled) are the identity in the
19336       // dword shuffle, and the high words are self-contained.
19337       if (Mask[0] != 0 || Mask[1] != 1 ||
19338           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19339         return false;
19340
19341       continue;
19342
19343     case X86ISD::PSHUFHW:
19344       // Check that the high words (being shuffled) are the identity in the
19345       // dword shuffle, and the low words are self-contained.
19346       if (Mask[2] != 2 || Mask[3] != 3 ||
19347           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19348         return false;
19349
19350       continue;
19351
19352     case X86ISD::UNPCKL:
19353     case X86ISD::UNPCKH:
19354       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19355       // shuffle into a preceding word shuffle.
19356       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19357         return false;
19358
19359       // Search for a half-shuffle which we can combine with.
19360       unsigned CombineOp =
19361           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19362       if (V.getOperand(0) != V.getOperand(1) ||
19363           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19364         return false;
19365       V = V.getOperand(0);
19366       do {
19367         switch (V.getOpcode()) {
19368         default:
19369           return false; // Nothing to combine.
19370
19371         case X86ISD::PSHUFLW:
19372         case X86ISD::PSHUFHW:
19373           if (V.getOpcode() == CombineOp)
19374             break;
19375
19376           // Fallthrough!
19377         case ISD::BITCAST:
19378           V = V.getOperand(0);
19379           continue;
19380         }
19381         break;
19382       } while (V.hasOneUse());
19383       break;
19384     }
19385     // Break out of the loop if we break out of the switch.
19386     break;
19387   }
19388
19389   if (!V.hasOneUse())
19390     // We fell out of the loop without finding a viable combining instruction.
19391     return false;
19392
19393   // Record the old value to use in RAUW-ing.
19394   SDValue Old = V;
19395
19396   // Merge this node's mask and our incoming mask.
19397   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19398   for (int &M : Mask)
19399     M = VMask[M];
19400   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19401                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19402
19403   // It is possible that one of the combinable shuffles was completely absorbed
19404   // by the other, just replace it and revisit all users in that case.
19405   if (Old.getNode() == V.getNode()) {
19406     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19407     return true;
19408   }
19409
19410   // Replace N with its operand as we're going to combine that shuffle away.
19411   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19412
19413   // Replace the combinable shuffle with the combined one, updating all users
19414   // so that we re-evaluate the chain here.
19415   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19416   return true;
19417 }
19418
19419 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19420 ///
19421 /// We walk up the chain, skipping shuffles of the other half and looking
19422 /// through shuffles which switch halves trying to find a shuffle of the same
19423 /// pair of dwords.
19424 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19425                                         SelectionDAG &DAG,
19426                                         TargetLowering::DAGCombinerInfo &DCI) {
19427   assert(
19428       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19429       "Called with something other than an x86 128-bit half shuffle!");
19430   SDLoc DL(N);
19431   unsigned CombineOpcode = N.getOpcode();
19432
19433   // Walk up a single-use chain looking for a combinable shuffle.
19434   SDValue V = N.getOperand(0);
19435   for (; V.hasOneUse(); V = V.getOperand(0)) {
19436     switch (V.getOpcode()) {
19437     default:
19438       return false; // Nothing combined!
19439
19440     case ISD::BITCAST:
19441       // Skip bitcasts as we always know the type for the target specific
19442       // instructions.
19443       continue;
19444
19445     case X86ISD::PSHUFLW:
19446     case X86ISD::PSHUFHW:
19447       if (V.getOpcode() == CombineOpcode)
19448         break;
19449
19450       // Other-half shuffles are no-ops.
19451       continue;
19452     }
19453     // Break out of the loop if we break out of the switch.
19454     break;
19455   }
19456
19457   if (!V.hasOneUse())
19458     // We fell out of the loop without finding a viable combining instruction.
19459     return false;
19460
19461   // Combine away the bottom node as its shuffle will be accumulated into
19462   // a preceding shuffle.
19463   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19464
19465   // Record the old value.
19466   SDValue Old = V;
19467
19468   // Merge this node's mask and our incoming mask (adjusted to account for all
19469   // the pshufd instructions encountered).
19470   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19471   for (int &M : Mask)
19472     M = VMask[M];
19473   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19474                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19475
19476   // Check that the shuffles didn't cancel each other out. If not, we need to
19477   // combine to the new one.
19478   if (Old != V)
19479     // Replace the combinable shuffle with the combined one, updating all users
19480     // so that we re-evaluate the chain here.
19481     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19482
19483   return true;
19484 }
19485
19486 /// \brief Try to combine x86 target specific shuffles.
19487 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19488                                            TargetLowering::DAGCombinerInfo &DCI,
19489                                            const X86Subtarget *Subtarget) {
19490   SDLoc DL(N);
19491   MVT VT = N.getSimpleValueType();
19492   SmallVector<int, 4> Mask;
19493
19494   switch (N.getOpcode()) {
19495   case X86ISD::PSHUFD:
19496   case X86ISD::PSHUFLW:
19497   case X86ISD::PSHUFHW:
19498     Mask = getPSHUFShuffleMask(N);
19499     assert(Mask.size() == 4);
19500     break;
19501   default:
19502     return SDValue();
19503   }
19504
19505   // Nuke no-op shuffles that show up after combining.
19506   if (isNoopShuffleMask(Mask))
19507     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19508
19509   // Look for simplifications involving one or two shuffle instructions.
19510   SDValue V = N.getOperand(0);
19511   switch (N.getOpcode()) {
19512   default:
19513     break;
19514   case X86ISD::PSHUFLW:
19515   case X86ISD::PSHUFHW:
19516     assert(VT == MVT::v8i16);
19517     (void)VT;
19518
19519     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19520       return SDValue(); // We combined away this shuffle, so we're done.
19521
19522     // See if this reduces to a PSHUFD which is no more expensive and can
19523     // combine with more operations.
19524     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
19525         areAdjacentMasksSequential(Mask)) {
19526       int DMask[] = {-1, -1, -1, -1};
19527       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19528       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19529       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19530       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19531       DCI.AddToWorklist(V.getNode());
19532       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19533                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19534       DCI.AddToWorklist(V.getNode());
19535       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19536     }
19537
19538     // Look for shuffle patterns which can be implemented as a single unpack.
19539     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19540     // only works when we have a PSHUFD followed by two half-shuffles.
19541     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19542         (V.getOpcode() == X86ISD::PSHUFLW ||
19543          V.getOpcode() == X86ISD::PSHUFHW) &&
19544         V.getOpcode() != N.getOpcode() &&
19545         V.hasOneUse()) {
19546       SDValue D = V.getOperand(0);
19547       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19548         D = D.getOperand(0);
19549       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19550         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19551         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19552         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19553         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19554         int WordMask[8];
19555         for (int i = 0; i < 4; ++i) {
19556           WordMask[i + NOffset] = Mask[i] + NOffset;
19557           WordMask[i + VOffset] = VMask[i] + VOffset;
19558         }
19559         // Map the word mask through the DWord mask.
19560         int MappedMask[8];
19561         for (int i = 0; i < 8; ++i)
19562           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19563         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19564         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19565         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19566                        std::begin(UnpackLoMask)) ||
19567             std::equal(std::begin(MappedMask), std::end(MappedMask),
19568                        std::begin(UnpackHiMask))) {
19569           // We can replace all three shuffles with an unpack.
19570           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19571           DCI.AddToWorklist(V.getNode());
19572           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19573                                                 : X86ISD::UNPCKH,
19574                              DL, MVT::v8i16, V, V);
19575         }
19576       }
19577     }
19578
19579     break;
19580
19581   case X86ISD::PSHUFD:
19582     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19583       return SDValue(); // We combined away this shuffle.
19584
19585     break;
19586   }
19587
19588   return SDValue();
19589 }
19590
19591 /// PerformShuffleCombine - Performs several different shuffle combines.
19592 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19593                                      TargetLowering::DAGCombinerInfo &DCI,
19594                                      const X86Subtarget *Subtarget) {
19595   SDLoc dl(N);
19596   SDValue N0 = N->getOperand(0);
19597   SDValue N1 = N->getOperand(1);
19598   EVT VT = N->getValueType(0);
19599
19600   // Don't create instructions with illegal types after legalize types has run.
19601   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19602   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19603     return SDValue();
19604
19605   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19606   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19607       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19608     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19609
19610   // During Type Legalization, when promoting illegal vector types,
19611   // the backend might introduce new shuffle dag nodes and bitcasts.
19612   //
19613   // This code performs the following transformation:
19614   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19615   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19616   //
19617   // We do this only if both the bitcast and the BINOP dag nodes have
19618   // one use. Also, perform this transformation only if the new binary
19619   // operation is legal. This is to avoid introducing dag nodes that
19620   // potentially need to be further expanded (or custom lowered) into a
19621   // less optimal sequence of dag nodes.
19622   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19623       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19624       N0.getOpcode() == ISD::BITCAST) {
19625     SDValue BC0 = N0.getOperand(0);
19626     EVT SVT = BC0.getValueType();
19627     unsigned Opcode = BC0.getOpcode();
19628     unsigned NumElts = VT.getVectorNumElements();
19629     
19630     if (BC0.hasOneUse() && SVT.isVector() &&
19631         SVT.getVectorNumElements() * 2 == NumElts &&
19632         TLI.isOperationLegal(Opcode, VT)) {
19633       bool CanFold = false;
19634       switch (Opcode) {
19635       default : break;
19636       case ISD::ADD :
19637       case ISD::FADD :
19638       case ISD::SUB :
19639       case ISD::FSUB :
19640       case ISD::MUL :
19641       case ISD::FMUL :
19642         CanFold = true;
19643       }
19644
19645       unsigned SVTNumElts = SVT.getVectorNumElements();
19646       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19647       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19648         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19649       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19650         CanFold = SVOp->getMaskElt(i) < 0;
19651
19652       if (CanFold) {
19653         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19654         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19655         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19656         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19657       }
19658     }
19659   }
19660
19661   // Only handle 128 wide vector from here on.
19662   if (!VT.is128BitVector())
19663     return SDValue();
19664
19665   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19666   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19667   // consecutive, non-overlapping, and in the right order.
19668   SmallVector<SDValue, 16> Elts;
19669   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19670     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19671
19672   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19673   if (LD.getNode())
19674     return LD;
19675
19676   if (isTargetShuffle(N->getOpcode())) {
19677     SDValue Shuffle =
19678         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19679     if (Shuffle.getNode())
19680       return Shuffle;
19681
19682     // Try recursively combining arbitrary sequences of x86 shuffle
19683     // instructions into higher-order shuffles. We do this after combining
19684     // specific PSHUF instruction sequences into their minimal form so that we
19685     // can evaluate how many specialized shuffle instructions are involved in
19686     // a particular chain.
19687     SmallVector<int, 1> NonceMask; // Just a placeholder.
19688     NonceMask.push_back(0);
19689     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19690                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19691                                       DCI, Subtarget))
19692       return SDValue(); // This routine will use CombineTo to replace N.
19693   }
19694
19695   return SDValue();
19696 }
19697
19698 /// PerformTruncateCombine - Converts truncate operation to
19699 /// a sequence of vector shuffle operations.
19700 /// It is possible when we truncate 256-bit vector to 128-bit vector
19701 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19702                                       TargetLowering::DAGCombinerInfo &DCI,
19703                                       const X86Subtarget *Subtarget)  {
19704   return SDValue();
19705 }
19706
19707 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19708 /// specific shuffle of a load can be folded into a single element load.
19709 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19710 /// shuffles have been customed lowered so we need to handle those here.
19711 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19712                                          TargetLowering::DAGCombinerInfo &DCI) {
19713   if (DCI.isBeforeLegalizeOps())
19714     return SDValue();
19715
19716   SDValue InVec = N->getOperand(0);
19717   SDValue EltNo = N->getOperand(1);
19718
19719   if (!isa<ConstantSDNode>(EltNo))
19720     return SDValue();
19721
19722   EVT VT = InVec.getValueType();
19723
19724   bool HasShuffleIntoBitcast = false;
19725   if (InVec.getOpcode() == ISD::BITCAST) {
19726     // Don't duplicate a load with other uses.
19727     if (!InVec.hasOneUse())
19728       return SDValue();
19729     EVT BCVT = InVec.getOperand(0).getValueType();
19730     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19731       return SDValue();
19732     InVec = InVec.getOperand(0);
19733     HasShuffleIntoBitcast = true;
19734   }
19735
19736   if (!isTargetShuffle(InVec.getOpcode()))
19737     return SDValue();
19738
19739   // Don't duplicate a load with other uses.
19740   if (!InVec.hasOneUse())
19741     return SDValue();
19742
19743   SmallVector<int, 16> ShuffleMask;
19744   bool UnaryShuffle;
19745   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19746                             UnaryShuffle))
19747     return SDValue();
19748
19749   // Select the input vector, guarding against out of range extract vector.
19750   unsigned NumElems = VT.getVectorNumElements();
19751   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19752   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19753   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19754                                          : InVec.getOperand(1);
19755
19756   // If inputs to shuffle are the same for both ops, then allow 2 uses
19757   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19758
19759   if (LdNode.getOpcode() == ISD::BITCAST) {
19760     // Don't duplicate a load with other uses.
19761     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19762       return SDValue();
19763
19764     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19765     LdNode = LdNode.getOperand(0);
19766   }
19767
19768   if (!ISD::isNormalLoad(LdNode.getNode()))
19769     return SDValue();
19770
19771   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19772
19773   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19774     return SDValue();
19775
19776   if (HasShuffleIntoBitcast) {
19777     // If there's a bitcast before the shuffle, check if the load type and
19778     // alignment is valid.
19779     unsigned Align = LN0->getAlignment();
19780     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19781     unsigned NewAlign = TLI.getDataLayout()->
19782       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19783
19784     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19785       return SDValue();
19786   }
19787
19788   // All checks match so transform back to vector_shuffle so that DAG combiner
19789   // can finish the job
19790   SDLoc dl(N);
19791
19792   // Create shuffle node taking into account the case that its a unary shuffle
19793   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19794   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19795                                  InVec.getOperand(0), Shuffle,
19796                                  &ShuffleMask[0]);
19797   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19798   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19799                      EltNo);
19800 }
19801
19802 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19803 /// generation and convert it from being a bunch of shuffles and extracts
19804 /// to a simple store and scalar loads to extract the elements.
19805 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19806                                          TargetLowering::DAGCombinerInfo &DCI) {
19807   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19808   if (NewOp.getNode())
19809     return NewOp;
19810
19811   SDValue InputVector = N->getOperand(0);
19812
19813   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19814   // from mmx to v2i32 has a single usage.
19815   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19816       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19817       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19818     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19819                        N->getValueType(0),
19820                        InputVector.getNode()->getOperand(0));
19821
19822   // Only operate on vectors of 4 elements, where the alternative shuffling
19823   // gets to be more expensive.
19824   if (InputVector.getValueType() != MVT::v4i32)
19825     return SDValue();
19826
19827   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19828   // single use which is a sign-extend or zero-extend, and all elements are
19829   // used.
19830   SmallVector<SDNode *, 4> Uses;
19831   unsigned ExtractedElements = 0;
19832   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19833        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19834     if (UI.getUse().getResNo() != InputVector.getResNo())
19835       return SDValue();
19836
19837     SDNode *Extract = *UI;
19838     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19839       return SDValue();
19840
19841     if (Extract->getValueType(0) != MVT::i32)
19842       return SDValue();
19843     if (!Extract->hasOneUse())
19844       return SDValue();
19845     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19846         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19847       return SDValue();
19848     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19849       return SDValue();
19850
19851     // Record which element was extracted.
19852     ExtractedElements |=
19853       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19854
19855     Uses.push_back(Extract);
19856   }
19857
19858   // If not all the elements were used, this may not be worthwhile.
19859   if (ExtractedElements != 15)
19860     return SDValue();
19861
19862   // Ok, we've now decided to do the transformation.
19863   SDLoc dl(InputVector);
19864
19865   // Store the value to a temporary stack slot.
19866   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19867   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19868                             MachinePointerInfo(), false, false, 0);
19869
19870   // Replace each use (extract) with a load of the appropriate element.
19871   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19872        UE = Uses.end(); UI != UE; ++UI) {
19873     SDNode *Extract = *UI;
19874
19875     // cOMpute the element's address.
19876     SDValue Idx = Extract->getOperand(1);
19877     unsigned EltSize =
19878         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19879     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19880     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19881     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19882
19883     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19884                                      StackPtr, OffsetVal);
19885
19886     // Load the scalar.
19887     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19888                                      ScalarAddr, MachinePointerInfo(),
19889                                      false, false, false, 0);
19890
19891     // Replace the exact with the load.
19892     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19893   }
19894
19895   // The replacement was made in place; don't return anything.
19896   return SDValue();
19897 }
19898
19899 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19900 static std::pair<unsigned, bool>
19901 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19902                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19903   if (!VT.isVector())
19904     return std::make_pair(0, false);
19905
19906   bool NeedSplit = false;
19907   switch (VT.getSimpleVT().SimpleTy) {
19908   default: return std::make_pair(0, false);
19909   case MVT::v32i8:
19910   case MVT::v16i16:
19911   case MVT::v8i32:
19912     if (!Subtarget->hasAVX2())
19913       NeedSplit = true;
19914     if (!Subtarget->hasAVX())
19915       return std::make_pair(0, false);
19916     break;
19917   case MVT::v16i8:
19918   case MVT::v8i16:
19919   case MVT::v4i32:
19920     if (!Subtarget->hasSSE2())
19921       return std::make_pair(0, false);
19922   }
19923
19924   // SSE2 has only a small subset of the operations.
19925   bool hasUnsigned = Subtarget->hasSSE41() ||
19926                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19927   bool hasSigned = Subtarget->hasSSE41() ||
19928                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19929
19930   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19931
19932   unsigned Opc = 0;
19933   // Check for x CC y ? x : y.
19934   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19935       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19936     switch (CC) {
19937     default: break;
19938     case ISD::SETULT:
19939     case ISD::SETULE:
19940       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19941     case ISD::SETUGT:
19942     case ISD::SETUGE:
19943       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19944     case ISD::SETLT:
19945     case ISD::SETLE:
19946       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19947     case ISD::SETGT:
19948     case ISD::SETGE:
19949       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19950     }
19951   // Check for x CC y ? y : x -- a min/max with reversed arms.
19952   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19953              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19954     switch (CC) {
19955     default: break;
19956     case ISD::SETULT:
19957     case ISD::SETULE:
19958       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19959     case ISD::SETUGT:
19960     case ISD::SETUGE:
19961       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19962     case ISD::SETLT:
19963     case ISD::SETLE:
19964       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19965     case ISD::SETGT:
19966     case ISD::SETGE:
19967       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19968     }
19969   }
19970
19971   return std::make_pair(Opc, NeedSplit);
19972 }
19973
19974 static SDValue
19975 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19976                                       const X86Subtarget *Subtarget) {
19977   SDLoc dl(N);
19978   SDValue Cond = N->getOperand(0);
19979   SDValue LHS = N->getOperand(1);
19980   SDValue RHS = N->getOperand(2);
19981
19982   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19983     SDValue CondSrc = Cond->getOperand(0);
19984     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19985       Cond = CondSrc->getOperand(0);
19986   }
19987
19988   MVT VT = N->getSimpleValueType(0);
19989   MVT EltVT = VT.getVectorElementType();
19990   unsigned NumElems = VT.getVectorNumElements();
19991   // There is no blend with immediate in AVX-512.
19992   if (VT.is512BitVector())
19993     return SDValue();
19994
19995   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19996     return SDValue();
19997   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19998     return SDValue();
19999
20000   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20001     return SDValue();
20002
20003   unsigned MaskValue = 0;
20004   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20005     return SDValue();
20006
20007   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20008   for (unsigned i = 0; i < NumElems; ++i) {
20009     // Be sure we emit undef where we can.
20010     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20011       ShuffleMask[i] = -1;
20012     else
20013       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20014   }
20015
20016   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20017 }
20018
20019 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20020 /// nodes.
20021 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20022                                     TargetLowering::DAGCombinerInfo &DCI,
20023                                     const X86Subtarget *Subtarget) {
20024   SDLoc DL(N);
20025   SDValue Cond = N->getOperand(0);
20026   // Get the LHS/RHS of the select.
20027   SDValue LHS = N->getOperand(1);
20028   SDValue RHS = N->getOperand(2);
20029   EVT VT = LHS.getValueType();
20030   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20031
20032   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20033   // instructions match the semantics of the common C idiom x<y?x:y but not
20034   // x<=y?x:y, because of how they handle negative zero (which can be
20035   // ignored in unsafe-math mode).
20036   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20037       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20038       (Subtarget->hasSSE2() ||
20039        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20040     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20041
20042     unsigned Opcode = 0;
20043     // Check for x CC y ? x : y.
20044     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20045         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20046       switch (CC) {
20047       default: break;
20048       case ISD::SETULT:
20049         // Converting this to a min would handle NaNs incorrectly, and swapping
20050         // the operands would cause it to handle comparisons between positive
20051         // and negative zero incorrectly.
20052         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20053           if (!DAG.getTarget().Options.UnsafeFPMath &&
20054               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20055             break;
20056           std::swap(LHS, RHS);
20057         }
20058         Opcode = X86ISD::FMIN;
20059         break;
20060       case ISD::SETOLE:
20061         // Converting this to a min would handle comparisons between positive
20062         // and negative zero incorrectly.
20063         if (!DAG.getTarget().Options.UnsafeFPMath &&
20064             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20065           break;
20066         Opcode = X86ISD::FMIN;
20067         break;
20068       case ISD::SETULE:
20069         // Converting this to a min would handle both negative zeros and NaNs
20070         // incorrectly, but we can swap the operands to fix both.
20071         std::swap(LHS, RHS);
20072       case ISD::SETOLT:
20073       case ISD::SETLT:
20074       case ISD::SETLE:
20075         Opcode = X86ISD::FMIN;
20076         break;
20077
20078       case ISD::SETOGE:
20079         // Converting this to a max would handle comparisons between positive
20080         // and negative zero incorrectly.
20081         if (!DAG.getTarget().Options.UnsafeFPMath &&
20082             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20083           break;
20084         Opcode = X86ISD::FMAX;
20085         break;
20086       case ISD::SETUGT:
20087         // Converting this to a max would handle NaNs incorrectly, and swapping
20088         // the operands would cause it to handle comparisons between positive
20089         // and negative zero incorrectly.
20090         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20091           if (!DAG.getTarget().Options.UnsafeFPMath &&
20092               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20093             break;
20094           std::swap(LHS, RHS);
20095         }
20096         Opcode = X86ISD::FMAX;
20097         break;
20098       case ISD::SETUGE:
20099         // Converting this to a max would handle both negative zeros and NaNs
20100         // incorrectly, but we can swap the operands to fix both.
20101         std::swap(LHS, RHS);
20102       case ISD::SETOGT:
20103       case ISD::SETGT:
20104       case ISD::SETGE:
20105         Opcode = X86ISD::FMAX;
20106         break;
20107       }
20108     // Check for x CC y ? y : x -- a min/max with reversed arms.
20109     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20110                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20111       switch (CC) {
20112       default: break;
20113       case ISD::SETOGE:
20114         // Converting this to a min would handle comparisons between positive
20115         // and negative zero incorrectly, and swapping the operands would
20116         // cause it to handle NaNs incorrectly.
20117         if (!DAG.getTarget().Options.UnsafeFPMath &&
20118             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20119           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20120             break;
20121           std::swap(LHS, RHS);
20122         }
20123         Opcode = X86ISD::FMIN;
20124         break;
20125       case ISD::SETUGT:
20126         // Converting this to a min would handle NaNs incorrectly.
20127         if (!DAG.getTarget().Options.UnsafeFPMath &&
20128             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20129           break;
20130         Opcode = X86ISD::FMIN;
20131         break;
20132       case ISD::SETUGE:
20133         // Converting this to a min would handle both negative zeros and NaNs
20134         // incorrectly, but we can swap the operands to fix both.
20135         std::swap(LHS, RHS);
20136       case ISD::SETOGT:
20137       case ISD::SETGT:
20138       case ISD::SETGE:
20139         Opcode = X86ISD::FMIN;
20140         break;
20141
20142       case ISD::SETULT:
20143         // Converting this to a max would handle NaNs incorrectly.
20144         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20145           break;
20146         Opcode = X86ISD::FMAX;
20147         break;
20148       case ISD::SETOLE:
20149         // Converting this to a max would handle comparisons between positive
20150         // and negative zero incorrectly, and swapping the operands would
20151         // cause it to handle NaNs incorrectly.
20152         if (!DAG.getTarget().Options.UnsafeFPMath &&
20153             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20154           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20155             break;
20156           std::swap(LHS, RHS);
20157         }
20158         Opcode = X86ISD::FMAX;
20159         break;
20160       case ISD::SETULE:
20161         // Converting this to a max would handle both negative zeros and NaNs
20162         // incorrectly, but we can swap the operands to fix both.
20163         std::swap(LHS, RHS);
20164       case ISD::SETOLT:
20165       case ISD::SETLT:
20166       case ISD::SETLE:
20167         Opcode = X86ISD::FMAX;
20168         break;
20169       }
20170     }
20171
20172     if (Opcode)
20173       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20174   }
20175
20176   EVT CondVT = Cond.getValueType();
20177   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20178       CondVT.getVectorElementType() == MVT::i1) {
20179     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20180     // lowering on AVX-512. In this case we convert it to
20181     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20182     // The same situation for all 128 and 256-bit vectors of i8 and i16
20183     EVT OpVT = LHS.getValueType();
20184     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20185         (OpVT.getVectorElementType() == MVT::i8 ||
20186          OpVT.getVectorElementType() == MVT::i16)) {
20187       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20188       DCI.AddToWorklist(Cond.getNode());
20189       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20190     }
20191   }
20192   // If this is a select between two integer constants, try to do some
20193   // optimizations.
20194   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20195     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20196       // Don't do this for crazy integer types.
20197       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20198         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20199         // so that TrueC (the true value) is larger than FalseC.
20200         bool NeedsCondInvert = false;
20201
20202         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20203             // Efficiently invertible.
20204             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20205              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20206               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20207           NeedsCondInvert = true;
20208           std::swap(TrueC, FalseC);
20209         }
20210
20211         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20212         if (FalseC->getAPIntValue() == 0 &&
20213             TrueC->getAPIntValue().isPowerOf2()) {
20214           if (NeedsCondInvert) // Invert the condition if needed.
20215             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20216                                DAG.getConstant(1, Cond.getValueType()));
20217
20218           // Zero extend the condition if needed.
20219           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20220
20221           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20222           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20223                              DAG.getConstant(ShAmt, MVT::i8));
20224         }
20225
20226         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20227         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20228           if (NeedsCondInvert) // Invert the condition if needed.
20229             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20230                                DAG.getConstant(1, Cond.getValueType()));
20231
20232           // Zero extend the condition if needed.
20233           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20234                              FalseC->getValueType(0), Cond);
20235           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20236                              SDValue(FalseC, 0));
20237         }
20238
20239         // Optimize cases that will turn into an LEA instruction.  This requires
20240         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20241         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20242           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20243           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20244
20245           bool isFastMultiplier = false;
20246           if (Diff < 10) {
20247             switch ((unsigned char)Diff) {
20248               default: break;
20249               case 1:  // result = add base, cond
20250               case 2:  // result = lea base(    , cond*2)
20251               case 3:  // result = lea base(cond, cond*2)
20252               case 4:  // result = lea base(    , cond*4)
20253               case 5:  // result = lea base(cond, cond*4)
20254               case 8:  // result = lea base(    , cond*8)
20255               case 9:  // result = lea base(cond, cond*8)
20256                 isFastMultiplier = true;
20257                 break;
20258             }
20259           }
20260
20261           if (isFastMultiplier) {
20262             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20263             if (NeedsCondInvert) // Invert the condition if needed.
20264               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20265                                  DAG.getConstant(1, Cond.getValueType()));
20266
20267             // Zero extend the condition if needed.
20268             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20269                                Cond);
20270             // Scale the condition by the difference.
20271             if (Diff != 1)
20272               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20273                                  DAG.getConstant(Diff, Cond.getValueType()));
20274
20275             // Add the base if non-zero.
20276             if (FalseC->getAPIntValue() != 0)
20277               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20278                                  SDValue(FalseC, 0));
20279             return Cond;
20280           }
20281         }
20282       }
20283   }
20284
20285   // Canonicalize max and min:
20286   // (x > y) ? x : y -> (x >= y) ? x : y
20287   // (x < y) ? x : y -> (x <= y) ? x : y
20288   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20289   // the need for an extra compare
20290   // against zero. e.g.
20291   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20292   // subl   %esi, %edi
20293   // testl  %edi, %edi
20294   // movl   $0, %eax
20295   // cmovgl %edi, %eax
20296   // =>
20297   // xorl   %eax, %eax
20298   // subl   %esi, $edi
20299   // cmovsl %eax, %edi
20300   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20301       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20302       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20303     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20304     switch (CC) {
20305     default: break;
20306     case ISD::SETLT:
20307     case ISD::SETGT: {
20308       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20309       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20310                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20311       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20312     }
20313     }
20314   }
20315
20316   // Early exit check
20317   if (!TLI.isTypeLegal(VT))
20318     return SDValue();
20319
20320   // Match VSELECTs into subs with unsigned saturation.
20321   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20322       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20323       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20324        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20325     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20326
20327     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20328     // left side invert the predicate to simplify logic below.
20329     SDValue Other;
20330     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20331       Other = RHS;
20332       CC = ISD::getSetCCInverse(CC, true);
20333     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20334       Other = LHS;
20335     }
20336
20337     if (Other.getNode() && Other->getNumOperands() == 2 &&
20338         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20339       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20340       SDValue CondRHS = Cond->getOperand(1);
20341
20342       // Look for a general sub with unsigned saturation first.
20343       // x >= y ? x-y : 0 --> subus x, y
20344       // x >  y ? x-y : 0 --> subus x, y
20345       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20346           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20347         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20348
20349       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20350         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20351           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20352             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20353               // If the RHS is a constant we have to reverse the const
20354               // canonicalization.
20355               // x > C-1 ? x+-C : 0 --> subus x, C
20356               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20357                   CondRHSConst->getAPIntValue() ==
20358                       (-OpRHSConst->getAPIntValue() - 1))
20359                 return DAG.getNode(
20360                     X86ISD::SUBUS, DL, VT, OpLHS,
20361                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20362
20363           // Another special case: If C was a sign bit, the sub has been
20364           // canonicalized into a xor.
20365           // FIXME: Would it be better to use computeKnownBits to determine
20366           //        whether it's safe to decanonicalize the xor?
20367           // x s< 0 ? x^C : 0 --> subus x, C
20368           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20369               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20370               OpRHSConst->getAPIntValue().isSignBit())
20371             // Note that we have to rebuild the RHS constant here to ensure we
20372             // don't rely on particular values of undef lanes.
20373             return DAG.getNode(
20374                 X86ISD::SUBUS, DL, VT, OpLHS,
20375                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20376         }
20377     }
20378   }
20379
20380   // Try to match a min/max vector operation.
20381   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20382     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20383     unsigned Opc = ret.first;
20384     bool NeedSplit = ret.second;
20385
20386     if (Opc && NeedSplit) {
20387       unsigned NumElems = VT.getVectorNumElements();
20388       // Extract the LHS vectors
20389       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20390       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20391
20392       // Extract the RHS vectors
20393       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20394       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20395
20396       // Create min/max for each subvector
20397       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20398       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20399
20400       // Merge the result
20401       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20402     } else if (Opc)
20403       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20404   }
20405
20406   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20407   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20408       // Check if SETCC has already been promoted
20409       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20410       // Check that condition value type matches vselect operand type
20411       CondVT == VT) { 
20412
20413     assert(Cond.getValueType().isVector() &&
20414            "vector select expects a vector selector!");
20415
20416     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20417     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20418
20419     if (!TValIsAllOnes && !FValIsAllZeros) {
20420       // Try invert the condition if true value is not all 1s and false value
20421       // is not all 0s.
20422       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20423       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20424
20425       if (TValIsAllZeros || FValIsAllOnes) {
20426         SDValue CC = Cond.getOperand(2);
20427         ISD::CondCode NewCC =
20428           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20429                                Cond.getOperand(0).getValueType().isInteger());
20430         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20431         std::swap(LHS, RHS);
20432         TValIsAllOnes = FValIsAllOnes;
20433         FValIsAllZeros = TValIsAllZeros;
20434       }
20435     }
20436
20437     if (TValIsAllOnes || FValIsAllZeros) {
20438       SDValue Ret;
20439
20440       if (TValIsAllOnes && FValIsAllZeros)
20441         Ret = Cond;
20442       else if (TValIsAllOnes)
20443         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20444                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20445       else if (FValIsAllZeros)
20446         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20447                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20448
20449       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20450     }
20451   }
20452
20453   // Try to fold this VSELECT into a MOVSS/MOVSD
20454   if (N->getOpcode() == ISD::VSELECT &&
20455       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20456     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20457         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20458       bool CanFold = false;
20459       unsigned NumElems = Cond.getNumOperands();
20460       SDValue A = LHS;
20461       SDValue B = RHS;
20462       
20463       if (isZero(Cond.getOperand(0))) {
20464         CanFold = true;
20465
20466         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20467         // fold (vselect <0,-1> -> (movsd A, B)
20468         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20469           CanFold = isAllOnes(Cond.getOperand(i));
20470       } else if (isAllOnes(Cond.getOperand(0))) {
20471         CanFold = true;
20472         std::swap(A, B);
20473
20474         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20475         // fold (vselect <-1,0> -> (movsd B, A)
20476         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20477           CanFold = isZero(Cond.getOperand(i));
20478       }
20479
20480       if (CanFold) {
20481         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20482           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20483         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20484       }
20485
20486       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20487         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20488         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20489         //                             (v2i64 (bitcast B)))))
20490         //
20491         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20492         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20493         //                             (v2f64 (bitcast B)))))
20494         //
20495         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20496         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20497         //                             (v2i64 (bitcast A)))))
20498         //
20499         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20500         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20501         //                             (v2f64 (bitcast A)))))
20502
20503         CanFold = (isZero(Cond.getOperand(0)) &&
20504                    isZero(Cond.getOperand(1)) &&
20505                    isAllOnes(Cond.getOperand(2)) &&
20506                    isAllOnes(Cond.getOperand(3)));
20507
20508         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20509             isAllOnes(Cond.getOperand(1)) &&
20510             isZero(Cond.getOperand(2)) &&
20511             isZero(Cond.getOperand(3))) {
20512           CanFold = true;
20513           std::swap(LHS, RHS);
20514         }
20515
20516         if (CanFold) {
20517           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20518           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20519           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20520           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20521                                                 NewB, DAG);
20522           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20523         }
20524       }
20525     }
20526   }
20527
20528   // If we know that this node is legal then we know that it is going to be
20529   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20530   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20531   // to simplify previous instructions.
20532   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20533       !DCI.isBeforeLegalize() &&
20534       // We explicitly check against v8i16 and v16i16 because, although
20535       // they're marked as Custom, they might only be legal when Cond is a
20536       // build_vector of constants. This will be taken care in a later
20537       // condition.
20538       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20539        VT != MVT::v8i16)) {
20540     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20541
20542     // Don't optimize vector selects that map to mask-registers.
20543     if (BitWidth == 1)
20544       return SDValue();
20545
20546     // Check all uses of that condition operand to check whether it will be
20547     // consumed by non-BLEND instructions, which may depend on all bits are set
20548     // properly.
20549     for (SDNode::use_iterator I = Cond->use_begin(),
20550                               E = Cond->use_end(); I != E; ++I)
20551       if (I->getOpcode() != ISD::VSELECT)
20552         // TODO: Add other opcodes eventually lowered into BLEND.
20553         return SDValue();
20554
20555     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20556     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20557
20558     APInt KnownZero, KnownOne;
20559     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20560                                           DCI.isBeforeLegalizeOps());
20561     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20562         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20563       DCI.CommitTargetLoweringOpt(TLO);
20564   }
20565
20566   // We should generate an X86ISD::BLENDI from a vselect if its argument
20567   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20568   // constants. This specific pattern gets generated when we split a
20569   // selector for a 512 bit vector in a machine without AVX512 (but with
20570   // 256-bit vectors), during legalization:
20571   //
20572   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20573   //
20574   // Iff we find this pattern and the build_vectors are built from
20575   // constants, we translate the vselect into a shuffle_vector that we
20576   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20577   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20578     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20579     if (Shuffle.getNode())
20580       return Shuffle;
20581   }
20582
20583   return SDValue();
20584 }
20585
20586 // Check whether a boolean test is testing a boolean value generated by
20587 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20588 // code.
20589 //
20590 // Simplify the following patterns:
20591 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20592 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20593 // to (Op EFLAGS Cond)
20594 //
20595 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20596 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20597 // to (Op EFLAGS !Cond)
20598 //
20599 // where Op could be BRCOND or CMOV.
20600 //
20601 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20602   // Quit if not CMP and SUB with its value result used.
20603   if (Cmp.getOpcode() != X86ISD::CMP &&
20604       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20605       return SDValue();
20606
20607   // Quit if not used as a boolean value.
20608   if (CC != X86::COND_E && CC != X86::COND_NE)
20609     return SDValue();
20610
20611   // Check CMP operands. One of them should be 0 or 1 and the other should be
20612   // an SetCC or extended from it.
20613   SDValue Op1 = Cmp.getOperand(0);
20614   SDValue Op2 = Cmp.getOperand(1);
20615
20616   SDValue SetCC;
20617   const ConstantSDNode* C = nullptr;
20618   bool needOppositeCond = (CC == X86::COND_E);
20619   bool checkAgainstTrue = false; // Is it a comparison against 1?
20620
20621   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20622     SetCC = Op2;
20623   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20624     SetCC = Op1;
20625   else // Quit if all operands are not constants.
20626     return SDValue();
20627
20628   if (C->getZExtValue() == 1) {
20629     needOppositeCond = !needOppositeCond;
20630     checkAgainstTrue = true;
20631   } else if (C->getZExtValue() != 0)
20632     // Quit if the constant is neither 0 or 1.
20633     return SDValue();
20634
20635   bool truncatedToBoolWithAnd = false;
20636   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20637   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20638          SetCC.getOpcode() == ISD::TRUNCATE ||
20639          SetCC.getOpcode() == ISD::AND) {
20640     if (SetCC.getOpcode() == ISD::AND) {
20641       int OpIdx = -1;
20642       ConstantSDNode *CS;
20643       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20644           CS->getZExtValue() == 1)
20645         OpIdx = 1;
20646       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20647           CS->getZExtValue() == 1)
20648         OpIdx = 0;
20649       if (OpIdx == -1)
20650         break;
20651       SetCC = SetCC.getOperand(OpIdx);
20652       truncatedToBoolWithAnd = true;
20653     } else
20654       SetCC = SetCC.getOperand(0);
20655   }
20656
20657   switch (SetCC.getOpcode()) {
20658   case X86ISD::SETCC_CARRY:
20659     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20660     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20661     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20662     // truncated to i1 using 'and'.
20663     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20664       break;
20665     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20666            "Invalid use of SETCC_CARRY!");
20667     // FALL THROUGH
20668   case X86ISD::SETCC:
20669     // Set the condition code or opposite one if necessary.
20670     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20671     if (needOppositeCond)
20672       CC = X86::GetOppositeBranchCondition(CC);
20673     return SetCC.getOperand(1);
20674   case X86ISD::CMOV: {
20675     // Check whether false/true value has canonical one, i.e. 0 or 1.
20676     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20677     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20678     // Quit if true value is not a constant.
20679     if (!TVal)
20680       return SDValue();
20681     // Quit if false value is not a constant.
20682     if (!FVal) {
20683       SDValue Op = SetCC.getOperand(0);
20684       // Skip 'zext' or 'trunc' node.
20685       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20686           Op.getOpcode() == ISD::TRUNCATE)
20687         Op = Op.getOperand(0);
20688       // A special case for rdrand/rdseed, where 0 is set if false cond is
20689       // found.
20690       if ((Op.getOpcode() != X86ISD::RDRAND &&
20691            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20692         return SDValue();
20693     }
20694     // Quit if false value is not the constant 0 or 1.
20695     bool FValIsFalse = true;
20696     if (FVal && FVal->getZExtValue() != 0) {
20697       if (FVal->getZExtValue() != 1)
20698         return SDValue();
20699       // If FVal is 1, opposite cond is needed.
20700       needOppositeCond = !needOppositeCond;
20701       FValIsFalse = false;
20702     }
20703     // Quit if TVal is not the constant opposite of FVal.
20704     if (FValIsFalse && TVal->getZExtValue() != 1)
20705       return SDValue();
20706     if (!FValIsFalse && TVal->getZExtValue() != 0)
20707       return SDValue();
20708     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20709     if (needOppositeCond)
20710       CC = X86::GetOppositeBranchCondition(CC);
20711     return SetCC.getOperand(3);
20712   }
20713   }
20714
20715   return SDValue();
20716 }
20717
20718 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20719 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20720                                   TargetLowering::DAGCombinerInfo &DCI,
20721                                   const X86Subtarget *Subtarget) {
20722   SDLoc DL(N);
20723
20724   // If the flag operand isn't dead, don't touch this CMOV.
20725   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20726     return SDValue();
20727
20728   SDValue FalseOp = N->getOperand(0);
20729   SDValue TrueOp = N->getOperand(1);
20730   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20731   SDValue Cond = N->getOperand(3);
20732
20733   if (CC == X86::COND_E || CC == X86::COND_NE) {
20734     switch (Cond.getOpcode()) {
20735     default: break;
20736     case X86ISD::BSR:
20737     case X86ISD::BSF:
20738       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20739       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20740         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20741     }
20742   }
20743
20744   SDValue Flags;
20745
20746   Flags = checkBoolTestSetCCCombine(Cond, CC);
20747   if (Flags.getNode() &&
20748       // Extra check as FCMOV only supports a subset of X86 cond.
20749       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20750     SDValue Ops[] = { FalseOp, TrueOp,
20751                       DAG.getConstant(CC, MVT::i8), Flags };
20752     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20753   }
20754
20755   // If this is a select between two integer constants, try to do some
20756   // optimizations.  Note that the operands are ordered the opposite of SELECT
20757   // operands.
20758   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20759     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20760       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20761       // larger than FalseC (the false value).
20762       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20763         CC = X86::GetOppositeBranchCondition(CC);
20764         std::swap(TrueC, FalseC);
20765         std::swap(TrueOp, FalseOp);
20766       }
20767
20768       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20769       // This is efficient for any integer data type (including i8/i16) and
20770       // shift amount.
20771       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20772         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20773                            DAG.getConstant(CC, MVT::i8), Cond);
20774
20775         // Zero extend the condition if needed.
20776         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20777
20778         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20779         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20780                            DAG.getConstant(ShAmt, MVT::i8));
20781         if (N->getNumValues() == 2)  // Dead flag value?
20782           return DCI.CombineTo(N, Cond, SDValue());
20783         return Cond;
20784       }
20785
20786       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20787       // for any integer data type, including i8/i16.
20788       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20789         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20790                            DAG.getConstant(CC, MVT::i8), Cond);
20791
20792         // Zero extend the condition if needed.
20793         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20794                            FalseC->getValueType(0), Cond);
20795         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20796                            SDValue(FalseC, 0));
20797
20798         if (N->getNumValues() == 2)  // Dead flag value?
20799           return DCI.CombineTo(N, Cond, SDValue());
20800         return Cond;
20801       }
20802
20803       // Optimize cases that will turn into an LEA instruction.  This requires
20804       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20805       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20806         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20807         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20808
20809         bool isFastMultiplier = false;
20810         if (Diff < 10) {
20811           switch ((unsigned char)Diff) {
20812           default: break;
20813           case 1:  // result = add base, cond
20814           case 2:  // result = lea base(    , cond*2)
20815           case 3:  // result = lea base(cond, cond*2)
20816           case 4:  // result = lea base(    , cond*4)
20817           case 5:  // result = lea base(cond, cond*4)
20818           case 8:  // result = lea base(    , cond*8)
20819           case 9:  // result = lea base(cond, cond*8)
20820             isFastMultiplier = true;
20821             break;
20822           }
20823         }
20824
20825         if (isFastMultiplier) {
20826           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20827           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20828                              DAG.getConstant(CC, MVT::i8), Cond);
20829           // Zero extend the condition if needed.
20830           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20831                              Cond);
20832           // Scale the condition by the difference.
20833           if (Diff != 1)
20834             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20835                                DAG.getConstant(Diff, Cond.getValueType()));
20836
20837           // Add the base if non-zero.
20838           if (FalseC->getAPIntValue() != 0)
20839             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20840                                SDValue(FalseC, 0));
20841           if (N->getNumValues() == 2)  // Dead flag value?
20842             return DCI.CombineTo(N, Cond, SDValue());
20843           return Cond;
20844         }
20845       }
20846     }
20847   }
20848
20849   // Handle these cases:
20850   //   (select (x != c), e, c) -> select (x != c), e, x),
20851   //   (select (x == c), c, e) -> select (x == c), x, e)
20852   // where the c is an integer constant, and the "select" is the combination
20853   // of CMOV and CMP.
20854   //
20855   // The rationale for this change is that the conditional-move from a constant
20856   // needs two instructions, however, conditional-move from a register needs
20857   // only one instruction.
20858   //
20859   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20860   //  some instruction-combining opportunities. This opt needs to be
20861   //  postponed as late as possible.
20862   //
20863   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20864     // the DCI.xxxx conditions are provided to postpone the optimization as
20865     // late as possible.
20866
20867     ConstantSDNode *CmpAgainst = nullptr;
20868     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20869         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20870         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20871
20872       if (CC == X86::COND_NE &&
20873           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20874         CC = X86::GetOppositeBranchCondition(CC);
20875         std::swap(TrueOp, FalseOp);
20876       }
20877
20878       if (CC == X86::COND_E &&
20879           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20880         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20881                           DAG.getConstant(CC, MVT::i8), Cond };
20882         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20883       }
20884     }
20885   }
20886
20887   return SDValue();
20888 }
20889
20890 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20891                                                 const X86Subtarget *Subtarget) {
20892   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20893   switch (IntNo) {
20894   default: return SDValue();
20895   // SSE/AVX/AVX2 blend intrinsics.
20896   case Intrinsic::x86_avx2_pblendvb:
20897   case Intrinsic::x86_avx2_pblendw:
20898   case Intrinsic::x86_avx2_pblendd_128:
20899   case Intrinsic::x86_avx2_pblendd_256:
20900     // Don't try to simplify this intrinsic if we don't have AVX2.
20901     if (!Subtarget->hasAVX2())
20902       return SDValue();
20903     // FALL-THROUGH
20904   case Intrinsic::x86_avx_blend_pd_256:
20905   case Intrinsic::x86_avx_blend_ps_256:
20906   case Intrinsic::x86_avx_blendv_pd_256:
20907   case Intrinsic::x86_avx_blendv_ps_256:
20908     // Don't try to simplify this intrinsic if we don't have AVX.
20909     if (!Subtarget->hasAVX())
20910       return SDValue();
20911     // FALL-THROUGH
20912   case Intrinsic::x86_sse41_pblendw:
20913   case Intrinsic::x86_sse41_blendpd:
20914   case Intrinsic::x86_sse41_blendps:
20915   case Intrinsic::x86_sse41_blendvps:
20916   case Intrinsic::x86_sse41_blendvpd:
20917   case Intrinsic::x86_sse41_pblendvb: {
20918     SDValue Op0 = N->getOperand(1);
20919     SDValue Op1 = N->getOperand(2);
20920     SDValue Mask = N->getOperand(3);
20921
20922     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20923     if (!Subtarget->hasSSE41())
20924       return SDValue();
20925
20926     // fold (blend A, A, Mask) -> A
20927     if (Op0 == Op1)
20928       return Op0;
20929     // fold (blend A, B, allZeros) -> A
20930     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20931       return Op0;
20932     // fold (blend A, B, allOnes) -> B
20933     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20934       return Op1;
20935     
20936     // Simplify the case where the mask is a constant i32 value.
20937     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20938       if (C->isNullValue())
20939         return Op0;
20940       if (C->isAllOnesValue())
20941         return Op1;
20942     }
20943
20944     return SDValue();
20945   }
20946
20947   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20948   case Intrinsic::x86_sse2_psrai_w:
20949   case Intrinsic::x86_sse2_psrai_d:
20950   case Intrinsic::x86_avx2_psrai_w:
20951   case Intrinsic::x86_avx2_psrai_d:
20952   case Intrinsic::x86_sse2_psra_w:
20953   case Intrinsic::x86_sse2_psra_d:
20954   case Intrinsic::x86_avx2_psra_w:
20955   case Intrinsic::x86_avx2_psra_d: {
20956     SDValue Op0 = N->getOperand(1);
20957     SDValue Op1 = N->getOperand(2);
20958     EVT VT = Op0.getValueType();
20959     assert(VT.isVector() && "Expected a vector type!");
20960
20961     if (isa<BuildVectorSDNode>(Op1))
20962       Op1 = Op1.getOperand(0);
20963
20964     if (!isa<ConstantSDNode>(Op1))
20965       return SDValue();
20966
20967     EVT SVT = VT.getVectorElementType();
20968     unsigned SVTBits = SVT.getSizeInBits();
20969
20970     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20971     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20972     uint64_t ShAmt = C.getZExtValue();
20973
20974     // Don't try to convert this shift into a ISD::SRA if the shift
20975     // count is bigger than or equal to the element size.
20976     if (ShAmt >= SVTBits)
20977       return SDValue();
20978
20979     // Trivial case: if the shift count is zero, then fold this
20980     // into the first operand.
20981     if (ShAmt == 0)
20982       return Op0;
20983
20984     // Replace this packed shift intrinsic with a target independent
20985     // shift dag node.
20986     SDValue Splat = DAG.getConstant(C, VT);
20987     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20988   }
20989   }
20990 }
20991
20992 /// PerformMulCombine - Optimize a single multiply with constant into two
20993 /// in order to implement it with two cheaper instructions, e.g.
20994 /// LEA + SHL, LEA + LEA.
20995 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20996                                  TargetLowering::DAGCombinerInfo &DCI) {
20997   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20998     return SDValue();
20999
21000   EVT VT = N->getValueType(0);
21001   if (VT != MVT::i64)
21002     return SDValue();
21003
21004   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21005   if (!C)
21006     return SDValue();
21007   uint64_t MulAmt = C->getZExtValue();
21008   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21009     return SDValue();
21010
21011   uint64_t MulAmt1 = 0;
21012   uint64_t MulAmt2 = 0;
21013   if ((MulAmt % 9) == 0) {
21014     MulAmt1 = 9;
21015     MulAmt2 = MulAmt / 9;
21016   } else if ((MulAmt % 5) == 0) {
21017     MulAmt1 = 5;
21018     MulAmt2 = MulAmt / 5;
21019   } else if ((MulAmt % 3) == 0) {
21020     MulAmt1 = 3;
21021     MulAmt2 = MulAmt / 3;
21022   }
21023   if (MulAmt2 &&
21024       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21025     SDLoc DL(N);
21026
21027     if (isPowerOf2_64(MulAmt2) &&
21028         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21029       // If second multiplifer is pow2, issue it first. We want the multiply by
21030       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21031       // is an add.
21032       std::swap(MulAmt1, MulAmt2);
21033
21034     SDValue NewMul;
21035     if (isPowerOf2_64(MulAmt1))
21036       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21037                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21038     else
21039       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21040                            DAG.getConstant(MulAmt1, VT));
21041
21042     if (isPowerOf2_64(MulAmt2))
21043       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21044                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21045     else
21046       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21047                            DAG.getConstant(MulAmt2, VT));
21048
21049     // Do not add new nodes to DAG combiner worklist.
21050     DCI.CombineTo(N, NewMul, false);
21051   }
21052   return SDValue();
21053 }
21054
21055 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21056   SDValue N0 = N->getOperand(0);
21057   SDValue N1 = N->getOperand(1);
21058   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21059   EVT VT = N0.getValueType();
21060
21061   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21062   // since the result of setcc_c is all zero's or all ones.
21063   if (VT.isInteger() && !VT.isVector() &&
21064       N1C && N0.getOpcode() == ISD::AND &&
21065       N0.getOperand(1).getOpcode() == ISD::Constant) {
21066     SDValue N00 = N0.getOperand(0);
21067     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21068         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21069           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21070          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21071       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21072       APInt ShAmt = N1C->getAPIntValue();
21073       Mask = Mask.shl(ShAmt);
21074       if (Mask != 0)
21075         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21076                            N00, DAG.getConstant(Mask, VT));
21077     }
21078   }
21079
21080   // Hardware support for vector shifts is sparse which makes us scalarize the
21081   // vector operations in many cases. Also, on sandybridge ADD is faster than
21082   // shl.
21083   // (shl V, 1) -> add V,V
21084   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21085     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21086       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21087       // We shift all of the values by one. In many cases we do not have
21088       // hardware support for this operation. This is better expressed as an ADD
21089       // of two values.
21090       if (N1SplatC->getZExtValue() == 1)
21091         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21092     }
21093
21094   return SDValue();
21095 }
21096
21097 /// \brief Returns a vector of 0s if the node in input is a vector logical
21098 /// shift by a constant amount which is known to be bigger than or equal
21099 /// to the vector element size in bits.
21100 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21101                                       const X86Subtarget *Subtarget) {
21102   EVT VT = N->getValueType(0);
21103
21104   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21105       (!Subtarget->hasInt256() ||
21106        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21107     return SDValue();
21108
21109   SDValue Amt = N->getOperand(1);
21110   SDLoc DL(N);
21111   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21112     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21113       APInt ShiftAmt = AmtSplat->getAPIntValue();
21114       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21115
21116       // SSE2/AVX2 logical shifts always return a vector of 0s
21117       // if the shift amount is bigger than or equal to
21118       // the element size. The constant shift amount will be
21119       // encoded as a 8-bit immediate.
21120       if (ShiftAmt.trunc(8).uge(MaxAmount))
21121         return getZeroVector(VT, Subtarget, DAG, DL);
21122     }
21123
21124   return SDValue();
21125 }
21126
21127 /// PerformShiftCombine - Combine shifts.
21128 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21129                                    TargetLowering::DAGCombinerInfo &DCI,
21130                                    const X86Subtarget *Subtarget) {
21131   if (N->getOpcode() == ISD::SHL) {
21132     SDValue V = PerformSHLCombine(N, DAG);
21133     if (V.getNode()) return V;
21134   }
21135
21136   if (N->getOpcode() != ISD::SRA) {
21137     // Try to fold this logical shift into a zero vector.
21138     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21139     if (V.getNode()) return V;
21140   }
21141
21142   return SDValue();
21143 }
21144
21145 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21146 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21147 // and friends.  Likewise for OR -> CMPNEQSS.
21148 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21149                             TargetLowering::DAGCombinerInfo &DCI,
21150                             const X86Subtarget *Subtarget) {
21151   unsigned opcode;
21152
21153   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21154   // we're requiring SSE2 for both.
21155   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21156     SDValue N0 = N->getOperand(0);
21157     SDValue N1 = N->getOperand(1);
21158     SDValue CMP0 = N0->getOperand(1);
21159     SDValue CMP1 = N1->getOperand(1);
21160     SDLoc DL(N);
21161
21162     // The SETCCs should both refer to the same CMP.
21163     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21164       return SDValue();
21165
21166     SDValue CMP00 = CMP0->getOperand(0);
21167     SDValue CMP01 = CMP0->getOperand(1);
21168     EVT     VT    = CMP00.getValueType();
21169
21170     if (VT == MVT::f32 || VT == MVT::f64) {
21171       bool ExpectingFlags = false;
21172       // Check for any users that want flags:
21173       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21174            !ExpectingFlags && UI != UE; ++UI)
21175         switch (UI->getOpcode()) {
21176         default:
21177         case ISD::BR_CC:
21178         case ISD::BRCOND:
21179         case ISD::SELECT:
21180           ExpectingFlags = true;
21181           break;
21182         case ISD::CopyToReg:
21183         case ISD::SIGN_EXTEND:
21184         case ISD::ZERO_EXTEND:
21185         case ISD::ANY_EXTEND:
21186           break;
21187         }
21188
21189       if (!ExpectingFlags) {
21190         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21191         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21192
21193         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21194           X86::CondCode tmp = cc0;
21195           cc0 = cc1;
21196           cc1 = tmp;
21197         }
21198
21199         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21200             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21201           // FIXME: need symbolic constants for these magic numbers.
21202           // See X86ATTInstPrinter.cpp:printSSECC().
21203           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21204           if (Subtarget->hasAVX512()) {
21205             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21206                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21207             if (N->getValueType(0) != MVT::i1)
21208               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21209                                  FSetCC);
21210             return FSetCC;
21211           }
21212           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21213                                               CMP00.getValueType(), CMP00, CMP01,
21214                                               DAG.getConstant(x86cc, MVT::i8));
21215
21216           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21217           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21218
21219           if (is64BitFP && !Subtarget->is64Bit()) {
21220             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21221             // 64-bit integer, since that's not a legal type. Since
21222             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21223             // bits, but can do this little dance to extract the lowest 32 bits
21224             // and work with those going forward.
21225             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21226                                            OnesOrZeroesF);
21227             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21228                                            Vector64);
21229             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21230                                         Vector32, DAG.getIntPtrConstant(0));
21231             IntVT = MVT::i32;
21232           }
21233
21234           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21235           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21236                                       DAG.getConstant(1, IntVT));
21237           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21238           return OneBitOfTruth;
21239         }
21240       }
21241     }
21242   }
21243   return SDValue();
21244 }
21245
21246 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21247 /// so it can be folded inside ANDNP.
21248 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21249   EVT VT = N->getValueType(0);
21250
21251   // Match direct AllOnes for 128 and 256-bit vectors
21252   if (ISD::isBuildVectorAllOnes(N))
21253     return true;
21254
21255   // Look through a bit convert.
21256   if (N->getOpcode() == ISD::BITCAST)
21257     N = N->getOperand(0).getNode();
21258
21259   // Sometimes the operand may come from a insert_subvector building a 256-bit
21260   // allones vector
21261   if (VT.is256BitVector() &&
21262       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21263     SDValue V1 = N->getOperand(0);
21264     SDValue V2 = N->getOperand(1);
21265
21266     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21267         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21268         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21269         ISD::isBuildVectorAllOnes(V2.getNode()))
21270       return true;
21271   }
21272
21273   return false;
21274 }
21275
21276 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21277 // register. In most cases we actually compare or select YMM-sized registers
21278 // and mixing the two types creates horrible code. This method optimizes
21279 // some of the transition sequences.
21280 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21281                                  TargetLowering::DAGCombinerInfo &DCI,
21282                                  const X86Subtarget *Subtarget) {
21283   EVT VT = N->getValueType(0);
21284   if (!VT.is256BitVector())
21285     return SDValue();
21286
21287   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21288           N->getOpcode() == ISD::ZERO_EXTEND ||
21289           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21290
21291   SDValue Narrow = N->getOperand(0);
21292   EVT NarrowVT = Narrow->getValueType(0);
21293   if (!NarrowVT.is128BitVector())
21294     return SDValue();
21295
21296   if (Narrow->getOpcode() != ISD::XOR &&
21297       Narrow->getOpcode() != ISD::AND &&
21298       Narrow->getOpcode() != ISD::OR)
21299     return SDValue();
21300
21301   SDValue N0  = Narrow->getOperand(0);
21302   SDValue N1  = Narrow->getOperand(1);
21303   SDLoc DL(Narrow);
21304
21305   // The Left side has to be a trunc.
21306   if (N0.getOpcode() != ISD::TRUNCATE)
21307     return SDValue();
21308
21309   // The type of the truncated inputs.
21310   EVT WideVT = N0->getOperand(0)->getValueType(0);
21311   if (WideVT != VT)
21312     return SDValue();
21313
21314   // The right side has to be a 'trunc' or a constant vector.
21315   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21316   ConstantSDNode *RHSConstSplat = nullptr;
21317   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21318     RHSConstSplat = RHSBV->getConstantSplatNode();
21319   if (!RHSTrunc && !RHSConstSplat)
21320     return SDValue();
21321
21322   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21323
21324   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21325     return SDValue();
21326
21327   // Set N0 and N1 to hold the inputs to the new wide operation.
21328   N0 = N0->getOperand(0);
21329   if (RHSConstSplat) {
21330     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21331                      SDValue(RHSConstSplat, 0));
21332     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21333     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21334   } else if (RHSTrunc) {
21335     N1 = N1->getOperand(0);
21336   }
21337
21338   // Generate the wide operation.
21339   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21340   unsigned Opcode = N->getOpcode();
21341   switch (Opcode) {
21342   case ISD::ANY_EXTEND:
21343     return Op;
21344   case ISD::ZERO_EXTEND: {
21345     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21346     APInt Mask = APInt::getAllOnesValue(InBits);
21347     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21348     return DAG.getNode(ISD::AND, DL, VT,
21349                        Op, DAG.getConstant(Mask, VT));
21350   }
21351   case ISD::SIGN_EXTEND:
21352     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21353                        Op, DAG.getValueType(NarrowVT));
21354   default:
21355     llvm_unreachable("Unexpected opcode");
21356   }
21357 }
21358
21359 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21360                                  TargetLowering::DAGCombinerInfo &DCI,
21361                                  const X86Subtarget *Subtarget) {
21362   EVT VT = N->getValueType(0);
21363   if (DCI.isBeforeLegalizeOps())
21364     return SDValue();
21365
21366   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21367   if (R.getNode())
21368     return R;
21369
21370   // Create BEXTR instructions
21371   // BEXTR is ((X >> imm) & (2**size-1))
21372   if (VT == MVT::i32 || VT == MVT::i64) {
21373     SDValue N0 = N->getOperand(0);
21374     SDValue N1 = N->getOperand(1);
21375     SDLoc DL(N);
21376
21377     // Check for BEXTR.
21378     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21379         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21380       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21381       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21382       if (MaskNode && ShiftNode) {
21383         uint64_t Mask = MaskNode->getZExtValue();
21384         uint64_t Shift = ShiftNode->getZExtValue();
21385         if (isMask_64(Mask)) {
21386           uint64_t MaskSize = CountPopulation_64(Mask);
21387           if (Shift + MaskSize <= VT.getSizeInBits())
21388             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21389                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21390         }
21391       }
21392     } // BEXTR
21393
21394     return SDValue();
21395   }
21396
21397   // Want to form ANDNP nodes:
21398   // 1) In the hopes of then easily combining them with OR and AND nodes
21399   //    to form PBLEND/PSIGN.
21400   // 2) To match ANDN packed intrinsics
21401   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21402     return SDValue();
21403
21404   SDValue N0 = N->getOperand(0);
21405   SDValue N1 = N->getOperand(1);
21406   SDLoc DL(N);
21407
21408   // Check LHS for vnot
21409   if (N0.getOpcode() == ISD::XOR &&
21410       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21411       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21412     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21413
21414   // Check RHS for vnot
21415   if (N1.getOpcode() == ISD::XOR &&
21416       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21417       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21418     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21419
21420   return SDValue();
21421 }
21422
21423 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21424                                 TargetLowering::DAGCombinerInfo &DCI,
21425                                 const X86Subtarget *Subtarget) {
21426   if (DCI.isBeforeLegalizeOps())
21427     return SDValue();
21428
21429   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21430   if (R.getNode())
21431     return R;
21432
21433   SDValue N0 = N->getOperand(0);
21434   SDValue N1 = N->getOperand(1);
21435   EVT VT = N->getValueType(0);
21436
21437   // look for psign/blend
21438   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21439     if (!Subtarget->hasSSSE3() ||
21440         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21441       return SDValue();
21442
21443     // Canonicalize pandn to RHS
21444     if (N0.getOpcode() == X86ISD::ANDNP)
21445       std::swap(N0, N1);
21446     // or (and (m, y), (pandn m, x))
21447     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21448       SDValue Mask = N1.getOperand(0);
21449       SDValue X    = N1.getOperand(1);
21450       SDValue Y;
21451       if (N0.getOperand(0) == Mask)
21452         Y = N0.getOperand(1);
21453       if (N0.getOperand(1) == Mask)
21454         Y = N0.getOperand(0);
21455
21456       // Check to see if the mask appeared in both the AND and ANDNP and
21457       if (!Y.getNode())
21458         return SDValue();
21459
21460       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21461       // Look through mask bitcast.
21462       if (Mask.getOpcode() == ISD::BITCAST)
21463         Mask = Mask.getOperand(0);
21464       if (X.getOpcode() == ISD::BITCAST)
21465         X = X.getOperand(0);
21466       if (Y.getOpcode() == ISD::BITCAST)
21467         Y = Y.getOperand(0);
21468
21469       EVT MaskVT = Mask.getValueType();
21470
21471       // Validate that the Mask operand is a vector sra node.
21472       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21473       // there is no psrai.b
21474       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21475       unsigned SraAmt = ~0;
21476       if (Mask.getOpcode() == ISD::SRA) {
21477         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21478           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21479             SraAmt = AmtConst->getZExtValue();
21480       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21481         SDValue SraC = Mask.getOperand(1);
21482         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21483       }
21484       if ((SraAmt + 1) != EltBits)
21485         return SDValue();
21486
21487       SDLoc DL(N);
21488
21489       // Now we know we at least have a plendvb with the mask val.  See if
21490       // we can form a psignb/w/d.
21491       // psign = x.type == y.type == mask.type && y = sub(0, x);
21492       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21493           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21494           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21495         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21496                "Unsupported VT for PSIGN");
21497         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21498         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21499       }
21500       // PBLENDVB only available on SSE 4.1
21501       if (!Subtarget->hasSSE41())
21502         return SDValue();
21503
21504       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21505
21506       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21507       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21508       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21509       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21510       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21511     }
21512   }
21513
21514   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21515     return SDValue();
21516
21517   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21518   MachineFunction &MF = DAG.getMachineFunction();
21519   bool OptForSize = MF.getFunction()->getAttributes().
21520     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21521
21522   // SHLD/SHRD instructions have lower register pressure, but on some
21523   // platforms they have higher latency than the equivalent
21524   // series of shifts/or that would otherwise be generated.
21525   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21526   // have higher latencies and we are not optimizing for size.
21527   if (!OptForSize && Subtarget->isSHLDSlow())
21528     return SDValue();
21529
21530   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21531     std::swap(N0, N1);
21532   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21533     return SDValue();
21534   if (!N0.hasOneUse() || !N1.hasOneUse())
21535     return SDValue();
21536
21537   SDValue ShAmt0 = N0.getOperand(1);
21538   if (ShAmt0.getValueType() != MVT::i8)
21539     return SDValue();
21540   SDValue ShAmt1 = N1.getOperand(1);
21541   if (ShAmt1.getValueType() != MVT::i8)
21542     return SDValue();
21543   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21544     ShAmt0 = ShAmt0.getOperand(0);
21545   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21546     ShAmt1 = ShAmt1.getOperand(0);
21547
21548   SDLoc DL(N);
21549   unsigned Opc = X86ISD::SHLD;
21550   SDValue Op0 = N0.getOperand(0);
21551   SDValue Op1 = N1.getOperand(0);
21552   if (ShAmt0.getOpcode() == ISD::SUB) {
21553     Opc = X86ISD::SHRD;
21554     std::swap(Op0, Op1);
21555     std::swap(ShAmt0, ShAmt1);
21556   }
21557
21558   unsigned Bits = VT.getSizeInBits();
21559   if (ShAmt1.getOpcode() == ISD::SUB) {
21560     SDValue Sum = ShAmt1.getOperand(0);
21561     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21562       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21563       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21564         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21565       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21566         return DAG.getNode(Opc, DL, VT,
21567                            Op0, Op1,
21568                            DAG.getNode(ISD::TRUNCATE, DL,
21569                                        MVT::i8, ShAmt0));
21570     }
21571   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21572     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21573     if (ShAmt0C &&
21574         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21575       return DAG.getNode(Opc, DL, VT,
21576                          N0.getOperand(0), N1.getOperand(0),
21577                          DAG.getNode(ISD::TRUNCATE, DL,
21578                                        MVT::i8, ShAmt0));
21579   }
21580
21581   return SDValue();
21582 }
21583
21584 // Generate NEG and CMOV for integer abs.
21585 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21586   EVT VT = N->getValueType(0);
21587
21588   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21589   // 8-bit integer abs to NEG and CMOV.
21590   if (VT.isInteger() && VT.getSizeInBits() == 8)
21591     return SDValue();
21592
21593   SDValue N0 = N->getOperand(0);
21594   SDValue N1 = N->getOperand(1);
21595   SDLoc DL(N);
21596
21597   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21598   // and change it to SUB and CMOV.
21599   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21600       N0.getOpcode() == ISD::ADD &&
21601       N0.getOperand(1) == N1 &&
21602       N1.getOpcode() == ISD::SRA &&
21603       N1.getOperand(0) == N0.getOperand(0))
21604     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21605       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21606         // Generate SUB & CMOV.
21607         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21608                                   DAG.getConstant(0, VT), N0.getOperand(0));
21609
21610         SDValue Ops[] = { N0.getOperand(0), Neg,
21611                           DAG.getConstant(X86::COND_GE, MVT::i8),
21612                           SDValue(Neg.getNode(), 1) };
21613         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21614       }
21615   return SDValue();
21616 }
21617
21618 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21619 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21620                                  TargetLowering::DAGCombinerInfo &DCI,
21621                                  const X86Subtarget *Subtarget) {
21622   if (DCI.isBeforeLegalizeOps())
21623     return SDValue();
21624
21625   if (Subtarget->hasCMov()) {
21626     SDValue RV = performIntegerAbsCombine(N, DAG);
21627     if (RV.getNode())
21628       return RV;
21629   }
21630
21631   return SDValue();
21632 }
21633
21634 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21635 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21636                                   TargetLowering::DAGCombinerInfo &DCI,
21637                                   const X86Subtarget *Subtarget) {
21638   LoadSDNode *Ld = cast<LoadSDNode>(N);
21639   EVT RegVT = Ld->getValueType(0);
21640   EVT MemVT = Ld->getMemoryVT();
21641   SDLoc dl(Ld);
21642   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21643
21644   // On Sandybridge unaligned 256bit loads are inefficient.
21645   ISD::LoadExtType Ext = Ld->getExtensionType();
21646   unsigned Alignment = Ld->getAlignment();
21647   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21648   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21649       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21650     unsigned NumElems = RegVT.getVectorNumElements();
21651     if (NumElems < 2)
21652       return SDValue();
21653
21654     SDValue Ptr = Ld->getBasePtr();
21655     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21656
21657     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21658                                   NumElems/2);
21659     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21660                                 Ld->getPointerInfo(), Ld->isVolatile(),
21661                                 Ld->isNonTemporal(), Ld->isInvariant(),
21662                                 Alignment);
21663     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21664     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21665                                 Ld->getPointerInfo(), Ld->isVolatile(),
21666                                 Ld->isNonTemporal(), Ld->isInvariant(),
21667                                 std::min(16U, Alignment));
21668     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21669                              Load1.getValue(1),
21670                              Load2.getValue(1));
21671
21672     SDValue NewVec = DAG.getUNDEF(RegVT);
21673     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21674     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21675     return DCI.CombineTo(N, NewVec, TF, true);
21676   }
21677
21678   return SDValue();
21679 }
21680
21681 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21682 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21683                                    const X86Subtarget *Subtarget) {
21684   StoreSDNode *St = cast<StoreSDNode>(N);
21685   EVT VT = St->getValue().getValueType();
21686   EVT StVT = St->getMemoryVT();
21687   SDLoc dl(St);
21688   SDValue StoredVal = St->getOperand(1);
21689   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21690
21691   // If we are saving a concatenation of two XMM registers, perform two stores.
21692   // On Sandy Bridge, 256-bit memory operations are executed by two
21693   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21694   // memory  operation.
21695   unsigned Alignment = St->getAlignment();
21696   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21697   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21698       StVT == VT && !IsAligned) {
21699     unsigned NumElems = VT.getVectorNumElements();
21700     if (NumElems < 2)
21701       return SDValue();
21702
21703     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21704     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21705
21706     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21707     SDValue Ptr0 = St->getBasePtr();
21708     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21709
21710     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21711                                 St->getPointerInfo(), St->isVolatile(),
21712                                 St->isNonTemporal(), Alignment);
21713     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21714                                 St->getPointerInfo(), St->isVolatile(),
21715                                 St->isNonTemporal(),
21716                                 std::min(16U, Alignment));
21717     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21718   }
21719
21720   // Optimize trunc store (of multiple scalars) to shuffle and store.
21721   // First, pack all of the elements in one place. Next, store to memory
21722   // in fewer chunks.
21723   if (St->isTruncatingStore() && VT.isVector()) {
21724     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21725     unsigned NumElems = VT.getVectorNumElements();
21726     assert(StVT != VT && "Cannot truncate to the same type");
21727     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21728     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21729
21730     // From, To sizes and ElemCount must be pow of two
21731     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21732     // We are going to use the original vector elt for storing.
21733     // Accumulated smaller vector elements must be a multiple of the store size.
21734     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21735
21736     unsigned SizeRatio  = FromSz / ToSz;
21737
21738     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21739
21740     // Create a type on which we perform the shuffle
21741     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21742             StVT.getScalarType(), NumElems*SizeRatio);
21743
21744     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21745
21746     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21747     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21748     for (unsigned i = 0; i != NumElems; ++i)
21749       ShuffleVec[i] = i * SizeRatio;
21750
21751     // Can't shuffle using an illegal type.
21752     if (!TLI.isTypeLegal(WideVecVT))
21753       return SDValue();
21754
21755     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21756                                          DAG.getUNDEF(WideVecVT),
21757                                          &ShuffleVec[0]);
21758     // At this point all of the data is stored at the bottom of the
21759     // register. We now need to save it to mem.
21760
21761     // Find the largest store unit
21762     MVT StoreType = MVT::i8;
21763     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21764          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21765       MVT Tp = (MVT::SimpleValueType)tp;
21766       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21767         StoreType = Tp;
21768     }
21769
21770     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21771     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21772         (64 <= NumElems * ToSz))
21773       StoreType = MVT::f64;
21774
21775     // Bitcast the original vector into a vector of store-size units
21776     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21777             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21778     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21779     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21780     SmallVector<SDValue, 8> Chains;
21781     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21782                                         TLI.getPointerTy());
21783     SDValue Ptr = St->getBasePtr();
21784
21785     // Perform one or more big stores into memory.
21786     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21787       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21788                                    StoreType, ShuffWide,
21789                                    DAG.getIntPtrConstant(i));
21790       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21791                                 St->getPointerInfo(), St->isVolatile(),
21792                                 St->isNonTemporal(), St->getAlignment());
21793       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21794       Chains.push_back(Ch);
21795     }
21796
21797     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21798   }
21799
21800   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21801   // the FP state in cases where an emms may be missing.
21802   // A preferable solution to the general problem is to figure out the right
21803   // places to insert EMMS.  This qualifies as a quick hack.
21804
21805   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21806   if (VT.getSizeInBits() != 64)
21807     return SDValue();
21808
21809   const Function *F = DAG.getMachineFunction().getFunction();
21810   bool NoImplicitFloatOps = F->getAttributes().
21811     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21812   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21813                      && Subtarget->hasSSE2();
21814   if ((VT.isVector() ||
21815        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21816       isa<LoadSDNode>(St->getValue()) &&
21817       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21818       St->getChain().hasOneUse() && !St->isVolatile()) {
21819     SDNode* LdVal = St->getValue().getNode();
21820     LoadSDNode *Ld = nullptr;
21821     int TokenFactorIndex = -1;
21822     SmallVector<SDValue, 8> Ops;
21823     SDNode* ChainVal = St->getChain().getNode();
21824     // Must be a store of a load.  We currently handle two cases:  the load
21825     // is a direct child, and it's under an intervening TokenFactor.  It is
21826     // possible to dig deeper under nested TokenFactors.
21827     if (ChainVal == LdVal)
21828       Ld = cast<LoadSDNode>(St->getChain());
21829     else if (St->getValue().hasOneUse() &&
21830              ChainVal->getOpcode() == ISD::TokenFactor) {
21831       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21832         if (ChainVal->getOperand(i).getNode() == LdVal) {
21833           TokenFactorIndex = i;
21834           Ld = cast<LoadSDNode>(St->getValue());
21835         } else
21836           Ops.push_back(ChainVal->getOperand(i));
21837       }
21838     }
21839
21840     if (!Ld || !ISD::isNormalLoad(Ld))
21841       return SDValue();
21842
21843     // If this is not the MMX case, i.e. we are just turning i64 load/store
21844     // into f64 load/store, avoid the transformation if there are multiple
21845     // uses of the loaded value.
21846     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21847       return SDValue();
21848
21849     SDLoc LdDL(Ld);
21850     SDLoc StDL(N);
21851     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21852     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21853     // pair instead.
21854     if (Subtarget->is64Bit() || F64IsLegal) {
21855       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21856       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21857                                   Ld->getPointerInfo(), Ld->isVolatile(),
21858                                   Ld->isNonTemporal(), Ld->isInvariant(),
21859                                   Ld->getAlignment());
21860       SDValue NewChain = NewLd.getValue(1);
21861       if (TokenFactorIndex != -1) {
21862         Ops.push_back(NewChain);
21863         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21864       }
21865       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21866                           St->getPointerInfo(),
21867                           St->isVolatile(), St->isNonTemporal(),
21868                           St->getAlignment());
21869     }
21870
21871     // Otherwise, lower to two pairs of 32-bit loads / stores.
21872     SDValue LoAddr = Ld->getBasePtr();
21873     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21874                                  DAG.getConstant(4, MVT::i32));
21875
21876     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21877                                Ld->getPointerInfo(),
21878                                Ld->isVolatile(), Ld->isNonTemporal(),
21879                                Ld->isInvariant(), Ld->getAlignment());
21880     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21881                                Ld->getPointerInfo().getWithOffset(4),
21882                                Ld->isVolatile(), Ld->isNonTemporal(),
21883                                Ld->isInvariant(),
21884                                MinAlign(Ld->getAlignment(), 4));
21885
21886     SDValue NewChain = LoLd.getValue(1);
21887     if (TokenFactorIndex != -1) {
21888       Ops.push_back(LoLd);
21889       Ops.push_back(HiLd);
21890       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21891     }
21892
21893     LoAddr = St->getBasePtr();
21894     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21895                          DAG.getConstant(4, MVT::i32));
21896
21897     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21898                                 St->getPointerInfo(),
21899                                 St->isVolatile(), St->isNonTemporal(),
21900                                 St->getAlignment());
21901     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21902                                 St->getPointerInfo().getWithOffset(4),
21903                                 St->isVolatile(),
21904                                 St->isNonTemporal(),
21905                                 MinAlign(St->getAlignment(), 4));
21906     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21907   }
21908   return SDValue();
21909 }
21910
21911 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21912 /// and return the operands for the horizontal operation in LHS and RHS.  A
21913 /// horizontal operation performs the binary operation on successive elements
21914 /// of its first operand, then on successive elements of its second operand,
21915 /// returning the resulting values in a vector.  For example, if
21916 ///   A = < float a0, float a1, float a2, float a3 >
21917 /// and
21918 ///   B = < float b0, float b1, float b2, float b3 >
21919 /// then the result of doing a horizontal operation on A and B is
21920 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21921 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21922 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21923 /// set to A, RHS to B, and the routine returns 'true'.
21924 /// Note that the binary operation should have the property that if one of the
21925 /// operands is UNDEF then the result is UNDEF.
21926 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21927   // Look for the following pattern: if
21928   //   A = < float a0, float a1, float a2, float a3 >
21929   //   B = < float b0, float b1, float b2, float b3 >
21930   // and
21931   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21932   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21933   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21934   // which is A horizontal-op B.
21935
21936   // At least one of the operands should be a vector shuffle.
21937   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21938       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21939     return false;
21940
21941   MVT VT = LHS.getSimpleValueType();
21942
21943   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21944          "Unsupported vector type for horizontal add/sub");
21945
21946   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21947   // operate independently on 128-bit lanes.
21948   unsigned NumElts = VT.getVectorNumElements();
21949   unsigned NumLanes = VT.getSizeInBits()/128;
21950   unsigned NumLaneElts = NumElts / NumLanes;
21951   assert((NumLaneElts % 2 == 0) &&
21952          "Vector type should have an even number of elements in each lane");
21953   unsigned HalfLaneElts = NumLaneElts/2;
21954
21955   // View LHS in the form
21956   //   LHS = VECTOR_SHUFFLE A, B, LMask
21957   // If LHS is not a shuffle then pretend it is the shuffle
21958   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21959   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21960   // type VT.
21961   SDValue A, B;
21962   SmallVector<int, 16> LMask(NumElts);
21963   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21964     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21965       A = LHS.getOperand(0);
21966     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21967       B = LHS.getOperand(1);
21968     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21969     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21970   } else {
21971     if (LHS.getOpcode() != ISD::UNDEF)
21972       A = LHS;
21973     for (unsigned i = 0; i != NumElts; ++i)
21974       LMask[i] = i;
21975   }
21976
21977   // Likewise, view RHS in the form
21978   //   RHS = VECTOR_SHUFFLE C, D, RMask
21979   SDValue C, D;
21980   SmallVector<int, 16> RMask(NumElts);
21981   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21982     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21983       C = RHS.getOperand(0);
21984     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21985       D = RHS.getOperand(1);
21986     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21987     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21988   } else {
21989     if (RHS.getOpcode() != ISD::UNDEF)
21990       C = RHS;
21991     for (unsigned i = 0; i != NumElts; ++i)
21992       RMask[i] = i;
21993   }
21994
21995   // Check that the shuffles are both shuffling the same vectors.
21996   if (!(A == C && B == D) && !(A == D && B == C))
21997     return false;
21998
21999   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22000   if (!A.getNode() && !B.getNode())
22001     return false;
22002
22003   // If A and B occur in reverse order in RHS, then "swap" them (which means
22004   // rewriting the mask).
22005   if (A != C)
22006     CommuteVectorShuffleMask(RMask, NumElts);
22007
22008   // At this point LHS and RHS are equivalent to
22009   //   LHS = VECTOR_SHUFFLE A, B, LMask
22010   //   RHS = VECTOR_SHUFFLE A, B, RMask
22011   // Check that the masks correspond to performing a horizontal operation.
22012   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22013     for (unsigned i = 0; i != NumLaneElts; ++i) {
22014       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22015
22016       // Ignore any UNDEF components.
22017       if (LIdx < 0 || RIdx < 0 ||
22018           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22019           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22020         continue;
22021
22022       // Check that successive elements are being operated on.  If not, this is
22023       // not a horizontal operation.
22024       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22025       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22026       if (!(LIdx == Index && RIdx == Index + 1) &&
22027           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22028         return false;
22029     }
22030   }
22031
22032   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22033   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22034   return true;
22035 }
22036
22037 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22038 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22039                                   const X86Subtarget *Subtarget) {
22040   EVT VT = N->getValueType(0);
22041   SDValue LHS = N->getOperand(0);
22042   SDValue RHS = N->getOperand(1);
22043
22044   // Try to synthesize horizontal adds from adds of shuffles.
22045   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22046        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22047       isHorizontalBinOp(LHS, RHS, true))
22048     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22049   return SDValue();
22050 }
22051
22052 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22053 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22054                                   const X86Subtarget *Subtarget) {
22055   EVT VT = N->getValueType(0);
22056   SDValue LHS = N->getOperand(0);
22057   SDValue RHS = N->getOperand(1);
22058
22059   // Try to synthesize horizontal subs from subs of shuffles.
22060   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22061        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22062       isHorizontalBinOp(LHS, RHS, false))
22063     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22064   return SDValue();
22065 }
22066
22067 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22068 /// X86ISD::FXOR nodes.
22069 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22070   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22071   // F[X]OR(0.0, x) -> x
22072   // F[X]OR(x, 0.0) -> x
22073   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22074     if (C->getValueAPF().isPosZero())
22075       return N->getOperand(1);
22076   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22077     if (C->getValueAPF().isPosZero())
22078       return N->getOperand(0);
22079   return SDValue();
22080 }
22081
22082 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22083 /// X86ISD::FMAX nodes.
22084 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22085   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22086
22087   // Only perform optimizations if UnsafeMath is used.
22088   if (!DAG.getTarget().Options.UnsafeFPMath)
22089     return SDValue();
22090
22091   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22092   // into FMINC and FMAXC, which are Commutative operations.
22093   unsigned NewOp = 0;
22094   switch (N->getOpcode()) {
22095     default: llvm_unreachable("unknown opcode");
22096     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22097     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22098   }
22099
22100   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22101                      N->getOperand(0), N->getOperand(1));
22102 }
22103
22104 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22105 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22106   // FAND(0.0, x) -> 0.0
22107   // FAND(x, 0.0) -> 0.0
22108   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22109     if (C->getValueAPF().isPosZero())
22110       return N->getOperand(0);
22111   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22112     if (C->getValueAPF().isPosZero())
22113       return N->getOperand(1);
22114   return SDValue();
22115 }
22116
22117 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22118 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22119   // FANDN(x, 0.0) -> 0.0
22120   // FANDN(0.0, x) -> x
22121   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22122     if (C->getValueAPF().isPosZero())
22123       return N->getOperand(1);
22124   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22125     if (C->getValueAPF().isPosZero())
22126       return N->getOperand(1);
22127   return SDValue();
22128 }
22129
22130 static SDValue PerformBTCombine(SDNode *N,
22131                                 SelectionDAG &DAG,
22132                                 TargetLowering::DAGCombinerInfo &DCI) {
22133   // BT ignores high bits in the bit index operand.
22134   SDValue Op1 = N->getOperand(1);
22135   if (Op1.hasOneUse()) {
22136     unsigned BitWidth = Op1.getValueSizeInBits();
22137     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22138     APInt KnownZero, KnownOne;
22139     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22140                                           !DCI.isBeforeLegalizeOps());
22141     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22142     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22143         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22144       DCI.CommitTargetLoweringOpt(TLO);
22145   }
22146   return SDValue();
22147 }
22148
22149 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22150   SDValue Op = N->getOperand(0);
22151   if (Op.getOpcode() == ISD::BITCAST)
22152     Op = Op.getOperand(0);
22153   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22154   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22155       VT.getVectorElementType().getSizeInBits() ==
22156       OpVT.getVectorElementType().getSizeInBits()) {
22157     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22158   }
22159   return SDValue();
22160 }
22161
22162 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22163                                                const X86Subtarget *Subtarget) {
22164   EVT VT = N->getValueType(0);
22165   if (!VT.isVector())
22166     return SDValue();
22167
22168   SDValue N0 = N->getOperand(0);
22169   SDValue N1 = N->getOperand(1);
22170   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22171   SDLoc dl(N);
22172
22173   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22174   // both SSE and AVX2 since there is no sign-extended shift right
22175   // operation on a vector with 64-bit elements.
22176   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22177   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22178   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22179       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22180     SDValue N00 = N0.getOperand(0);
22181
22182     // EXTLOAD has a better solution on AVX2,
22183     // it may be replaced with X86ISD::VSEXT node.
22184     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22185       if (!ISD::isNormalLoad(N00.getNode()))
22186         return SDValue();
22187
22188     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22189         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22190                                   N00, N1);
22191       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22192     }
22193   }
22194   return SDValue();
22195 }
22196
22197 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22198                                   TargetLowering::DAGCombinerInfo &DCI,
22199                                   const X86Subtarget *Subtarget) {
22200   if (!DCI.isBeforeLegalizeOps())
22201     return SDValue();
22202
22203   if (!Subtarget->hasFp256())
22204     return SDValue();
22205
22206   EVT VT = N->getValueType(0);
22207   if (VT.isVector() && VT.getSizeInBits() == 256) {
22208     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22209     if (R.getNode())
22210       return R;
22211   }
22212
22213   return SDValue();
22214 }
22215
22216 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22217                                  const X86Subtarget* Subtarget) {
22218   SDLoc dl(N);
22219   EVT VT = N->getValueType(0);
22220
22221   // Let legalize expand this if it isn't a legal type yet.
22222   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22223     return SDValue();
22224
22225   EVT ScalarVT = VT.getScalarType();
22226   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22227       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22228     return SDValue();
22229
22230   SDValue A = N->getOperand(0);
22231   SDValue B = N->getOperand(1);
22232   SDValue C = N->getOperand(2);
22233
22234   bool NegA = (A.getOpcode() == ISD::FNEG);
22235   bool NegB = (B.getOpcode() == ISD::FNEG);
22236   bool NegC = (C.getOpcode() == ISD::FNEG);
22237
22238   // Negative multiplication when NegA xor NegB
22239   bool NegMul = (NegA != NegB);
22240   if (NegA)
22241     A = A.getOperand(0);
22242   if (NegB)
22243     B = B.getOperand(0);
22244   if (NegC)
22245     C = C.getOperand(0);
22246
22247   unsigned Opcode;
22248   if (!NegMul)
22249     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22250   else
22251     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22252
22253   return DAG.getNode(Opcode, dl, VT, A, B, C);
22254 }
22255
22256 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22257                                   TargetLowering::DAGCombinerInfo &DCI,
22258                                   const X86Subtarget *Subtarget) {
22259   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22260   //           (and (i32 x86isd::setcc_carry), 1)
22261   // This eliminates the zext. This transformation is necessary because
22262   // ISD::SETCC is always legalized to i8.
22263   SDLoc dl(N);
22264   SDValue N0 = N->getOperand(0);
22265   EVT VT = N->getValueType(0);
22266
22267   if (N0.getOpcode() == ISD::AND &&
22268       N0.hasOneUse() &&
22269       N0.getOperand(0).hasOneUse()) {
22270     SDValue N00 = N0.getOperand(0);
22271     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22272       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22273       if (!C || C->getZExtValue() != 1)
22274         return SDValue();
22275       return DAG.getNode(ISD::AND, dl, VT,
22276                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22277                                      N00.getOperand(0), N00.getOperand(1)),
22278                          DAG.getConstant(1, VT));
22279     }
22280   }
22281
22282   if (N0.getOpcode() == ISD::TRUNCATE &&
22283       N0.hasOneUse() &&
22284       N0.getOperand(0).hasOneUse()) {
22285     SDValue N00 = N0.getOperand(0);
22286     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22287       return DAG.getNode(ISD::AND, dl, VT,
22288                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22289                                      N00.getOperand(0), N00.getOperand(1)),
22290                          DAG.getConstant(1, VT));
22291     }
22292   }
22293   if (VT.is256BitVector()) {
22294     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22295     if (R.getNode())
22296       return R;
22297   }
22298
22299   return SDValue();
22300 }
22301
22302 // Optimize x == -y --> x+y == 0
22303 //          x != -y --> x+y != 0
22304 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22305                                       const X86Subtarget* Subtarget) {
22306   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22307   SDValue LHS = N->getOperand(0);
22308   SDValue RHS = N->getOperand(1);
22309   EVT VT = N->getValueType(0);
22310   SDLoc DL(N);
22311
22312   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22313     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22314       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22315         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22316                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22317         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22318                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22319       }
22320   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22321     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22322       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22323         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22324                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22325         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22326                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22327       }
22328
22329   if (VT.getScalarType() == MVT::i1) {
22330     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22331       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22332     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22333     if (!IsSEXT0 && !IsVZero0)
22334       return SDValue();
22335     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22336       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22337     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22338
22339     if (!IsSEXT1 && !IsVZero1)
22340       return SDValue();
22341
22342     if (IsSEXT0 && IsVZero1) {
22343       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22344       if (CC == ISD::SETEQ)
22345         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22346       return LHS.getOperand(0);
22347     }
22348     if (IsSEXT1 && IsVZero0) {
22349       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22350       if (CC == ISD::SETEQ)
22351         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22352       return RHS.getOperand(0);
22353     }
22354   }
22355
22356   return SDValue();
22357 }
22358
22359 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22360                                       const X86Subtarget *Subtarget) {
22361   SDLoc dl(N);
22362   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22363   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22364          "X86insertps is only defined for v4x32");
22365
22366   SDValue Ld = N->getOperand(1);
22367   if (MayFoldLoad(Ld)) {
22368     // Extract the countS bits from the immediate so we can get the proper
22369     // address when narrowing the vector load to a specific element.
22370     // When the second source op is a memory address, interps doesn't use
22371     // countS and just gets an f32 from that address.
22372     unsigned DestIndex =
22373         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22374     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22375   } else
22376     return SDValue();
22377
22378   // Create this as a scalar to vector to match the instruction pattern.
22379   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22380   // countS bits are ignored when loading from memory on insertps, which
22381   // means we don't need to explicitly set them to 0.
22382   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22383                      LoadScalarToVector, N->getOperand(2));
22384 }
22385
22386 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22387 // as "sbb reg,reg", since it can be extended without zext and produces
22388 // an all-ones bit which is more useful than 0/1 in some cases.
22389 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22390                                MVT VT) {
22391   if (VT == MVT::i8)
22392     return DAG.getNode(ISD::AND, DL, VT,
22393                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22394                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22395                        DAG.getConstant(1, VT));
22396   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22397   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22398                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22399                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22400 }
22401
22402 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22403 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22404                                    TargetLowering::DAGCombinerInfo &DCI,
22405                                    const X86Subtarget *Subtarget) {
22406   SDLoc DL(N);
22407   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22408   SDValue EFLAGS = N->getOperand(1);
22409
22410   if (CC == X86::COND_A) {
22411     // Try to convert COND_A into COND_B in an attempt to facilitate
22412     // materializing "setb reg".
22413     //
22414     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22415     // cannot take an immediate as its first operand.
22416     //
22417     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22418         EFLAGS.getValueType().isInteger() &&
22419         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22420       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22421                                    EFLAGS.getNode()->getVTList(),
22422                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22423       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22424       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22425     }
22426   }
22427
22428   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22429   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22430   // cases.
22431   if (CC == X86::COND_B)
22432     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22433
22434   SDValue Flags;
22435
22436   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22437   if (Flags.getNode()) {
22438     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22439     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22440   }
22441
22442   return SDValue();
22443 }
22444
22445 // Optimize branch condition evaluation.
22446 //
22447 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22448                                     TargetLowering::DAGCombinerInfo &DCI,
22449                                     const X86Subtarget *Subtarget) {
22450   SDLoc DL(N);
22451   SDValue Chain = N->getOperand(0);
22452   SDValue Dest = N->getOperand(1);
22453   SDValue EFLAGS = N->getOperand(3);
22454   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22455
22456   SDValue Flags;
22457
22458   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22459   if (Flags.getNode()) {
22460     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22461     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22462                        Flags);
22463   }
22464
22465   return SDValue();
22466 }
22467
22468 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22469                                                          SelectionDAG &DAG) {
22470   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22471   // optimize away operation when it's from a constant.
22472   //
22473   // The general transformation is:
22474   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22475   //       AND(VECTOR_CMP(x,y), constant2)
22476   //    constant2 = UNARYOP(constant)
22477
22478   // Early exit if this isn't a vector operation, the operand of the
22479   // unary operation isn't a bitwise AND, or if the sizes of the operations
22480   // aren't the same.
22481   EVT VT = N->getValueType(0);
22482   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22483       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22484       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22485     return SDValue();
22486
22487   // Now check that the other operand of the AND is a constant. We could
22488   // make the transformation for non-constant splats as well, but it's unclear
22489   // that would be a benefit as it would not eliminate any operations, just
22490   // perform one more step in scalar code before moving to the vector unit.
22491   if (BuildVectorSDNode *BV =
22492           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22493     // Bail out if the vector isn't a constant.
22494     if (!BV->isConstant())
22495       return SDValue();
22496
22497     // Everything checks out. Build up the new and improved node.
22498     SDLoc DL(N);
22499     EVT IntVT = BV->getValueType(0);
22500     // Create a new constant of the appropriate type for the transformed
22501     // DAG.
22502     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22503     // The AND node needs bitcasts to/from an integer vector type around it.
22504     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22505     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22506                                  N->getOperand(0)->getOperand(0), MaskConst);
22507     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22508     return Res;
22509   }
22510
22511   return SDValue();
22512 }
22513
22514 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22515                                         const X86TargetLowering *XTLI) {
22516   // First try to optimize away the conversion entirely when it's
22517   // conditionally from a constant. Vectors only.
22518   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22519   if (Res != SDValue())
22520     return Res;
22521
22522   // Now move on to more general possibilities.
22523   SDValue Op0 = N->getOperand(0);
22524   EVT InVT = Op0->getValueType(0);
22525
22526   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22527   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22528     SDLoc dl(N);
22529     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22530     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22531     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22532   }
22533
22534   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22535   // a 32-bit target where SSE doesn't support i64->FP operations.
22536   if (Op0.getOpcode() == ISD::LOAD) {
22537     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22538     EVT VT = Ld->getValueType(0);
22539     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22540         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22541         !XTLI->getSubtarget()->is64Bit() &&
22542         VT == MVT::i64) {
22543       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22544                                           Ld->getChain(), Op0, DAG);
22545       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22546       return FILDChain;
22547     }
22548   }
22549   return SDValue();
22550 }
22551
22552 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22553 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22554                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22555   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22556   // the result is either zero or one (depending on the input carry bit).
22557   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22558   if (X86::isZeroNode(N->getOperand(0)) &&
22559       X86::isZeroNode(N->getOperand(1)) &&
22560       // We don't have a good way to replace an EFLAGS use, so only do this when
22561       // dead right now.
22562       SDValue(N, 1).use_empty()) {
22563     SDLoc DL(N);
22564     EVT VT = N->getValueType(0);
22565     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22566     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22567                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22568                                            DAG.getConstant(X86::COND_B,MVT::i8),
22569                                            N->getOperand(2)),
22570                                DAG.getConstant(1, VT));
22571     return DCI.CombineTo(N, Res1, CarryOut);
22572   }
22573
22574   return SDValue();
22575 }
22576
22577 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22578 //      (add Y, (setne X, 0)) -> sbb -1, Y
22579 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22580 //      (sub (setne X, 0), Y) -> adc -1, Y
22581 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22582   SDLoc DL(N);
22583
22584   // Look through ZExts.
22585   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22586   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22587     return SDValue();
22588
22589   SDValue SetCC = Ext.getOperand(0);
22590   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22591     return SDValue();
22592
22593   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22594   if (CC != X86::COND_E && CC != X86::COND_NE)
22595     return SDValue();
22596
22597   SDValue Cmp = SetCC.getOperand(1);
22598   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22599       !X86::isZeroNode(Cmp.getOperand(1)) ||
22600       !Cmp.getOperand(0).getValueType().isInteger())
22601     return SDValue();
22602
22603   SDValue CmpOp0 = Cmp.getOperand(0);
22604   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22605                                DAG.getConstant(1, CmpOp0.getValueType()));
22606
22607   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22608   if (CC == X86::COND_NE)
22609     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22610                        DL, OtherVal.getValueType(), OtherVal,
22611                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22612   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22613                      DL, OtherVal.getValueType(), OtherVal,
22614                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22615 }
22616
22617 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22618 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22619                                  const X86Subtarget *Subtarget) {
22620   EVT VT = N->getValueType(0);
22621   SDValue Op0 = N->getOperand(0);
22622   SDValue Op1 = N->getOperand(1);
22623
22624   // Try to synthesize horizontal adds from adds of shuffles.
22625   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22626        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22627       isHorizontalBinOp(Op0, Op1, true))
22628     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22629
22630   return OptimizeConditionalInDecrement(N, DAG);
22631 }
22632
22633 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22634                                  const X86Subtarget *Subtarget) {
22635   SDValue Op0 = N->getOperand(0);
22636   SDValue Op1 = N->getOperand(1);
22637
22638   // X86 can't encode an immediate LHS of a sub. See if we can push the
22639   // negation into a preceding instruction.
22640   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22641     // If the RHS of the sub is a XOR with one use and a constant, invert the
22642     // immediate. Then add one to the LHS of the sub so we can turn
22643     // X-Y -> X+~Y+1, saving one register.
22644     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22645         isa<ConstantSDNode>(Op1.getOperand(1))) {
22646       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22647       EVT VT = Op0.getValueType();
22648       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22649                                    Op1.getOperand(0),
22650                                    DAG.getConstant(~XorC, VT));
22651       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22652                          DAG.getConstant(C->getAPIntValue()+1, VT));
22653     }
22654   }
22655
22656   // Try to synthesize horizontal adds from adds of shuffles.
22657   EVT VT = N->getValueType(0);
22658   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22659        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22660       isHorizontalBinOp(Op0, Op1, true))
22661     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22662
22663   return OptimizeConditionalInDecrement(N, DAG);
22664 }
22665
22666 /// performVZEXTCombine - Performs build vector combines
22667 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22668                                         TargetLowering::DAGCombinerInfo &DCI,
22669                                         const X86Subtarget *Subtarget) {
22670   // (vzext (bitcast (vzext (x)) -> (vzext x)
22671   SDValue In = N->getOperand(0);
22672   while (In.getOpcode() == ISD::BITCAST)
22673     In = In.getOperand(0);
22674
22675   if (In.getOpcode() != X86ISD::VZEXT)
22676     return SDValue();
22677
22678   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22679                      In.getOperand(0));
22680 }
22681
22682 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22683                                              DAGCombinerInfo &DCI) const {
22684   SelectionDAG &DAG = DCI.DAG;
22685   switch (N->getOpcode()) {
22686   default: break;
22687   case ISD::EXTRACT_VECTOR_ELT:
22688     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22689   case ISD::VSELECT:
22690   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22691   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22692   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22693   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22694   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22695   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22696   case ISD::SHL:
22697   case ISD::SRA:
22698   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22699   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22700   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22701   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22702   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22703   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22704   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22705   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22706   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22707   case X86ISD::FXOR:
22708   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22709   case X86ISD::FMIN:
22710   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22711   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22712   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22713   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22714   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22715   case ISD::ANY_EXTEND:
22716   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22717   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22718   case ISD::SIGN_EXTEND_INREG:
22719     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22720   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22721   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22722   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22723   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22724   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22725   case X86ISD::SHUFP:       // Handle all target specific shuffles
22726   case X86ISD::PALIGNR:
22727   case X86ISD::UNPCKH:
22728   case X86ISD::UNPCKL:
22729   case X86ISD::MOVHLPS:
22730   case X86ISD::MOVLHPS:
22731   case X86ISD::PSHUFB:
22732   case X86ISD::PSHUFD:
22733   case X86ISD::PSHUFHW:
22734   case X86ISD::PSHUFLW:
22735   case X86ISD::MOVSS:
22736   case X86ISD::MOVSD:
22737   case X86ISD::VPERMILP:
22738   case X86ISD::VPERM2X128:
22739   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22740   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22741   case ISD::INTRINSIC_WO_CHAIN:
22742     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22743   case X86ISD::INSERTPS:
22744     return PerformINSERTPSCombine(N, DAG, Subtarget);
22745   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22746   }
22747
22748   return SDValue();
22749 }
22750
22751 /// isTypeDesirableForOp - Return true if the target has native support for
22752 /// the specified value type and it is 'desirable' to use the type for the
22753 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22754 /// instruction encodings are longer and some i16 instructions are slow.
22755 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22756   if (!isTypeLegal(VT))
22757     return false;
22758   if (VT != MVT::i16)
22759     return true;
22760
22761   switch (Opc) {
22762   default:
22763     return true;
22764   case ISD::LOAD:
22765   case ISD::SIGN_EXTEND:
22766   case ISD::ZERO_EXTEND:
22767   case ISD::ANY_EXTEND:
22768   case ISD::SHL:
22769   case ISD::SRL:
22770   case ISD::SUB:
22771   case ISD::ADD:
22772   case ISD::MUL:
22773   case ISD::AND:
22774   case ISD::OR:
22775   case ISD::XOR:
22776     return false;
22777   }
22778 }
22779
22780 /// IsDesirableToPromoteOp - This method query the target whether it is
22781 /// beneficial for dag combiner to promote the specified node. If true, it
22782 /// should return the desired promotion type by reference.
22783 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22784   EVT VT = Op.getValueType();
22785   if (VT != MVT::i16)
22786     return false;
22787
22788   bool Promote = false;
22789   bool Commute = false;
22790   switch (Op.getOpcode()) {
22791   default: break;
22792   case ISD::LOAD: {
22793     LoadSDNode *LD = cast<LoadSDNode>(Op);
22794     // If the non-extending load has a single use and it's not live out, then it
22795     // might be folded.
22796     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22797                                                      Op.hasOneUse()*/) {
22798       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22799              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22800         // The only case where we'd want to promote LOAD (rather then it being
22801         // promoted as an operand is when it's only use is liveout.
22802         if (UI->getOpcode() != ISD::CopyToReg)
22803           return false;
22804       }
22805     }
22806     Promote = true;
22807     break;
22808   }
22809   case ISD::SIGN_EXTEND:
22810   case ISD::ZERO_EXTEND:
22811   case ISD::ANY_EXTEND:
22812     Promote = true;
22813     break;
22814   case ISD::SHL:
22815   case ISD::SRL: {
22816     SDValue N0 = Op.getOperand(0);
22817     // Look out for (store (shl (load), x)).
22818     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22819       return false;
22820     Promote = true;
22821     break;
22822   }
22823   case ISD::ADD:
22824   case ISD::MUL:
22825   case ISD::AND:
22826   case ISD::OR:
22827   case ISD::XOR:
22828     Commute = true;
22829     // fallthrough
22830   case ISD::SUB: {
22831     SDValue N0 = Op.getOperand(0);
22832     SDValue N1 = Op.getOperand(1);
22833     if (!Commute && MayFoldLoad(N1))
22834       return false;
22835     // Avoid disabling potential load folding opportunities.
22836     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22837       return false;
22838     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22839       return false;
22840     Promote = true;
22841   }
22842   }
22843
22844   PVT = MVT::i32;
22845   return Promote;
22846 }
22847
22848 //===----------------------------------------------------------------------===//
22849 //                           X86 Inline Assembly Support
22850 //===----------------------------------------------------------------------===//
22851
22852 namespace {
22853   // Helper to match a string separated by whitespace.
22854   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22855     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22856
22857     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22858       StringRef piece(*args[i]);
22859       if (!s.startswith(piece)) // Check if the piece matches.
22860         return false;
22861
22862       s = s.substr(piece.size());
22863       StringRef::size_type pos = s.find_first_not_of(" \t");
22864       if (pos == 0) // We matched a prefix.
22865         return false;
22866
22867       s = s.substr(pos);
22868     }
22869
22870     return s.empty();
22871   }
22872   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22873 }
22874
22875 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22876
22877   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22878     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22879         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22880         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22881
22882       if (AsmPieces.size() == 3)
22883         return true;
22884       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22885         return true;
22886     }
22887   }
22888   return false;
22889 }
22890
22891 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22892   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22893
22894   std::string AsmStr = IA->getAsmString();
22895
22896   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22897   if (!Ty || Ty->getBitWidth() % 16 != 0)
22898     return false;
22899
22900   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22901   SmallVector<StringRef, 4> AsmPieces;
22902   SplitString(AsmStr, AsmPieces, ";\n");
22903
22904   switch (AsmPieces.size()) {
22905   default: return false;
22906   case 1:
22907     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22908     // we will turn this bswap into something that will be lowered to logical
22909     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22910     // lower so don't worry about this.
22911     // bswap $0
22912     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22913         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22914         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22915         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22916         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22917         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22918       // No need to check constraints, nothing other than the equivalent of
22919       // "=r,0" would be valid here.
22920       return IntrinsicLowering::LowerToByteSwap(CI);
22921     }
22922
22923     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22924     if (CI->getType()->isIntegerTy(16) &&
22925         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22926         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22927          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22928       AsmPieces.clear();
22929       const std::string &ConstraintsStr = IA->getConstraintString();
22930       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22931       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22932       if (clobbersFlagRegisters(AsmPieces))
22933         return IntrinsicLowering::LowerToByteSwap(CI);
22934     }
22935     break;
22936   case 3:
22937     if (CI->getType()->isIntegerTy(32) &&
22938         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22939         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22940         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22941         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22942       AsmPieces.clear();
22943       const std::string &ConstraintsStr = IA->getConstraintString();
22944       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22945       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22946       if (clobbersFlagRegisters(AsmPieces))
22947         return IntrinsicLowering::LowerToByteSwap(CI);
22948     }
22949
22950     if (CI->getType()->isIntegerTy(64)) {
22951       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22952       if (Constraints.size() >= 2 &&
22953           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22954           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22955         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22956         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22957             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22958             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22959           return IntrinsicLowering::LowerToByteSwap(CI);
22960       }
22961     }
22962     break;
22963   }
22964   return false;
22965 }
22966
22967 /// getConstraintType - Given a constraint letter, return the type of
22968 /// constraint it is for this target.
22969 X86TargetLowering::ConstraintType
22970 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22971   if (Constraint.size() == 1) {
22972     switch (Constraint[0]) {
22973     case 'R':
22974     case 'q':
22975     case 'Q':
22976     case 'f':
22977     case 't':
22978     case 'u':
22979     case 'y':
22980     case 'x':
22981     case 'Y':
22982     case 'l':
22983       return C_RegisterClass;
22984     case 'a':
22985     case 'b':
22986     case 'c':
22987     case 'd':
22988     case 'S':
22989     case 'D':
22990     case 'A':
22991       return C_Register;
22992     case 'I':
22993     case 'J':
22994     case 'K':
22995     case 'L':
22996     case 'M':
22997     case 'N':
22998     case 'G':
22999     case 'C':
23000     case 'e':
23001     case 'Z':
23002       return C_Other;
23003     default:
23004       break;
23005     }
23006   }
23007   return TargetLowering::getConstraintType(Constraint);
23008 }
23009
23010 /// Examine constraint type and operand type and determine a weight value.
23011 /// This object must already have been set up with the operand type
23012 /// and the current alternative constraint selected.
23013 TargetLowering::ConstraintWeight
23014   X86TargetLowering::getSingleConstraintMatchWeight(
23015     AsmOperandInfo &info, const char *constraint) const {
23016   ConstraintWeight weight = CW_Invalid;
23017   Value *CallOperandVal = info.CallOperandVal;
23018     // If we don't have a value, we can't do a match,
23019     // but allow it at the lowest weight.
23020   if (!CallOperandVal)
23021     return CW_Default;
23022   Type *type = CallOperandVal->getType();
23023   // Look at the constraint type.
23024   switch (*constraint) {
23025   default:
23026     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23027   case 'R':
23028   case 'q':
23029   case 'Q':
23030   case 'a':
23031   case 'b':
23032   case 'c':
23033   case 'd':
23034   case 'S':
23035   case 'D':
23036   case 'A':
23037     if (CallOperandVal->getType()->isIntegerTy())
23038       weight = CW_SpecificReg;
23039     break;
23040   case 'f':
23041   case 't':
23042   case 'u':
23043     if (type->isFloatingPointTy())
23044       weight = CW_SpecificReg;
23045     break;
23046   case 'y':
23047     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23048       weight = CW_SpecificReg;
23049     break;
23050   case 'x':
23051   case 'Y':
23052     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23053         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23054       weight = CW_Register;
23055     break;
23056   case 'I':
23057     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23058       if (C->getZExtValue() <= 31)
23059         weight = CW_Constant;
23060     }
23061     break;
23062   case 'J':
23063     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23064       if (C->getZExtValue() <= 63)
23065         weight = CW_Constant;
23066     }
23067     break;
23068   case 'K':
23069     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23070       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23071         weight = CW_Constant;
23072     }
23073     break;
23074   case 'L':
23075     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23076       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23077         weight = CW_Constant;
23078     }
23079     break;
23080   case 'M':
23081     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23082       if (C->getZExtValue() <= 3)
23083         weight = CW_Constant;
23084     }
23085     break;
23086   case 'N':
23087     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23088       if (C->getZExtValue() <= 0xff)
23089         weight = CW_Constant;
23090     }
23091     break;
23092   case 'G':
23093   case 'C':
23094     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23095       weight = CW_Constant;
23096     }
23097     break;
23098   case 'e':
23099     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23100       if ((C->getSExtValue() >= -0x80000000LL) &&
23101           (C->getSExtValue() <= 0x7fffffffLL))
23102         weight = CW_Constant;
23103     }
23104     break;
23105   case 'Z':
23106     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23107       if (C->getZExtValue() <= 0xffffffff)
23108         weight = CW_Constant;
23109     }
23110     break;
23111   }
23112   return weight;
23113 }
23114
23115 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23116 /// with another that has more specific requirements based on the type of the
23117 /// corresponding operand.
23118 const char *X86TargetLowering::
23119 LowerXConstraint(EVT ConstraintVT) const {
23120   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23121   // 'f' like normal targets.
23122   if (ConstraintVT.isFloatingPoint()) {
23123     if (Subtarget->hasSSE2())
23124       return "Y";
23125     if (Subtarget->hasSSE1())
23126       return "x";
23127   }
23128
23129   return TargetLowering::LowerXConstraint(ConstraintVT);
23130 }
23131
23132 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23133 /// vector.  If it is invalid, don't add anything to Ops.
23134 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23135                                                      std::string &Constraint,
23136                                                      std::vector<SDValue>&Ops,
23137                                                      SelectionDAG &DAG) const {
23138   SDValue Result;
23139
23140   // Only support length 1 constraints for now.
23141   if (Constraint.length() > 1) return;
23142
23143   char ConstraintLetter = Constraint[0];
23144   switch (ConstraintLetter) {
23145   default: break;
23146   case 'I':
23147     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23148       if (C->getZExtValue() <= 31) {
23149         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23150         break;
23151       }
23152     }
23153     return;
23154   case 'J':
23155     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23156       if (C->getZExtValue() <= 63) {
23157         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23158         break;
23159       }
23160     }
23161     return;
23162   case 'K':
23163     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23164       if (isInt<8>(C->getSExtValue())) {
23165         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23166         break;
23167       }
23168     }
23169     return;
23170   case 'N':
23171     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23172       if (C->getZExtValue() <= 255) {
23173         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23174         break;
23175       }
23176     }
23177     return;
23178   case 'e': {
23179     // 32-bit signed value
23180     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23181       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23182                                            C->getSExtValue())) {
23183         // Widen to 64 bits here to get it sign extended.
23184         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23185         break;
23186       }
23187     // FIXME gcc accepts some relocatable values here too, but only in certain
23188     // memory models; it's complicated.
23189     }
23190     return;
23191   }
23192   case 'Z': {
23193     // 32-bit unsigned value
23194     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23195       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23196                                            C->getZExtValue())) {
23197         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23198         break;
23199       }
23200     }
23201     // FIXME gcc accepts some relocatable values here too, but only in certain
23202     // memory models; it's complicated.
23203     return;
23204   }
23205   case 'i': {
23206     // Literal immediates are always ok.
23207     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23208       // Widen to 64 bits here to get it sign extended.
23209       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23210       break;
23211     }
23212
23213     // In any sort of PIC mode addresses need to be computed at runtime by
23214     // adding in a register or some sort of table lookup.  These can't
23215     // be used as immediates.
23216     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23217       return;
23218
23219     // If we are in non-pic codegen mode, we allow the address of a global (with
23220     // an optional displacement) to be used with 'i'.
23221     GlobalAddressSDNode *GA = nullptr;
23222     int64_t Offset = 0;
23223
23224     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23225     while (1) {
23226       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23227         Offset += GA->getOffset();
23228         break;
23229       } else if (Op.getOpcode() == ISD::ADD) {
23230         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23231           Offset += C->getZExtValue();
23232           Op = Op.getOperand(0);
23233           continue;
23234         }
23235       } else if (Op.getOpcode() == ISD::SUB) {
23236         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23237           Offset += -C->getZExtValue();
23238           Op = Op.getOperand(0);
23239           continue;
23240         }
23241       }
23242
23243       // Otherwise, this isn't something we can handle, reject it.
23244       return;
23245     }
23246
23247     const GlobalValue *GV = GA->getGlobal();
23248     // If we require an extra load to get this address, as in PIC mode, we
23249     // can't accept it.
23250     if (isGlobalStubReference(
23251             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23252       return;
23253
23254     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23255                                         GA->getValueType(0), Offset);
23256     break;
23257   }
23258   }
23259
23260   if (Result.getNode()) {
23261     Ops.push_back(Result);
23262     return;
23263   }
23264   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23265 }
23266
23267 std::pair<unsigned, const TargetRegisterClass*>
23268 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23269                                                 MVT VT) const {
23270   // First, see if this is a constraint that directly corresponds to an LLVM
23271   // register class.
23272   if (Constraint.size() == 1) {
23273     // GCC Constraint Letters
23274     switch (Constraint[0]) {
23275     default: break;
23276       // TODO: Slight differences here in allocation order and leaving
23277       // RIP in the class. Do they matter any more here than they do
23278       // in the normal allocation?
23279     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23280       if (Subtarget->is64Bit()) {
23281         if (VT == MVT::i32 || VT == MVT::f32)
23282           return std::make_pair(0U, &X86::GR32RegClass);
23283         if (VT == MVT::i16)
23284           return std::make_pair(0U, &X86::GR16RegClass);
23285         if (VT == MVT::i8 || VT == MVT::i1)
23286           return std::make_pair(0U, &X86::GR8RegClass);
23287         if (VT == MVT::i64 || VT == MVT::f64)
23288           return std::make_pair(0U, &X86::GR64RegClass);
23289         break;
23290       }
23291       // 32-bit fallthrough
23292     case 'Q':   // Q_REGS
23293       if (VT == MVT::i32 || VT == MVT::f32)
23294         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23295       if (VT == MVT::i16)
23296         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23297       if (VT == MVT::i8 || VT == MVT::i1)
23298         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23299       if (VT == MVT::i64)
23300         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23301       break;
23302     case 'r':   // GENERAL_REGS
23303     case 'l':   // INDEX_REGS
23304       if (VT == MVT::i8 || VT == MVT::i1)
23305         return std::make_pair(0U, &X86::GR8RegClass);
23306       if (VT == MVT::i16)
23307         return std::make_pair(0U, &X86::GR16RegClass);
23308       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23309         return std::make_pair(0U, &X86::GR32RegClass);
23310       return std::make_pair(0U, &X86::GR64RegClass);
23311     case 'R':   // LEGACY_REGS
23312       if (VT == MVT::i8 || VT == MVT::i1)
23313         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23314       if (VT == MVT::i16)
23315         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23316       if (VT == MVT::i32 || !Subtarget->is64Bit())
23317         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23318       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23319     case 'f':  // FP Stack registers.
23320       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23321       // value to the correct fpstack register class.
23322       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23323         return std::make_pair(0U, &X86::RFP32RegClass);
23324       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23325         return std::make_pair(0U, &X86::RFP64RegClass);
23326       return std::make_pair(0U, &X86::RFP80RegClass);
23327     case 'y':   // MMX_REGS if MMX allowed.
23328       if (!Subtarget->hasMMX()) break;
23329       return std::make_pair(0U, &X86::VR64RegClass);
23330     case 'Y':   // SSE_REGS if SSE2 allowed
23331       if (!Subtarget->hasSSE2()) break;
23332       // FALL THROUGH.
23333     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23334       if (!Subtarget->hasSSE1()) break;
23335
23336       switch (VT.SimpleTy) {
23337       default: break;
23338       // Scalar SSE types.
23339       case MVT::f32:
23340       case MVT::i32:
23341         return std::make_pair(0U, &X86::FR32RegClass);
23342       case MVT::f64:
23343       case MVT::i64:
23344         return std::make_pair(0U, &X86::FR64RegClass);
23345       // Vector types.
23346       case MVT::v16i8:
23347       case MVT::v8i16:
23348       case MVT::v4i32:
23349       case MVT::v2i64:
23350       case MVT::v4f32:
23351       case MVT::v2f64:
23352         return std::make_pair(0U, &X86::VR128RegClass);
23353       // AVX types.
23354       case MVT::v32i8:
23355       case MVT::v16i16:
23356       case MVT::v8i32:
23357       case MVT::v4i64:
23358       case MVT::v8f32:
23359       case MVT::v4f64:
23360         return std::make_pair(0U, &X86::VR256RegClass);
23361       case MVT::v8f64:
23362       case MVT::v16f32:
23363       case MVT::v16i32:
23364       case MVT::v8i64:
23365         return std::make_pair(0U, &X86::VR512RegClass);
23366       }
23367       break;
23368     }
23369   }
23370
23371   // Use the default implementation in TargetLowering to convert the register
23372   // constraint into a member of a register class.
23373   std::pair<unsigned, const TargetRegisterClass*> Res;
23374   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23375
23376   // Not found as a standard register?
23377   if (!Res.second) {
23378     // Map st(0) -> st(7) -> ST0
23379     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23380         tolower(Constraint[1]) == 's' &&
23381         tolower(Constraint[2]) == 't' &&
23382         Constraint[3] == '(' &&
23383         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23384         Constraint[5] == ')' &&
23385         Constraint[6] == '}') {
23386
23387       Res.first = X86::FP0+Constraint[4]-'0';
23388       Res.second = &X86::RFP80RegClass;
23389       return Res;
23390     }
23391
23392     // GCC allows "st(0)" to be called just plain "st".
23393     if (StringRef("{st}").equals_lower(Constraint)) {
23394       Res.first = X86::FP0;
23395       Res.second = &X86::RFP80RegClass;
23396       return Res;
23397     }
23398
23399     // flags -> EFLAGS
23400     if (StringRef("{flags}").equals_lower(Constraint)) {
23401       Res.first = X86::EFLAGS;
23402       Res.second = &X86::CCRRegClass;
23403       return Res;
23404     }
23405
23406     // 'A' means EAX + EDX.
23407     if (Constraint == "A") {
23408       Res.first = X86::EAX;
23409       Res.second = &X86::GR32_ADRegClass;
23410       return Res;
23411     }
23412     return Res;
23413   }
23414
23415   // Otherwise, check to see if this is a register class of the wrong value
23416   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23417   // turn into {ax},{dx}.
23418   if (Res.second->hasType(VT))
23419     return Res;   // Correct type already, nothing to do.
23420
23421   // All of the single-register GCC register classes map their values onto
23422   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23423   // really want an 8-bit or 32-bit register, map to the appropriate register
23424   // class and return the appropriate register.
23425   if (Res.second == &X86::GR16RegClass) {
23426     if (VT == MVT::i8 || VT == MVT::i1) {
23427       unsigned DestReg = 0;
23428       switch (Res.first) {
23429       default: break;
23430       case X86::AX: DestReg = X86::AL; break;
23431       case X86::DX: DestReg = X86::DL; break;
23432       case X86::CX: DestReg = X86::CL; break;
23433       case X86::BX: DestReg = X86::BL; break;
23434       }
23435       if (DestReg) {
23436         Res.first = DestReg;
23437         Res.second = &X86::GR8RegClass;
23438       }
23439     } else if (VT == MVT::i32 || VT == MVT::f32) {
23440       unsigned DestReg = 0;
23441       switch (Res.first) {
23442       default: break;
23443       case X86::AX: DestReg = X86::EAX; break;
23444       case X86::DX: DestReg = X86::EDX; break;
23445       case X86::CX: DestReg = X86::ECX; break;
23446       case X86::BX: DestReg = X86::EBX; break;
23447       case X86::SI: DestReg = X86::ESI; break;
23448       case X86::DI: DestReg = X86::EDI; break;
23449       case X86::BP: DestReg = X86::EBP; break;
23450       case X86::SP: DestReg = X86::ESP; break;
23451       }
23452       if (DestReg) {
23453         Res.first = DestReg;
23454         Res.second = &X86::GR32RegClass;
23455       }
23456     } else if (VT == MVT::i64 || VT == MVT::f64) {
23457       unsigned DestReg = 0;
23458       switch (Res.first) {
23459       default: break;
23460       case X86::AX: DestReg = X86::RAX; break;
23461       case X86::DX: DestReg = X86::RDX; break;
23462       case X86::CX: DestReg = X86::RCX; break;
23463       case X86::BX: DestReg = X86::RBX; break;
23464       case X86::SI: DestReg = X86::RSI; break;
23465       case X86::DI: DestReg = X86::RDI; break;
23466       case X86::BP: DestReg = X86::RBP; break;
23467       case X86::SP: DestReg = X86::RSP; break;
23468       }
23469       if (DestReg) {
23470         Res.first = DestReg;
23471         Res.second = &X86::GR64RegClass;
23472       }
23473     }
23474   } else if (Res.second == &X86::FR32RegClass ||
23475              Res.second == &X86::FR64RegClass ||
23476              Res.second == &X86::VR128RegClass ||
23477              Res.second == &X86::VR256RegClass ||
23478              Res.second == &X86::FR32XRegClass ||
23479              Res.second == &X86::FR64XRegClass ||
23480              Res.second == &X86::VR128XRegClass ||
23481              Res.second == &X86::VR256XRegClass ||
23482              Res.second == &X86::VR512RegClass) {
23483     // Handle references to XMM physical registers that got mapped into the
23484     // wrong class.  This can happen with constraints like {xmm0} where the
23485     // target independent register mapper will just pick the first match it can
23486     // find, ignoring the required type.
23487
23488     if (VT == MVT::f32 || VT == MVT::i32)
23489       Res.second = &X86::FR32RegClass;
23490     else if (VT == MVT::f64 || VT == MVT::i64)
23491       Res.second = &X86::FR64RegClass;
23492     else if (X86::VR128RegClass.hasType(VT))
23493       Res.second = &X86::VR128RegClass;
23494     else if (X86::VR256RegClass.hasType(VT))
23495       Res.second = &X86::VR256RegClass;
23496     else if (X86::VR512RegClass.hasType(VT))
23497       Res.second = &X86::VR512RegClass;
23498   }
23499
23500   return Res;
23501 }
23502
23503 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23504                                             Type *Ty) const {
23505   // Scaling factors are not free at all.
23506   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23507   // will take 2 allocations in the out of order engine instead of 1
23508   // for plain addressing mode, i.e. inst (reg1).
23509   // E.g.,
23510   // vaddps (%rsi,%drx), %ymm0, %ymm1
23511   // Requires two allocations (one for the load, one for the computation)
23512   // whereas:
23513   // vaddps (%rsi), %ymm0, %ymm1
23514   // Requires just 1 allocation, i.e., freeing allocations for other operations
23515   // and having less micro operations to execute.
23516   //
23517   // For some X86 architectures, this is even worse because for instance for
23518   // stores, the complex addressing mode forces the instruction to use the
23519   // "load" ports instead of the dedicated "store" port.
23520   // E.g., on Haswell:
23521   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23522   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23523   if (isLegalAddressingMode(AM, Ty))
23524     // Scale represents reg2 * scale, thus account for 1
23525     // as soon as we use a second register.
23526     return AM.Scale != 0;
23527   return -1;
23528 }
23529
23530 bool X86TargetLowering::isTargetFTOL() const {
23531   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23532 }