[x86] Remove the FIXME that was implemented in r214628. Managed to
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
524   }
525
526   // There's never any support for operations beyond MVT::f32.
527   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
531
532   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
536
537   if (Subtarget->hasPOPCNT()) {
538     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
539   } else {
540     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
541     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
543     if (Subtarget->is64Bit())
544       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
545   }
546
547   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
548
549   if (!Subtarget->hasMOVBE())
550     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
551
552   // These should be promoted to a larger select which is supported.
553   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
554   // X86 wants to expand cmov itself.
555   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
556   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
561   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
567   if (Subtarget->is64Bit()) {
568     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
569     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
570   }
571   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
572   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574   // support continuation, user-level threading, and etc.. As a result, no
575   // other SjLj exception interfaces are implemented and please don't build
576   // your own exception handling based on them.
577   // LLVM/Clang supports zero-cost DWARF exception handling.
578   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
580
581   // Darwin ABI issue.
582   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
583   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
584   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
586   if (Subtarget->is64Bit())
587     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
589   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
592     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
593     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
594     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
595     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
596   }
597   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
599   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
601   if (Subtarget->is64Bit()) {
602     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
603     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
605   }
606
607   if (Subtarget->hasSSE1())
608     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
609
610   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
611
612   // Expand certain atomics
613   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
614     MVT VT = IntVTs[i];
615     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
618   }
619
620   if (Subtarget->hasCmpxchg16b()) {
621     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
622   }
623
624   // FIXME - use subtarget debug flags
625   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
628   }
629
630   if (Subtarget->is64Bit()) {
631     setExceptionPointerRegister(X86::RAX);
632     setExceptionSelectorRegister(X86::RDX);
633   } else {
634     setExceptionPointerRegister(X86::EAX);
635     setExceptionSelectorRegister(X86::EDX);
636   }
637   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
639
640   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
642
643   setOperationAction(ISD::TRAP, MVT::Other, Legal);
644   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
645
646   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
648   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
649   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650     // TargetInfo::X86_64ABIBuiltinVaList
651     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
652     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
653   } else {
654     // TargetInfo::CharPtrBuiltinVaList
655     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
656     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
657   }
658
659   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
660   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
661
662   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
663                      MVT::i64 : MVT::i32, Custom);
664
665   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666     // f32 and f64 use SSE.
667     // Set up the FP register classes.
668     addRegisterClass(MVT::f32, &X86::FR32RegClass);
669     addRegisterClass(MVT::f64, &X86::FR64RegClass);
670
671     // Use ANDPD to simulate FABS.
672     setOperationAction(ISD::FABS , MVT::f64, Custom);
673     setOperationAction(ISD::FABS , MVT::f32, Custom);
674
675     // Use XORP to simulate FNEG.
676     setOperationAction(ISD::FNEG , MVT::f64, Custom);
677     setOperationAction(ISD::FNEG , MVT::f32, Custom);
678
679     // Use ANDPD and ORPD to simulate FCOPYSIGN.
680     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
682
683     // Lower this to FGETSIGNx86 plus an AND.
684     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
686
687     // We don't support sin/cos/fmod
688     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
689     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
690     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
692     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
693     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
694
695     // Expand FP immediates into loads from the stack, except for the special
696     // cases we handle.
697     addLegalFPImmediate(APFloat(+0.0)); // xorpd
698     addLegalFPImmediate(APFloat(+0.0f)); // xorps
699   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700     // Use SSE for f32, x87 for f64.
701     // Set up the FP register classes.
702     addRegisterClass(MVT::f32, &X86::FR32RegClass);
703     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
704
705     // Use ANDPS to simulate FABS.
706     setOperationAction(ISD::FABS , MVT::f32, Custom);
707
708     // Use XORP to simulate FNEG.
709     setOperationAction(ISD::FNEG , MVT::f32, Custom);
710
711     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
712
713     // Use ANDPS and ORPS to simulate FCOPYSIGN.
714     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
716
717     // We don't support sin/cos/fmod
718     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
719     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
720     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
721
722     // Special cases we handle for FP constants.
723     addLegalFPImmediate(APFloat(+0.0f)); // xorps
724     addLegalFPImmediate(APFloat(+0.0)); // FLD0
725     addLegalFPImmediate(APFloat(+1.0)); // FLD1
726     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
728
729     if (!TM.Options.UnsafeFPMath) {
730       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
732       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733     }
734   } else if (!TM.Options.UseSoftFloat) {
735     // f32 and f64 in x87.
736     // Set up the FP register classes.
737     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
739
740     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
741     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
744
745     if (!TM.Options.UnsafeFPMath) {
746       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
747       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
749       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
752     }
753     addLegalFPImmediate(APFloat(+0.0)); // FLD0
754     addLegalFPImmediate(APFloat(+1.0)); // FLD1
755     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
761   }
762
763   // We don't support FMA.
764   setOperationAction(ISD::FMA, MVT::f64, Expand);
765   setOperationAction(ISD::FMA, MVT::f32, Expand);
766
767   // Long double always uses X87.
768   if (!TM.Options.UseSoftFloat) {
769     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
771     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
772     {
773       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774       addLegalFPImmediate(TmpFlt);  // FLD0
775       TmpFlt.changeSign();
776       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
777
778       bool ignored;
779       APFloat TmpFlt2(+1.0);
780       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
781                       &ignored);
782       addLegalFPImmediate(TmpFlt2);  // FLD1
783       TmpFlt2.changeSign();
784       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
785     }
786
787     if (!TM.Options.UnsafeFPMath) {
788       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
789       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
790       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
791     }
792
793     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
795     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
797     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798     setOperationAction(ISD::FMA, MVT::f80, Expand);
799   }
800
801   // Always use a library call for pow.
802   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
804   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
805
806   setOperationAction(ISD::FLOG, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP, MVT::f80, Expand);
810   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
811
812   // First set operation action for all vector types to either promote
813   // (for widening) or expand (for scalarization). Then we will selectively
814   // turn on ones that can be effectively codegen'd.
815   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817     MVT VT = (MVT::SimpleValueType)i;
818     setOperationAction(ISD::ADD , VT, Expand);
819     setOperationAction(ISD::SUB , VT, Expand);
820     setOperationAction(ISD::FADD, VT, Expand);
821     setOperationAction(ISD::FNEG, VT, Expand);
822     setOperationAction(ISD::FSUB, VT, Expand);
823     setOperationAction(ISD::MUL , VT, Expand);
824     setOperationAction(ISD::FMUL, VT, Expand);
825     setOperationAction(ISD::SDIV, VT, Expand);
826     setOperationAction(ISD::UDIV, VT, Expand);
827     setOperationAction(ISD::FDIV, VT, Expand);
828     setOperationAction(ISD::SREM, VT, Expand);
829     setOperationAction(ISD::UREM, VT, Expand);
830     setOperationAction(ISD::LOAD, VT, Expand);
831     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836     setOperationAction(ISD::FABS, VT, Expand);
837     setOperationAction(ISD::FSIN, VT, Expand);
838     setOperationAction(ISD::FSINCOS, VT, Expand);
839     setOperationAction(ISD::FCOS, VT, Expand);
840     setOperationAction(ISD::FSINCOS, VT, Expand);
841     setOperationAction(ISD::FREM, VT, Expand);
842     setOperationAction(ISD::FMA,  VT, Expand);
843     setOperationAction(ISD::FPOWI, VT, Expand);
844     setOperationAction(ISD::FSQRT, VT, Expand);
845     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846     setOperationAction(ISD::FFLOOR, VT, Expand);
847     setOperationAction(ISD::FCEIL, VT, Expand);
848     setOperationAction(ISD::FTRUNC, VT, Expand);
849     setOperationAction(ISD::FRINT, VT, Expand);
850     setOperationAction(ISD::FNEARBYINT, VT, Expand);
851     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852     setOperationAction(ISD::MULHS, VT, Expand);
853     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854     setOperationAction(ISD::MULHU, VT, Expand);
855     setOperationAction(ISD::SDIVREM, VT, Expand);
856     setOperationAction(ISD::UDIVREM, VT, Expand);
857     setOperationAction(ISD::FPOW, VT, Expand);
858     setOperationAction(ISD::CTPOP, VT, Expand);
859     setOperationAction(ISD::CTTZ, VT, Expand);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861     setOperationAction(ISD::CTLZ, VT, Expand);
862     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863     setOperationAction(ISD::SHL, VT, Expand);
864     setOperationAction(ISD::SRA, VT, Expand);
865     setOperationAction(ISD::SRL, VT, Expand);
866     setOperationAction(ISD::ROTL, VT, Expand);
867     setOperationAction(ISD::ROTR, VT, Expand);
868     setOperationAction(ISD::BSWAP, VT, Expand);
869     setOperationAction(ISD::SETCC, VT, Expand);
870     setOperationAction(ISD::FLOG, VT, Expand);
871     setOperationAction(ISD::FLOG2, VT, Expand);
872     setOperationAction(ISD::FLOG10, VT, Expand);
873     setOperationAction(ISD::FEXP, VT, Expand);
874     setOperationAction(ISD::FEXP2, VT, Expand);
875     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880     setOperationAction(ISD::TRUNCATE, VT, Expand);
881     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884     setOperationAction(ISD::VSELECT, VT, Expand);
885     setOperationAction(ISD::SELECT_CC, VT, Expand);
886     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888       setTruncStoreAction(VT,
889                           (MVT::SimpleValueType)InnerVT, Expand);
890     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
892
893     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894     // we have to deal with them whether we ask for Expansion or not. Setting
895     // Expand causes its own optimisation problems though, so leave them legal.
896     if (VT.getVectorElementType() == MVT::i1)
897       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
898   }
899
900   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901   // with -msoft-float, disable use of MMX as well.
902   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904     // No operations on x86mmx supported, everything uses intrinsics.
905   }
906
907   // MMX-sized vectors (other than x86mmx) are expected to be expanded
908   // into smaller operations.
909   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
910   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
912   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
913   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
914   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
915   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
916   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
917   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
918   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
919   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
920   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
921   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
922   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
923   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
924   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
928   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
929   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
930   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
931   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
933   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
937   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
938
939   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
941
942     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
946     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
947     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
948     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
949     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
950     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
951     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
952     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
954   }
955
956   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
958
959     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
960     // registers cannot be used even for integer operations.
961     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
965
966     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
967     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
968     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
969     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
970     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
971     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
972     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
974     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
975     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
976     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
977     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
978     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
979     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
980     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
981     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
985     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
986     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
987     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
988
989     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
992     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
993
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
995     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002       MVT VT = (MVT::SimpleValueType)i;
1003       // Do not attempt to custom lower non-power-of-2 vectors
1004       if (!isPowerOf2_32(VT.getVectorNumElements()))
1005         continue;
1006       // Do not attempt to custom lower non-128-bit vectors
1007       if (!VT.is128BitVector())
1008         continue;
1009       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1010       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012     }
1013
1014     // We support custom legalizing of sext and anyext loads for specific
1015     // memory vector types which we can load as a scalar (or sequence of
1016     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1017     // loads these must work with a single scalar load.
1018     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1019     if (Subtarget->is64Bit()) {
1020       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1021       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1022     }
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1028     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1029
1030     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1031     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1032     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1033     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1034     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1035     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1036
1037     if (Subtarget->is64Bit()) {
1038       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1039       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1040     }
1041
1042     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1043     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1044       MVT VT = (MVT::SimpleValueType)i;
1045
1046       // Do not attempt to promote non-128-bit vectors
1047       if (!VT.is128BitVector())
1048         continue;
1049
1050       setOperationAction(ISD::AND,    VT, Promote);
1051       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1052       setOperationAction(ISD::OR,     VT, Promote);
1053       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1054       setOperationAction(ISD::XOR,    VT, Promote);
1055       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1056       setOperationAction(ISD::LOAD,   VT, Promote);
1057       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1058       setOperationAction(ISD::SELECT, VT, Promote);
1059       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1060     }
1061
1062     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1063
1064     // Custom lower v2i64 and v2f64 selects.
1065     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1066     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1067     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1068     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1069
1070     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1071     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1072
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1074     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1075     // As there is no 64-bit GPR available, we need build a special custom
1076     // sequence to convert from v2i32 to v2f32.
1077     if (!Subtarget->is64Bit())
1078       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1079
1080     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1081     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1082
1083     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1084
1085     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1086     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1087     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1088   }
1089
1090   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1091     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1092     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1093     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1094     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1095     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1096     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1097     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1098     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1099     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1100     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1101
1102     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1103     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1104     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1105     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1106     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1107     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1108     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1109     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1110     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1111     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1112
1113     // FIXME: Do we need to handle scalar-to-vector here?
1114     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1115
1116     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1119     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1120     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1121     // There is no BLENDI for byte vectors. We don't need to custom lower
1122     // some vselects for now.
1123     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1124
1125     // SSE41 brings specific instructions for doing vector sign extend even in
1126     // cases where we don't have SRA.
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1128     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1129     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1130
1131     // i8 and i16 vectors are custom , because the source register and source
1132     // source memory operand types are not the same width.  f32 vectors are
1133     // custom since the immediate controlling the insert encodes additional
1134     // information.
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1138     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1139
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1143     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1144
1145     // FIXME: these should be Legal but thats only for the case where
1146     // the index is constant.  For now custom expand to deal with that.
1147     if (Subtarget->is64Bit()) {
1148       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1149       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1150     }
1151   }
1152
1153   if (Subtarget->hasSSE2()) {
1154     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1155     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1156
1157     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1158     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1159
1160     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1161     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1162
1163     // In the customized shift lowering, the legal cases in AVX2 will be
1164     // recognized.
1165     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1166     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1167
1168     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1169     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1170
1171     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1172   }
1173
1174   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1175     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1176     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1177     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1179     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1180     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1181
1182     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1183     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1184     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1185
1186     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1190     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1191     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1192     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1193     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1194     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1195     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1196     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1197     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1198
1199     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1203     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1204     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1205     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1206     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1207     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1208     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1209     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1210     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1211
1212     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1213     // even though v8i16 is a legal type.
1214     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1215     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1216     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1217
1218     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1219     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1220     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1221
1222     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1223     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1224
1225     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1226
1227     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1228     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1229
1230     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1231     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1232
1233     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1234     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1235
1236     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1238     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1239     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1240
1241     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1242     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1243     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1244
1245     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1247     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1248     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1249
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1251     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1252     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1254     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1255     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1257     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1258     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1260     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1261     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1262
1263     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1264       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1266       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1267       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1268       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1269       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1270     }
1271
1272     if (Subtarget->hasInt256()) {
1273       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1275       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1276       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1277
1278       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1280       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1281       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1282
1283       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1284       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1285       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1286       // Don't lower v32i8 because there is no 128-bit byte mul
1287
1288       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1289       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1290       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1291       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1292
1293       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1294       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1295     } else {
1296       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1298       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1299       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1300
1301       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1303       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1304       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1305
1306       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1307       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1308       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1309       // Don't lower v32i8 because there is no 128-bit byte mul
1310     }
1311
1312     // In the customized shift lowering, the legal cases in AVX2 will be
1313     // recognized.
1314     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1315     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1316
1317     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1318     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1319
1320     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1321
1322     // Custom lower several nodes for 256-bit types.
1323     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1324              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1325       MVT VT = (MVT::SimpleValueType)i;
1326
1327       // Extract subvector is special because the value type
1328       // (result) is 128-bit but the source is 256-bit wide.
1329       if (VT.is128BitVector())
1330         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1331
1332       // Do not attempt to custom lower other non-256-bit vectors
1333       if (!VT.is256BitVector())
1334         continue;
1335
1336       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1337       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1338       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1339       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1340       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1341       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1342       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1343     }
1344
1345     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1346     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1347       MVT VT = (MVT::SimpleValueType)i;
1348
1349       // Do not attempt to promote non-256-bit vectors
1350       if (!VT.is256BitVector())
1351         continue;
1352
1353       setOperationAction(ISD::AND,    VT, Promote);
1354       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1355       setOperationAction(ISD::OR,     VT, Promote);
1356       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1357       setOperationAction(ISD::XOR,    VT, Promote);
1358       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1359       setOperationAction(ISD::LOAD,   VT, Promote);
1360       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1361       setOperationAction(ISD::SELECT, VT, Promote);
1362       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1363     }
1364   }
1365
1366   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1367     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1368     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1369     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1370     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1371
1372     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1373     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1374     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1375
1376     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1377     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1378     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1379     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1380     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1381     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1385     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1386     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1387
1388     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1391     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1392     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1393     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1394
1395     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1398     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1399     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1400     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1401     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1402     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1403
1404     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1405     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1406     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1407     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1408     if (Subtarget->is64Bit()) {
1409       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1410       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1411       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1412       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1413     }
1414     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1416     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1417     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1418     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1421     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1422     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1423     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1424
1425     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1438
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1445
1446     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1447     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1448
1449     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1450
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1454     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1456     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1460
1461     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1462     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1463
1464     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1465     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1466
1467     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1468
1469     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1470     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1471
1472     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1473     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1474
1475     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1476     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1477
1478     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1479     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1480     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1481     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1482     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1483     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1484
1485     if (Subtarget->hasCDI()) {
1486       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1487       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1488     }
1489
1490     // Custom lower several nodes.
1491     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1492              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1493       MVT VT = (MVT::SimpleValueType)i;
1494
1495       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1496       // Extract subvector is special because the value type
1497       // (result) is 256/128-bit but the source is 512-bit wide.
1498       if (VT.is128BitVector() || VT.is256BitVector())
1499         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1500
1501       if (VT.getVectorElementType() == MVT::i1)
1502         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1503
1504       // Do not attempt to custom lower other non-512-bit vectors
1505       if (!VT.is512BitVector())
1506         continue;
1507
1508       if ( EltSize >= 32) {
1509         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1510         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1511         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1512         setOperationAction(ISD::VSELECT,             VT, Legal);
1513         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1514         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1515         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1516       }
1517     }
1518     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1519       MVT VT = (MVT::SimpleValueType)i;
1520
1521       // Do not attempt to promote non-256-bit vectors
1522       if (!VT.is512BitVector())
1523         continue;
1524
1525       setOperationAction(ISD::SELECT, VT, Promote);
1526       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1527     }
1528   }// has  AVX-512
1529
1530   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1531     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1532     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1533   }
1534
1535   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1536   // of this type with custom code.
1537   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1538            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1539     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1540                        Custom);
1541   }
1542
1543   // We want to custom lower some of our intrinsics.
1544   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1545   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1546   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1547   if (!Subtarget->is64Bit())
1548     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1549
1550   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1551   // handle type legalization for these operations here.
1552   //
1553   // FIXME: We really should do custom legalization for addition and
1554   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1555   // than generic legalization for 64-bit multiplication-with-overflow, though.
1556   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1557     // Add/Sub/Mul with overflow operations are custom lowered.
1558     MVT VT = IntVTs[i];
1559     setOperationAction(ISD::SADDO, VT, Custom);
1560     setOperationAction(ISD::UADDO, VT, Custom);
1561     setOperationAction(ISD::SSUBO, VT, Custom);
1562     setOperationAction(ISD::USUBO, VT, Custom);
1563     setOperationAction(ISD::SMULO, VT, Custom);
1564     setOperationAction(ISD::UMULO, VT, Custom);
1565   }
1566
1567   // There are no 8-bit 3-address imul/mul instructions
1568   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1569   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1570
1571   if (!Subtarget->is64Bit()) {
1572     // These libcalls are not available in 32-bit.
1573     setLibcallName(RTLIB::SHL_I128, nullptr);
1574     setLibcallName(RTLIB::SRL_I128, nullptr);
1575     setLibcallName(RTLIB::SRA_I128, nullptr);
1576   }
1577
1578   // Combine sin / cos into one node or libcall if possible.
1579   if (Subtarget->hasSinCos()) {
1580     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1581     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1582     if (Subtarget->isTargetDarwin()) {
1583       // For MacOSX, we don't want to the normal expansion of a libcall to
1584       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1585       // traffic.
1586       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1587       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1588     }
1589   }
1590
1591   if (Subtarget->isTargetWin64()) {
1592     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1593     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1594     setOperationAction(ISD::SREM, MVT::i128, Custom);
1595     setOperationAction(ISD::UREM, MVT::i128, Custom);
1596     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1597     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1598   }
1599
1600   // We have target-specific dag combine patterns for the following nodes:
1601   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1602   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1603   setTargetDAGCombine(ISD::VSELECT);
1604   setTargetDAGCombine(ISD::SELECT);
1605   setTargetDAGCombine(ISD::SHL);
1606   setTargetDAGCombine(ISD::SRA);
1607   setTargetDAGCombine(ISD::SRL);
1608   setTargetDAGCombine(ISD::OR);
1609   setTargetDAGCombine(ISD::AND);
1610   setTargetDAGCombine(ISD::ADD);
1611   setTargetDAGCombine(ISD::FADD);
1612   setTargetDAGCombine(ISD::FSUB);
1613   setTargetDAGCombine(ISD::FMA);
1614   setTargetDAGCombine(ISD::SUB);
1615   setTargetDAGCombine(ISD::LOAD);
1616   setTargetDAGCombine(ISD::STORE);
1617   setTargetDAGCombine(ISD::ZERO_EXTEND);
1618   setTargetDAGCombine(ISD::ANY_EXTEND);
1619   setTargetDAGCombine(ISD::SIGN_EXTEND);
1620   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1621   setTargetDAGCombine(ISD::TRUNCATE);
1622   setTargetDAGCombine(ISD::SINT_TO_FP);
1623   setTargetDAGCombine(ISD::SETCC);
1624   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1625   setTargetDAGCombine(ISD::BUILD_VECTOR);
1626   if (Subtarget->is64Bit())
1627     setTargetDAGCombine(ISD::MUL);
1628   setTargetDAGCombine(ISD::XOR);
1629
1630   computeRegisterProperties();
1631
1632   // On Darwin, -Os means optimize for size without hurting performance,
1633   // do not reduce the limit.
1634   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1635   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1636   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1637   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1638   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1639   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1640   setPrefLoopAlignment(4); // 2^4 bytes.
1641
1642   // Predictable cmov don't hurt on atom because it's in-order.
1643   PredictableSelectIsExpensive = !Subtarget->isAtom();
1644
1645   setPrefFunctionAlignment(4); // 2^4 bytes.
1646 }
1647
1648 // This has so far only been implemented for 64-bit MachO.
1649 bool X86TargetLowering::useLoadStackGuardNode() const {
1650   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1651          Subtarget->is64Bit();
1652 }
1653
1654 TargetLoweringBase::LegalizeTypeAction
1655 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1656   if (ExperimentalVectorWideningLegalization &&
1657       VT.getVectorNumElements() != 1 &&
1658       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1659     return TypeWidenVector;
1660
1661   return TargetLoweringBase::getPreferredVectorAction(VT);
1662 }
1663
1664 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1665   if (!VT.isVector())
1666     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1667
1668   if (Subtarget->hasAVX512())
1669     switch(VT.getVectorNumElements()) {
1670     case  8: return MVT::v8i1;
1671     case 16: return MVT::v16i1;
1672   }
1673
1674   return VT.changeVectorElementTypeToInteger();
1675 }
1676
1677 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1678 /// the desired ByVal argument alignment.
1679 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1680   if (MaxAlign == 16)
1681     return;
1682   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1683     if (VTy->getBitWidth() == 128)
1684       MaxAlign = 16;
1685   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1686     unsigned EltAlign = 0;
1687     getMaxByValAlign(ATy->getElementType(), EltAlign);
1688     if (EltAlign > MaxAlign)
1689       MaxAlign = EltAlign;
1690   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1691     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1692       unsigned EltAlign = 0;
1693       getMaxByValAlign(STy->getElementType(i), EltAlign);
1694       if (EltAlign > MaxAlign)
1695         MaxAlign = EltAlign;
1696       if (MaxAlign == 16)
1697         break;
1698     }
1699   }
1700 }
1701
1702 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1703 /// function arguments in the caller parameter area. For X86, aggregates
1704 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1705 /// are at 4-byte boundaries.
1706 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1707   if (Subtarget->is64Bit()) {
1708     // Max of 8 and alignment of type.
1709     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1710     if (TyAlign > 8)
1711       return TyAlign;
1712     return 8;
1713   }
1714
1715   unsigned Align = 4;
1716   if (Subtarget->hasSSE1())
1717     getMaxByValAlign(Ty, Align);
1718   return Align;
1719 }
1720
1721 /// getOptimalMemOpType - Returns the target specific optimal type for load
1722 /// and store operations as a result of memset, memcpy, and memmove
1723 /// lowering. If DstAlign is zero that means it's safe to destination
1724 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1725 /// means there isn't a need to check it against alignment requirement,
1726 /// probably because the source does not need to be loaded. If 'IsMemset' is
1727 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1728 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1729 /// source is constant so it does not need to be loaded.
1730 /// It returns EVT::Other if the type should be determined using generic
1731 /// target-independent logic.
1732 EVT
1733 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1734                                        unsigned DstAlign, unsigned SrcAlign,
1735                                        bool IsMemset, bool ZeroMemset,
1736                                        bool MemcpyStrSrc,
1737                                        MachineFunction &MF) const {
1738   const Function *F = MF.getFunction();
1739   if ((!IsMemset || ZeroMemset) &&
1740       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1741                                        Attribute::NoImplicitFloat)) {
1742     if (Size >= 16 &&
1743         (Subtarget->isUnalignedMemAccessFast() ||
1744          ((DstAlign == 0 || DstAlign >= 16) &&
1745           (SrcAlign == 0 || SrcAlign >= 16)))) {
1746       if (Size >= 32) {
1747         if (Subtarget->hasInt256())
1748           return MVT::v8i32;
1749         if (Subtarget->hasFp256())
1750           return MVT::v8f32;
1751       }
1752       if (Subtarget->hasSSE2())
1753         return MVT::v4i32;
1754       if (Subtarget->hasSSE1())
1755         return MVT::v4f32;
1756     } else if (!MemcpyStrSrc && Size >= 8 &&
1757                !Subtarget->is64Bit() &&
1758                Subtarget->hasSSE2()) {
1759       // Do not use f64 to lower memcpy if source is string constant. It's
1760       // better to use i32 to avoid the loads.
1761       return MVT::f64;
1762     }
1763   }
1764   if (Subtarget->is64Bit() && Size >= 8)
1765     return MVT::i64;
1766   return MVT::i32;
1767 }
1768
1769 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1770   if (VT == MVT::f32)
1771     return X86ScalarSSEf32;
1772   else if (VT == MVT::f64)
1773     return X86ScalarSSEf64;
1774   return true;
1775 }
1776
1777 bool
1778 X86TargetLowering::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.getTarget().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 =
2725     static_cast<const X86RegisterInfo*>(DAG.getTarget().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.getTarget().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 =
3113     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3114   const TargetFrameLowering &TFI = *TM.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 =
3228     static_cast<const X86RegisterInfo*>(DAG.getTarget().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.getTarget().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::SHUFP:
3468   case X86ISD::VPERM2X128:
3469     return DAG.getNode(Opc, dl, VT, V1, V2,
3470                        DAG.getConstant(TargetMask, MVT::i8));
3471   }
3472 }
3473
3474 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3475                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3476   switch(Opc) {
3477   default: llvm_unreachable("Unknown x86 shuffle node");
3478   case X86ISD::MOVLHPS:
3479   case X86ISD::MOVLHPD:
3480   case X86ISD::MOVHLPS:
3481   case X86ISD::MOVLPS:
3482   case X86ISD::MOVLPD:
3483   case X86ISD::MOVSS:
3484   case X86ISD::MOVSD:
3485   case X86ISD::UNPCKL:
3486   case X86ISD::UNPCKH:
3487     return DAG.getNode(Opc, dl, VT, V1, V2);
3488   }
3489 }
3490
3491 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3492   MachineFunction &MF = DAG.getMachineFunction();
3493   const X86RegisterInfo *RegInfo =
3494     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3495   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3496   int ReturnAddrIndex = FuncInfo->getRAIndex();
3497
3498   if (ReturnAddrIndex == 0) {
3499     // Set up a frame object for the return address.
3500     unsigned SlotSize = RegInfo->getSlotSize();
3501     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3502                                                            -(int64_t)SlotSize,
3503                                                            false);
3504     FuncInfo->setRAIndex(ReturnAddrIndex);
3505   }
3506
3507   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3508 }
3509
3510 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3511                                        bool hasSymbolicDisplacement) {
3512   // Offset should fit into 32 bit immediate field.
3513   if (!isInt<32>(Offset))
3514     return false;
3515
3516   // If we don't have a symbolic displacement - we don't have any extra
3517   // restrictions.
3518   if (!hasSymbolicDisplacement)
3519     return true;
3520
3521   // FIXME: Some tweaks might be needed for medium code model.
3522   if (M != CodeModel::Small && M != CodeModel::Kernel)
3523     return false;
3524
3525   // For small code model we assume that latest object is 16MB before end of 31
3526   // bits boundary. We may also accept pretty large negative constants knowing
3527   // that all objects are in the positive half of address space.
3528   if (M == CodeModel::Small && Offset < 16*1024*1024)
3529     return true;
3530
3531   // For kernel code model we know that all object resist in the negative half
3532   // of 32bits address space. We may not accept negative offsets, since they may
3533   // be just off and we may accept pretty large positive ones.
3534   if (M == CodeModel::Kernel && Offset > 0)
3535     return true;
3536
3537   return false;
3538 }
3539
3540 /// isCalleePop - Determines whether the callee is required to pop its
3541 /// own arguments. Callee pop is necessary to support tail calls.
3542 bool X86::isCalleePop(CallingConv::ID CallingConv,
3543                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3544   if (IsVarArg)
3545     return false;
3546
3547   switch (CallingConv) {
3548   default:
3549     return false;
3550   case CallingConv::X86_StdCall:
3551     return !is64Bit;
3552   case CallingConv::X86_FastCall:
3553     return !is64Bit;
3554   case CallingConv::X86_ThisCall:
3555     return !is64Bit;
3556   case CallingConv::Fast:
3557     return TailCallOpt;
3558   case CallingConv::GHC:
3559     return TailCallOpt;
3560   case CallingConv::HiPE:
3561     return TailCallOpt;
3562   }
3563 }
3564
3565 /// \brief Return true if the condition is an unsigned comparison operation.
3566 static bool isX86CCUnsigned(unsigned X86CC) {
3567   switch (X86CC) {
3568   default: llvm_unreachable("Invalid integer condition!");
3569   case X86::COND_E:     return true;
3570   case X86::COND_G:     return false;
3571   case X86::COND_GE:    return false;
3572   case X86::COND_L:     return false;
3573   case X86::COND_LE:    return false;
3574   case X86::COND_NE:    return true;
3575   case X86::COND_B:     return true;
3576   case X86::COND_A:     return true;
3577   case X86::COND_BE:    return true;
3578   case X86::COND_AE:    return true;
3579   }
3580   llvm_unreachable("covered switch fell through?!");
3581 }
3582
3583 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3584 /// specific condition code, returning the condition code and the LHS/RHS of the
3585 /// comparison to make.
3586 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3587                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3588   if (!isFP) {
3589     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3590       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3591         // X > -1   -> X == 0, jump !sign.
3592         RHS = DAG.getConstant(0, RHS.getValueType());
3593         return X86::COND_NS;
3594       }
3595       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3596         // X < 0   -> X == 0, jump on sign.
3597         return X86::COND_S;
3598       }
3599       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3600         // X < 1   -> X <= 0
3601         RHS = DAG.getConstant(0, RHS.getValueType());
3602         return X86::COND_LE;
3603       }
3604     }
3605
3606     switch (SetCCOpcode) {
3607     default: llvm_unreachable("Invalid integer condition!");
3608     case ISD::SETEQ:  return X86::COND_E;
3609     case ISD::SETGT:  return X86::COND_G;
3610     case ISD::SETGE:  return X86::COND_GE;
3611     case ISD::SETLT:  return X86::COND_L;
3612     case ISD::SETLE:  return X86::COND_LE;
3613     case ISD::SETNE:  return X86::COND_NE;
3614     case ISD::SETULT: return X86::COND_B;
3615     case ISD::SETUGT: return X86::COND_A;
3616     case ISD::SETULE: return X86::COND_BE;
3617     case ISD::SETUGE: return X86::COND_AE;
3618     }
3619   }
3620
3621   // First determine if it is required or is profitable to flip the operands.
3622
3623   // If LHS is a foldable load, but RHS is not, flip the condition.
3624   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3625       !ISD::isNON_EXTLoad(RHS.getNode())) {
3626     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3627     std::swap(LHS, RHS);
3628   }
3629
3630   switch (SetCCOpcode) {
3631   default: break;
3632   case ISD::SETOLT:
3633   case ISD::SETOLE:
3634   case ISD::SETUGT:
3635   case ISD::SETUGE:
3636     std::swap(LHS, RHS);
3637     break;
3638   }
3639
3640   // On a floating point condition, the flags are set as follows:
3641   // ZF  PF  CF   op
3642   //  0 | 0 | 0 | X > Y
3643   //  0 | 0 | 1 | X < Y
3644   //  1 | 0 | 0 | X == Y
3645   //  1 | 1 | 1 | unordered
3646   switch (SetCCOpcode) {
3647   default: llvm_unreachable("Condcode should be pre-legalized away");
3648   case ISD::SETUEQ:
3649   case ISD::SETEQ:   return X86::COND_E;
3650   case ISD::SETOLT:              // flipped
3651   case ISD::SETOGT:
3652   case ISD::SETGT:   return X86::COND_A;
3653   case ISD::SETOLE:              // flipped
3654   case ISD::SETOGE:
3655   case ISD::SETGE:   return X86::COND_AE;
3656   case ISD::SETUGT:              // flipped
3657   case ISD::SETULT:
3658   case ISD::SETLT:   return X86::COND_B;
3659   case ISD::SETUGE:              // flipped
3660   case ISD::SETULE:
3661   case ISD::SETLE:   return X86::COND_BE;
3662   case ISD::SETONE:
3663   case ISD::SETNE:   return X86::COND_NE;
3664   case ISD::SETUO:   return X86::COND_P;
3665   case ISD::SETO:    return X86::COND_NP;
3666   case ISD::SETOEQ:
3667   case ISD::SETUNE:  return X86::COND_INVALID;
3668   }
3669 }
3670
3671 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3672 /// code. Current x86 isa includes the following FP cmov instructions:
3673 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3674 static bool hasFPCMov(unsigned X86CC) {
3675   switch (X86CC) {
3676   default:
3677     return false;
3678   case X86::COND_B:
3679   case X86::COND_BE:
3680   case X86::COND_E:
3681   case X86::COND_P:
3682   case X86::COND_A:
3683   case X86::COND_AE:
3684   case X86::COND_NE:
3685   case X86::COND_NP:
3686     return true;
3687   }
3688 }
3689
3690 /// isFPImmLegal - Returns true if the target can instruction select the
3691 /// specified FP immediate natively. If false, the legalizer will
3692 /// materialize the FP immediate as a load from a constant pool.
3693 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3694   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3695     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3696       return true;
3697   }
3698   return false;
3699 }
3700
3701 /// \brief Returns true if it is beneficial to convert a load of a constant
3702 /// to just the constant itself.
3703 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3704                                                           Type *Ty) const {
3705   assert(Ty->isIntegerTy());
3706
3707   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3708   if (BitSize == 0 || BitSize > 64)
3709     return false;
3710   return true;
3711 }
3712
3713 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3714 /// the specified range (L, H].
3715 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3716   return (Val < 0) || (Val >= Low && Val < Hi);
3717 }
3718
3719 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3720 /// specified value.
3721 static bool isUndefOrEqual(int Val, int CmpVal) {
3722   return (Val < 0 || Val == CmpVal);
3723 }
3724
3725 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3726 /// from position Pos and ending in Pos+Size, falls within the specified
3727 /// sequential range (L, L+Pos]. or is undef.
3728 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3729                                        unsigned Pos, unsigned Size, int Low) {
3730   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3731     if (!isUndefOrEqual(Mask[i], Low))
3732       return false;
3733   return true;
3734 }
3735
3736 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3737 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3738 /// the second operand.
3739 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3740   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3741     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3742   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3743     return (Mask[0] < 2 && Mask[1] < 2);
3744   return false;
3745 }
3746
3747 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3748 /// is suitable for input to PSHUFHW.
3749 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3750   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3751     return false;
3752
3753   // Lower quadword copied in order or undef.
3754   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3755     return false;
3756
3757   // Upper quadword shuffled.
3758   for (unsigned i = 4; i != 8; ++i)
3759     if (!isUndefOrInRange(Mask[i], 4, 8))
3760       return false;
3761
3762   if (VT == MVT::v16i16) {
3763     // Lower quadword copied in order or undef.
3764     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3765       return false;
3766
3767     // Upper quadword shuffled.
3768     for (unsigned i = 12; i != 16; ++i)
3769       if (!isUndefOrInRange(Mask[i], 12, 16))
3770         return false;
3771   }
3772
3773   return true;
3774 }
3775
3776 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3777 /// is suitable for input to PSHUFLW.
3778 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3779   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3780     return false;
3781
3782   // Upper quadword copied in order.
3783   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3784     return false;
3785
3786   // Lower quadword shuffled.
3787   for (unsigned i = 0; i != 4; ++i)
3788     if (!isUndefOrInRange(Mask[i], 0, 4))
3789       return false;
3790
3791   if (VT == MVT::v16i16) {
3792     // Upper quadword copied in order.
3793     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3794       return false;
3795
3796     // Lower quadword shuffled.
3797     for (unsigned i = 8; i != 12; ++i)
3798       if (!isUndefOrInRange(Mask[i], 8, 12))
3799         return false;
3800   }
3801
3802   return true;
3803 }
3804
3805 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3806 /// is suitable for input to PALIGNR.
3807 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3808                           const X86Subtarget *Subtarget) {
3809   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3810       (VT.is256BitVector() && !Subtarget->hasInt256()))
3811     return false;
3812
3813   unsigned NumElts = VT.getVectorNumElements();
3814   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3815   unsigned NumLaneElts = NumElts/NumLanes;
3816
3817   // Do not handle 64-bit element shuffles with palignr.
3818   if (NumLaneElts == 2)
3819     return false;
3820
3821   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3822     unsigned i;
3823     for (i = 0; i != NumLaneElts; ++i) {
3824       if (Mask[i+l] >= 0)
3825         break;
3826     }
3827
3828     // Lane is all undef, go to next lane
3829     if (i == NumLaneElts)
3830       continue;
3831
3832     int Start = Mask[i+l];
3833
3834     // Make sure its in this lane in one of the sources
3835     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3836         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3837       return false;
3838
3839     // If not lane 0, then we must match lane 0
3840     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3841       return false;
3842
3843     // Correct second source to be contiguous with first source
3844     if (Start >= (int)NumElts)
3845       Start -= NumElts - NumLaneElts;
3846
3847     // Make sure we're shifting in the right direction.
3848     if (Start <= (int)(i+l))
3849       return false;
3850
3851     Start -= i;
3852
3853     // Check the rest of the elements to see if they are consecutive.
3854     for (++i; i != NumLaneElts; ++i) {
3855       int Idx = Mask[i+l];
3856
3857       // Make sure its in this lane
3858       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3859           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3860         return false;
3861
3862       // If not lane 0, then we must match lane 0
3863       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3864         return false;
3865
3866       if (Idx >= (int)NumElts)
3867         Idx -= NumElts - NumLaneElts;
3868
3869       if (!isUndefOrEqual(Idx, Start+i))
3870         return false;
3871
3872     }
3873   }
3874
3875   return true;
3876 }
3877
3878 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3879 /// the two vector operands have swapped position.
3880 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3881                                      unsigned NumElems) {
3882   for (unsigned i = 0; i != NumElems; ++i) {
3883     int idx = Mask[i];
3884     if (idx < 0)
3885       continue;
3886     else if (idx < (int)NumElems)
3887       Mask[i] = idx + NumElems;
3888     else
3889       Mask[i] = idx - NumElems;
3890   }
3891 }
3892
3893 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3894 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3895 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3896 /// reverse of what x86 shuffles want.
3897 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3898
3899   unsigned NumElems = VT.getVectorNumElements();
3900   unsigned NumLanes = VT.getSizeInBits()/128;
3901   unsigned NumLaneElems = NumElems/NumLanes;
3902
3903   if (NumLaneElems != 2 && NumLaneElems != 4)
3904     return false;
3905
3906   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3907   bool symetricMaskRequired =
3908     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3909
3910   // VSHUFPSY divides the resulting vector into 4 chunks.
3911   // The sources are also splitted into 4 chunks, and each destination
3912   // chunk must come from a different source chunk.
3913   //
3914   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3915   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3916   //
3917   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3918   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3919   //
3920   // VSHUFPDY divides the resulting vector into 4 chunks.
3921   // The sources are also splitted into 4 chunks, and each destination
3922   // chunk must come from a different source chunk.
3923   //
3924   //  SRC1 =>      X3       X2       X1       X0
3925   //  SRC2 =>      Y3       Y2       Y1       Y0
3926   //
3927   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3928   //
3929   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3930   unsigned HalfLaneElems = NumLaneElems/2;
3931   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3932     for (unsigned i = 0; i != NumLaneElems; ++i) {
3933       int Idx = Mask[i+l];
3934       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3935       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3936         return false;
3937       // For VSHUFPSY, the mask of the second half must be the same as the
3938       // first but with the appropriate offsets. This works in the same way as
3939       // VPERMILPS works with masks.
3940       if (!symetricMaskRequired || Idx < 0)
3941         continue;
3942       if (MaskVal[i] < 0) {
3943         MaskVal[i] = Idx - l;
3944         continue;
3945       }
3946       if ((signed)(Idx - l) != MaskVal[i])
3947         return false;
3948     }
3949   }
3950
3951   return true;
3952 }
3953
3954 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3955 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3956 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3957   if (!VT.is128BitVector())
3958     return false;
3959
3960   unsigned NumElems = VT.getVectorNumElements();
3961
3962   if (NumElems != 4)
3963     return false;
3964
3965   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3966   return isUndefOrEqual(Mask[0], 6) &&
3967          isUndefOrEqual(Mask[1], 7) &&
3968          isUndefOrEqual(Mask[2], 2) &&
3969          isUndefOrEqual(Mask[3], 3);
3970 }
3971
3972 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3973 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3974 /// <2, 3, 2, 3>
3975 static bool isMOVHLPS_v_undef_Mask(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   return isUndefOrEqual(Mask[0], 2) &&
3985          isUndefOrEqual(Mask[1], 3) &&
3986          isUndefOrEqual(Mask[2], 2) &&
3987          isUndefOrEqual(Mask[3], 3);
3988 }
3989
3990 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3991 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3992 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3993   if (!VT.is128BitVector())
3994     return false;
3995
3996   unsigned NumElems = VT.getVectorNumElements();
3997
3998   if (NumElems != 2 && NumElems != 4)
3999     return false;
4000
4001   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4002     if (!isUndefOrEqual(Mask[i], i + NumElems))
4003       return false;
4004
4005   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4006     if (!isUndefOrEqual(Mask[i], i))
4007       return false;
4008
4009   return true;
4010 }
4011
4012 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4013 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4014 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4015   if (!VT.is128BitVector())
4016     return false;
4017
4018   unsigned NumElems = VT.getVectorNumElements();
4019
4020   if (NumElems != 2 && NumElems != 4)
4021     return false;
4022
4023   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4024     if (!isUndefOrEqual(Mask[i], i))
4025       return false;
4026
4027   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4028     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4029       return false;
4030
4031   return true;
4032 }
4033
4034 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4035 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4036 /// i. e: If all but one element come from the same vector.
4037 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4038   // TODO: Deal with AVX's VINSERTPS
4039   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4040     return false;
4041
4042   unsigned CorrectPosV1 = 0;
4043   unsigned CorrectPosV2 = 0;
4044   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4045     if (Mask[i] == -1) {
4046       ++CorrectPosV1;
4047       ++CorrectPosV2;
4048       continue;
4049     }
4050
4051     if (Mask[i] == i)
4052       ++CorrectPosV1;
4053     else if (Mask[i] == i + 4)
4054       ++CorrectPosV2;
4055   }
4056
4057   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4058     // We have 3 elements (undefs count as elements from any vector) from one
4059     // vector, and one from another.
4060     return true;
4061
4062   return false;
4063 }
4064
4065 //
4066 // Some special combinations that can be optimized.
4067 //
4068 static
4069 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4070                                SelectionDAG &DAG) {
4071   MVT VT = SVOp->getSimpleValueType(0);
4072   SDLoc dl(SVOp);
4073
4074   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4075     return SDValue();
4076
4077   ArrayRef<int> Mask = SVOp->getMask();
4078
4079   // These are the special masks that may be optimized.
4080   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4081   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4082   bool MatchEvenMask = true;
4083   bool MatchOddMask  = true;
4084   for (int i=0; i<8; ++i) {
4085     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4086       MatchEvenMask = false;
4087     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4088       MatchOddMask = false;
4089   }
4090
4091   if (!MatchEvenMask && !MatchOddMask)
4092     return SDValue();
4093
4094   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4095
4096   SDValue Op0 = SVOp->getOperand(0);
4097   SDValue Op1 = SVOp->getOperand(1);
4098
4099   if (MatchEvenMask) {
4100     // Shift the second operand right to 32 bits.
4101     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4102     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4103   } else {
4104     // Shift the first operand left to 32 bits.
4105     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4106     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4107   }
4108   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4109   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4110 }
4111
4112 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4113 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4114 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4115                          bool HasInt256, bool V2IsSplat = false) {
4116
4117   assert(VT.getSizeInBits() >= 128 &&
4118          "Unsupported vector type for unpckl");
4119
4120   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4121   unsigned NumLanes;
4122   unsigned NumOf256BitLanes;
4123   unsigned NumElts = VT.getVectorNumElements();
4124   if (VT.is256BitVector()) {
4125     if (NumElts != 4 && NumElts != 8 &&
4126         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4127     return false;
4128     NumLanes = 2;
4129     NumOf256BitLanes = 1;
4130   } else if (VT.is512BitVector()) {
4131     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4132            "Unsupported vector type for unpckh");
4133     NumLanes = 2;
4134     NumOf256BitLanes = 2;
4135   } else {
4136     NumLanes = 1;
4137     NumOf256BitLanes = 1;
4138   }
4139
4140   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4141   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4142
4143   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4144     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4145       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4146         int BitI  = Mask[l256*NumEltsInStride+l+i];
4147         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4148         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4149           return false;
4150         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4151           return false;
4152         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4153           return false;
4154       }
4155     }
4156   }
4157   return true;
4158 }
4159
4160 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4161 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4162 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4163                          bool HasInt256, bool V2IsSplat = false) {
4164   assert(VT.getSizeInBits() >= 128 &&
4165          "Unsupported vector type for unpckh");
4166
4167   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4168   unsigned NumLanes;
4169   unsigned NumOf256BitLanes;
4170   unsigned NumElts = VT.getVectorNumElements();
4171   if (VT.is256BitVector()) {
4172     if (NumElts != 4 && NumElts != 8 &&
4173         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4174     return false;
4175     NumLanes = 2;
4176     NumOf256BitLanes = 1;
4177   } else if (VT.is512BitVector()) {
4178     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4179            "Unsupported vector type for unpckh");
4180     NumLanes = 2;
4181     NumOf256BitLanes = 2;
4182   } else {
4183     NumLanes = 1;
4184     NumOf256BitLanes = 1;
4185   }
4186
4187   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4188   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4189
4190   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4191     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4192       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4193         int BitI  = Mask[l256*NumEltsInStride+l+i];
4194         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4195         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4196           return false;
4197         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4198           return false;
4199         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4200           return false;
4201       }
4202     }
4203   }
4204   return true;
4205 }
4206
4207 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4208 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4209 /// <0, 0, 1, 1>
4210 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4211   unsigned NumElts = VT.getVectorNumElements();
4212   bool Is256BitVec = VT.is256BitVector();
4213
4214   if (VT.is512BitVector())
4215     return false;
4216   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4217          "Unsupported vector type for unpckh");
4218
4219   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4220       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4221     return false;
4222
4223   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4224   // FIXME: Need a better way to get rid of this, there's no latency difference
4225   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4226   // the former later. We should also remove the "_undef" special mask.
4227   if (NumElts == 4 && Is256BitVec)
4228     return false;
4229
4230   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4231   // independently on 128-bit lanes.
4232   unsigned NumLanes = VT.getSizeInBits()/128;
4233   unsigned NumLaneElts = NumElts/NumLanes;
4234
4235   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4236     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4237       int BitI  = Mask[l+i];
4238       int BitI1 = Mask[l+i+1];
4239
4240       if (!isUndefOrEqual(BitI, j))
4241         return false;
4242       if (!isUndefOrEqual(BitI1, j))
4243         return false;
4244     }
4245   }
4246
4247   return true;
4248 }
4249
4250 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4251 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4252 /// <2, 2, 3, 3>
4253 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4254   unsigned NumElts = VT.getVectorNumElements();
4255
4256   if (VT.is512BitVector())
4257     return false;
4258
4259   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4260          "Unsupported vector type for unpckh");
4261
4262   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4263       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4264     return false;
4265
4266   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4267   // independently on 128-bit lanes.
4268   unsigned NumLanes = VT.getSizeInBits()/128;
4269   unsigned NumLaneElts = NumElts/NumLanes;
4270
4271   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4272     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4273       int BitI  = Mask[l+i];
4274       int BitI1 = Mask[l+i+1];
4275       if (!isUndefOrEqual(BitI, j))
4276         return false;
4277       if (!isUndefOrEqual(BitI1, j))
4278         return false;
4279     }
4280   }
4281   return true;
4282 }
4283
4284 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4285 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4286 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4287   if (!VT.is512BitVector())
4288     return false;
4289
4290   unsigned NumElts = VT.getVectorNumElements();
4291   unsigned HalfSize = NumElts/2;
4292   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4293     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4294       *Imm = 1;
4295       return true;
4296     }
4297   }
4298   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4299     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4300       *Imm = 0;
4301       return true;
4302     }
4303   }
4304   return false;
4305 }
4306
4307 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4308 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4309 /// MOVSD, and MOVD, i.e. setting the lowest element.
4310 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4311   if (VT.getVectorElementType().getSizeInBits() < 32)
4312     return false;
4313   if (!VT.is128BitVector())
4314     return false;
4315
4316   unsigned NumElts = VT.getVectorNumElements();
4317
4318   if (!isUndefOrEqual(Mask[0], NumElts))
4319     return false;
4320
4321   for (unsigned i = 1; i != NumElts; ++i)
4322     if (!isUndefOrEqual(Mask[i], i))
4323       return false;
4324
4325   return true;
4326 }
4327
4328 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4329 /// as permutations between 128-bit chunks or halves. As an example: this
4330 /// shuffle bellow:
4331 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4332 /// The first half comes from the second half of V1 and the second half from the
4333 /// the second half of V2.
4334 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4335   if (!HasFp256 || !VT.is256BitVector())
4336     return false;
4337
4338   // The shuffle result is divided into half A and half B. In total the two
4339   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4340   // B must come from C, D, E or F.
4341   unsigned HalfSize = VT.getVectorNumElements()/2;
4342   bool MatchA = false, MatchB = false;
4343
4344   // Check if A comes from one of C, D, E, F.
4345   for (unsigned Half = 0; Half != 4; ++Half) {
4346     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4347       MatchA = true;
4348       break;
4349     }
4350   }
4351
4352   // Check if B comes from one of C, D, E, F.
4353   for (unsigned Half = 0; Half != 4; ++Half) {
4354     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4355       MatchB = true;
4356       break;
4357     }
4358   }
4359
4360   return MatchA && MatchB;
4361 }
4362
4363 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4364 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4365 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4366   MVT VT = SVOp->getSimpleValueType(0);
4367
4368   unsigned HalfSize = VT.getVectorNumElements()/2;
4369
4370   unsigned FstHalf = 0, SndHalf = 0;
4371   for (unsigned i = 0; i < HalfSize; ++i) {
4372     if (SVOp->getMaskElt(i) > 0) {
4373       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4374       break;
4375     }
4376   }
4377   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4378     if (SVOp->getMaskElt(i) > 0) {
4379       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4380       break;
4381     }
4382   }
4383
4384   return (FstHalf | (SndHalf << 4));
4385 }
4386
4387 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4388 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4389   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4390   if (EltSize < 32)
4391     return false;
4392
4393   unsigned NumElts = VT.getVectorNumElements();
4394   Imm8 = 0;
4395   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4396     for (unsigned i = 0; i != NumElts; ++i) {
4397       if (Mask[i] < 0)
4398         continue;
4399       Imm8 |= Mask[i] << (i*2);
4400     }
4401     return true;
4402   }
4403
4404   unsigned LaneSize = 4;
4405   SmallVector<int, 4> MaskVal(LaneSize, -1);
4406
4407   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4408     for (unsigned i = 0; i != LaneSize; ++i) {
4409       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4410         return false;
4411       if (Mask[i+l] < 0)
4412         continue;
4413       if (MaskVal[i] < 0) {
4414         MaskVal[i] = Mask[i+l] - l;
4415         Imm8 |= MaskVal[i] << (i*2);
4416         continue;
4417       }
4418       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4419         return false;
4420     }
4421   }
4422   return true;
4423 }
4424
4425 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4426 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4427 /// Note that VPERMIL mask matching is different depending whether theunderlying
4428 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4429 /// to the same elements of the low, but to the higher half of the source.
4430 /// In VPERMILPD the two lanes could be shuffled independently of each other
4431 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4432 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4433   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4434   if (VT.getSizeInBits() < 256 || EltSize < 32)
4435     return false;
4436   bool symetricMaskRequired = (EltSize == 32);
4437   unsigned NumElts = VT.getVectorNumElements();
4438
4439   unsigned NumLanes = VT.getSizeInBits()/128;
4440   unsigned LaneSize = NumElts/NumLanes;
4441   // 2 or 4 elements in one lane
4442
4443   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4444   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4445     for (unsigned i = 0; i != LaneSize; ++i) {
4446       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4447         return false;
4448       if (symetricMaskRequired) {
4449         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4450           ExpectedMaskVal[i] = Mask[i+l] - l;
4451           continue;
4452         }
4453         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4454           return false;
4455       }
4456     }
4457   }
4458   return true;
4459 }
4460
4461 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4462 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4463 /// element of vector 2 and the other elements to come from vector 1 in order.
4464 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4465                                bool V2IsSplat = false, bool V2IsUndef = false) {
4466   if (!VT.is128BitVector())
4467     return false;
4468
4469   unsigned NumOps = VT.getVectorNumElements();
4470   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4471     return false;
4472
4473   if (!isUndefOrEqual(Mask[0], 0))
4474     return false;
4475
4476   for (unsigned i = 1; i != NumOps; ++i)
4477     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4478           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4479           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4480       return false;
4481
4482   return true;
4483 }
4484
4485 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4486 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4487 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4488 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4489                            const X86Subtarget *Subtarget) {
4490   if (!Subtarget->hasSSE3())
4491     return false;
4492
4493   unsigned NumElems = VT.getVectorNumElements();
4494
4495   if ((VT.is128BitVector() && NumElems != 4) ||
4496       (VT.is256BitVector() && NumElems != 8) ||
4497       (VT.is512BitVector() && NumElems != 16))
4498     return false;
4499
4500   // "i+1" is the value the indexed mask element must have
4501   for (unsigned i = 0; i != NumElems; i += 2)
4502     if (!isUndefOrEqual(Mask[i], i+1) ||
4503         !isUndefOrEqual(Mask[i+1], i+1))
4504       return false;
4505
4506   return true;
4507 }
4508
4509 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4510 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4511 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4512 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4513                            const X86Subtarget *Subtarget) {
4514   if (!Subtarget->hasSSE3())
4515     return false;
4516
4517   unsigned NumElems = VT.getVectorNumElements();
4518
4519   if ((VT.is128BitVector() && NumElems != 4) ||
4520       (VT.is256BitVector() && NumElems != 8) ||
4521       (VT.is512BitVector() && NumElems != 16))
4522     return false;
4523
4524   // "i" is the value the indexed mask element must have
4525   for (unsigned i = 0; i != NumElems; i += 2)
4526     if (!isUndefOrEqual(Mask[i], i) ||
4527         !isUndefOrEqual(Mask[i+1], i))
4528       return false;
4529
4530   return true;
4531 }
4532
4533 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4534 /// specifies a shuffle of elements that is suitable for input to 256-bit
4535 /// version of MOVDDUP.
4536 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4537   if (!HasFp256 || !VT.is256BitVector())
4538     return false;
4539
4540   unsigned NumElts = VT.getVectorNumElements();
4541   if (NumElts != 4)
4542     return false;
4543
4544   for (unsigned i = 0; i != NumElts/2; ++i)
4545     if (!isUndefOrEqual(Mask[i], 0))
4546       return false;
4547   for (unsigned i = NumElts/2; i != NumElts; ++i)
4548     if (!isUndefOrEqual(Mask[i], NumElts/2))
4549       return false;
4550   return true;
4551 }
4552
4553 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4554 /// specifies a shuffle of elements that is suitable for input to 128-bit
4555 /// version of MOVDDUP.
4556 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4557   if (!VT.is128BitVector())
4558     return false;
4559
4560   unsigned e = VT.getVectorNumElements() / 2;
4561   for (unsigned i = 0; i != e; ++i)
4562     if (!isUndefOrEqual(Mask[i], i))
4563       return false;
4564   for (unsigned i = 0; i != e; ++i)
4565     if (!isUndefOrEqual(Mask[e+i], i))
4566       return false;
4567   return true;
4568 }
4569
4570 /// isVEXTRACTIndex - Return true if the specified
4571 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4572 /// suitable for instruction that extract 128 or 256 bit vectors
4573 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4574   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4575   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4576     return false;
4577
4578   // The index should be aligned on a vecWidth-bit boundary.
4579   uint64_t Index =
4580     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4581
4582   MVT VT = N->getSimpleValueType(0);
4583   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4584   bool Result = (Index * ElSize) % vecWidth == 0;
4585
4586   return Result;
4587 }
4588
4589 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4590 /// operand specifies a subvector insert that is suitable for input to
4591 /// insertion of 128 or 256-bit subvectors
4592 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4593   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4594   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4595     return false;
4596   // The index should be aligned on a vecWidth-bit boundary.
4597   uint64_t Index =
4598     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4599
4600   MVT VT = N->getSimpleValueType(0);
4601   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4602   bool Result = (Index * ElSize) % vecWidth == 0;
4603
4604   return Result;
4605 }
4606
4607 bool X86::isVINSERT128Index(SDNode *N) {
4608   return isVINSERTIndex(N, 128);
4609 }
4610
4611 bool X86::isVINSERT256Index(SDNode *N) {
4612   return isVINSERTIndex(N, 256);
4613 }
4614
4615 bool X86::isVEXTRACT128Index(SDNode *N) {
4616   return isVEXTRACTIndex(N, 128);
4617 }
4618
4619 bool X86::isVEXTRACT256Index(SDNode *N) {
4620   return isVEXTRACTIndex(N, 256);
4621 }
4622
4623 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4624 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4625 /// Handles 128-bit and 256-bit.
4626 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4627   MVT VT = N->getSimpleValueType(0);
4628
4629   assert((VT.getSizeInBits() >= 128) &&
4630          "Unsupported vector type for PSHUF/SHUFP");
4631
4632   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4633   // independently on 128-bit lanes.
4634   unsigned NumElts = VT.getVectorNumElements();
4635   unsigned NumLanes = VT.getSizeInBits()/128;
4636   unsigned NumLaneElts = NumElts/NumLanes;
4637
4638   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4639          "Only supports 2, 4 or 8 elements per lane");
4640
4641   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4642   unsigned Mask = 0;
4643   for (unsigned i = 0; i != NumElts; ++i) {
4644     int Elt = N->getMaskElt(i);
4645     if (Elt < 0) continue;
4646     Elt &= NumLaneElts - 1;
4647     unsigned ShAmt = (i << Shift) % 8;
4648     Mask |= Elt << ShAmt;
4649   }
4650
4651   return Mask;
4652 }
4653
4654 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4655 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4656 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4657   MVT VT = N->getSimpleValueType(0);
4658
4659   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4660          "Unsupported vector type for PSHUFHW");
4661
4662   unsigned NumElts = VT.getVectorNumElements();
4663
4664   unsigned Mask = 0;
4665   for (unsigned l = 0; l != NumElts; l += 8) {
4666     // 8 nodes per lane, but we only care about the last 4.
4667     for (unsigned i = 0; i < 4; ++i) {
4668       int Elt = N->getMaskElt(l+i+4);
4669       if (Elt < 0) continue;
4670       Elt &= 0x3; // only 2-bits.
4671       Mask |= Elt << (i * 2);
4672     }
4673   }
4674
4675   return Mask;
4676 }
4677
4678 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4679 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4680 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4681   MVT VT = N->getSimpleValueType(0);
4682
4683   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4684          "Unsupported vector type for PSHUFHW");
4685
4686   unsigned NumElts = VT.getVectorNumElements();
4687
4688   unsigned Mask = 0;
4689   for (unsigned l = 0; l != NumElts; l += 8) {
4690     // 8 nodes per lane, but we only care about the first 4.
4691     for (unsigned i = 0; i < 4; ++i) {
4692       int Elt = N->getMaskElt(l+i);
4693       if (Elt < 0) continue;
4694       Elt &= 0x3; // only 2-bits
4695       Mask |= Elt << (i * 2);
4696     }
4697   }
4698
4699   return Mask;
4700 }
4701
4702 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4703 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4704 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4705   MVT VT = SVOp->getSimpleValueType(0);
4706   unsigned EltSize = VT.is512BitVector() ? 1 :
4707     VT.getVectorElementType().getSizeInBits() >> 3;
4708
4709   unsigned NumElts = VT.getVectorNumElements();
4710   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4711   unsigned NumLaneElts = NumElts/NumLanes;
4712
4713   int Val = 0;
4714   unsigned i;
4715   for (i = 0; i != NumElts; ++i) {
4716     Val = SVOp->getMaskElt(i);
4717     if (Val >= 0)
4718       break;
4719   }
4720   if (Val >= (int)NumElts)
4721     Val -= NumElts - NumLaneElts;
4722
4723   assert(Val - i > 0 && "PALIGNR imm should be positive");
4724   return (Val - i) * EltSize;
4725 }
4726
4727 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4728   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4729   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4730     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4731
4732   uint64_t Index =
4733     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4734
4735   MVT VecVT = N->getOperand(0).getSimpleValueType();
4736   MVT ElVT = VecVT.getVectorElementType();
4737
4738   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4739   return Index / NumElemsPerChunk;
4740 }
4741
4742 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4743   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4744   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4745     llvm_unreachable("Illegal insert subvector for VINSERT");
4746
4747   uint64_t Index =
4748     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4749
4750   MVT VecVT = N->getSimpleValueType(0);
4751   MVT ElVT = VecVT.getVectorElementType();
4752
4753   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4754   return Index / NumElemsPerChunk;
4755 }
4756
4757 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4758 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4759 /// and VINSERTI128 instructions.
4760 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4761   return getExtractVEXTRACTImmediate(N, 128);
4762 }
4763
4764 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4765 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4766 /// and VINSERTI64x4 instructions.
4767 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4768   return getExtractVEXTRACTImmediate(N, 256);
4769 }
4770
4771 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4772 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4773 /// and VINSERTI128 instructions.
4774 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4775   return getInsertVINSERTImmediate(N, 128);
4776 }
4777
4778 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4779 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4780 /// and VINSERTI64x4 instructions.
4781 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4782   return getInsertVINSERTImmediate(N, 256);
4783 }
4784
4785 /// isZero - Returns true if Elt is a constant integer zero
4786 static bool isZero(SDValue V) {
4787   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4788   return C && C->isNullValue();
4789 }
4790
4791 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4792 /// constant +0.0.
4793 bool X86::isZeroNode(SDValue Elt) {
4794   if (isZero(Elt))
4795     return true;
4796   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4797     return CFP->getValueAPF().isPosZero();
4798   return false;
4799 }
4800
4801 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4802 /// match movhlps. The lower half elements should come from upper half of
4803 /// V1 (and in order), and the upper half elements should come from the upper
4804 /// half of V2 (and in order).
4805 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4806   if (!VT.is128BitVector())
4807     return false;
4808   if (VT.getVectorNumElements() != 4)
4809     return false;
4810   for (unsigned i = 0, e = 2; i != e; ++i)
4811     if (!isUndefOrEqual(Mask[i], i+2))
4812       return false;
4813   for (unsigned i = 2; i != 4; ++i)
4814     if (!isUndefOrEqual(Mask[i], i+4))
4815       return false;
4816   return true;
4817 }
4818
4819 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4820 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4821 /// required.
4822 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4823   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4824     return false;
4825   N = N->getOperand(0).getNode();
4826   if (!ISD::isNON_EXTLoad(N))
4827     return false;
4828   if (LD)
4829     *LD = cast<LoadSDNode>(N);
4830   return true;
4831 }
4832
4833 // Test whether the given value is a vector value which will be legalized
4834 // into a load.
4835 static bool WillBeConstantPoolLoad(SDNode *N) {
4836   if (N->getOpcode() != ISD::BUILD_VECTOR)
4837     return false;
4838
4839   // Check for any non-constant elements.
4840   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4841     switch (N->getOperand(i).getNode()->getOpcode()) {
4842     case ISD::UNDEF:
4843     case ISD::ConstantFP:
4844     case ISD::Constant:
4845       break;
4846     default:
4847       return false;
4848     }
4849
4850   // Vectors of all-zeros and all-ones are materialized with special
4851   // instructions rather than being loaded.
4852   return !ISD::isBuildVectorAllZeros(N) &&
4853          !ISD::isBuildVectorAllOnes(N);
4854 }
4855
4856 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4857 /// match movlp{s|d}. The lower half elements should come from lower half of
4858 /// V1 (and in order), and the upper half elements should come from the upper
4859 /// half of V2 (and in order). And since V1 will become the source of the
4860 /// MOVLP, it must be either a vector load or a scalar load to vector.
4861 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4862                                ArrayRef<int> Mask, MVT VT) {
4863   if (!VT.is128BitVector())
4864     return false;
4865
4866   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4867     return false;
4868   // Is V2 is a vector load, don't do this transformation. We will try to use
4869   // load folding shufps op.
4870   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4871     return false;
4872
4873   unsigned NumElems = VT.getVectorNumElements();
4874
4875   if (NumElems != 2 && NumElems != 4)
4876     return false;
4877   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4878     if (!isUndefOrEqual(Mask[i], i))
4879       return false;
4880   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4881     if (!isUndefOrEqual(Mask[i], i+NumElems))
4882       return false;
4883   return true;
4884 }
4885
4886 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4887 /// to an zero vector.
4888 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4889 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4890   SDValue V1 = N->getOperand(0);
4891   SDValue V2 = N->getOperand(1);
4892   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4893   for (unsigned i = 0; i != NumElems; ++i) {
4894     int Idx = N->getMaskElt(i);
4895     if (Idx >= (int)NumElems) {
4896       unsigned Opc = V2.getOpcode();
4897       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4898         continue;
4899       if (Opc != ISD::BUILD_VECTOR ||
4900           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4901         return false;
4902     } else if (Idx >= 0) {
4903       unsigned Opc = V1.getOpcode();
4904       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4905         continue;
4906       if (Opc != ISD::BUILD_VECTOR ||
4907           !X86::isZeroNode(V1.getOperand(Idx)))
4908         return false;
4909     }
4910   }
4911   return true;
4912 }
4913
4914 /// getZeroVector - Returns a vector of specified type with all zero elements.
4915 ///
4916 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4917                              SelectionDAG &DAG, SDLoc dl) {
4918   assert(VT.isVector() && "Expected a vector type");
4919
4920   // Always build SSE zero vectors as <4 x i32> bitcasted
4921   // to their dest type. This ensures they get CSE'd.
4922   SDValue Vec;
4923   if (VT.is128BitVector()) {  // SSE
4924     if (Subtarget->hasSSE2()) {  // SSE2
4925       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4926       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4927     } else { // SSE1
4928       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4929       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4930     }
4931   } else if (VT.is256BitVector()) { // AVX
4932     if (Subtarget->hasInt256()) { // AVX2
4933       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4934       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4935       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4936     } else {
4937       // 256-bit logic and arithmetic instructions in AVX are all
4938       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4939       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4940       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4941       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4942     }
4943   } else if (VT.is512BitVector()) { // AVX-512
4944       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4945       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4946                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4947       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4948   } else if (VT.getScalarType() == MVT::i1) {
4949     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4950     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4951     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4952     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4953   } else
4954     llvm_unreachable("Unexpected vector type");
4955
4956   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4957 }
4958
4959 /// getOnesVector - Returns a vector of specified type with all bits set.
4960 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4961 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4962 /// Then bitcast to their original type, ensuring they get CSE'd.
4963 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4964                              SDLoc dl) {
4965   assert(VT.isVector() && "Expected a vector type");
4966
4967   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4968   SDValue Vec;
4969   if (VT.is256BitVector()) {
4970     if (HasInt256) { // AVX2
4971       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4972       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4973     } else { // AVX
4974       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4975       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4976     }
4977   } else if (VT.is128BitVector()) {
4978     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4979   } else
4980     llvm_unreachable("Unexpected vector type");
4981
4982   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4983 }
4984
4985 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4986 /// that point to V2 points to its first element.
4987 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4988   for (unsigned i = 0; i != NumElems; ++i) {
4989     if (Mask[i] > (int)NumElems) {
4990       Mask[i] = NumElems;
4991     }
4992   }
4993 }
4994
4995 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4996 /// operation of specified width.
4997 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4998                        SDValue V2) {
4999   unsigned NumElems = VT.getVectorNumElements();
5000   SmallVector<int, 8> Mask;
5001   Mask.push_back(NumElems);
5002   for (unsigned i = 1; i != NumElems; ++i)
5003     Mask.push_back(i);
5004   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5005 }
5006
5007 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5008 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5009                           SDValue V2) {
5010   unsigned NumElems = VT.getVectorNumElements();
5011   SmallVector<int, 8> Mask;
5012   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5013     Mask.push_back(i);
5014     Mask.push_back(i + NumElems);
5015   }
5016   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5017 }
5018
5019 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5020 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5021                           SDValue V2) {
5022   unsigned NumElems = VT.getVectorNumElements();
5023   SmallVector<int, 8> Mask;
5024   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5025     Mask.push_back(i + Half);
5026     Mask.push_back(i + NumElems + Half);
5027   }
5028   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5029 }
5030
5031 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5032 // a generic shuffle instruction because the target has no such instructions.
5033 // Generate shuffles which repeat i16 and i8 several times until they can be
5034 // represented by v4f32 and then be manipulated by target suported shuffles.
5035 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5036   MVT VT = V.getSimpleValueType();
5037   int NumElems = VT.getVectorNumElements();
5038   SDLoc dl(V);
5039
5040   while (NumElems > 4) {
5041     if (EltNo < NumElems/2) {
5042       V = getUnpackl(DAG, dl, VT, V, V);
5043     } else {
5044       V = getUnpackh(DAG, dl, VT, V, V);
5045       EltNo -= NumElems/2;
5046     }
5047     NumElems >>= 1;
5048   }
5049   return V;
5050 }
5051
5052 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5053 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5054   MVT VT = V.getSimpleValueType();
5055   SDLoc dl(V);
5056
5057   if (VT.is128BitVector()) {
5058     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5059     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5060     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5061                              &SplatMask[0]);
5062   } else if (VT.is256BitVector()) {
5063     // To use VPERMILPS to splat scalars, the second half of indicies must
5064     // refer to the higher part, which is a duplication of the lower one,
5065     // because VPERMILPS can only handle in-lane permutations.
5066     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5067                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5068
5069     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5070     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5071                              &SplatMask[0]);
5072   } else
5073     llvm_unreachable("Vector size not supported");
5074
5075   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5076 }
5077
5078 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5079 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5080   MVT SrcVT = SV->getSimpleValueType(0);
5081   SDValue V1 = SV->getOperand(0);
5082   SDLoc dl(SV);
5083
5084   int EltNo = SV->getSplatIndex();
5085   int NumElems = SrcVT.getVectorNumElements();
5086   bool Is256BitVec = SrcVT.is256BitVector();
5087
5088   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5089          "Unknown how to promote splat for type");
5090
5091   // Extract the 128-bit part containing the splat element and update
5092   // the splat element index when it refers to the higher register.
5093   if (Is256BitVec) {
5094     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5095     if (EltNo >= NumElems/2)
5096       EltNo -= NumElems/2;
5097   }
5098
5099   // All i16 and i8 vector types can't be used directly by a generic shuffle
5100   // instruction because the target has no such instruction. Generate shuffles
5101   // which repeat i16 and i8 several times until they fit in i32, and then can
5102   // be manipulated by target suported shuffles.
5103   MVT EltVT = SrcVT.getVectorElementType();
5104   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5105     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5106
5107   // Recreate the 256-bit vector and place the same 128-bit vector
5108   // into the low and high part. This is necessary because we want
5109   // to use VPERM* to shuffle the vectors
5110   if (Is256BitVec) {
5111     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5112   }
5113
5114   return getLegalSplat(DAG, V1, EltNo);
5115 }
5116
5117 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5118 /// vector of zero or undef vector.  This produces a shuffle where the low
5119 /// element of V2 is swizzled into the zero/undef vector, landing at element
5120 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5121 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5122                                            bool IsZero,
5123                                            const X86Subtarget *Subtarget,
5124                                            SelectionDAG &DAG) {
5125   MVT VT = V2.getSimpleValueType();
5126   SDValue V1 = IsZero
5127     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5128   unsigned NumElems = VT.getVectorNumElements();
5129   SmallVector<int, 16> MaskVec;
5130   for (unsigned i = 0; i != NumElems; ++i)
5131     // If this is the insertion idx, put the low elt of V2 here.
5132     MaskVec.push_back(i == Idx ? NumElems : i);
5133   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5134 }
5135
5136 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5137 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5138 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5139 /// shuffles which use a single input multiple times, and in those cases it will
5140 /// adjust the mask to only have indices within that single input.
5141 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5142                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5143   unsigned NumElems = VT.getVectorNumElements();
5144   SDValue ImmN;
5145
5146   IsUnary = false;
5147   bool IsFakeUnary = false;
5148   switch(N->getOpcode()) {
5149   case X86ISD::SHUFP:
5150     ImmN = N->getOperand(N->getNumOperands()-1);
5151     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5152     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5153     break;
5154   case X86ISD::UNPCKH:
5155     DecodeUNPCKHMask(VT, Mask);
5156     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5157     break;
5158   case X86ISD::UNPCKL:
5159     DecodeUNPCKLMask(VT, Mask);
5160     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5161     break;
5162   case X86ISD::MOVHLPS:
5163     DecodeMOVHLPSMask(NumElems, Mask);
5164     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5165     break;
5166   case X86ISD::MOVLHPS:
5167     DecodeMOVLHPSMask(NumElems, Mask);
5168     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5169     break;
5170   case X86ISD::PALIGNR:
5171     ImmN = N->getOperand(N->getNumOperands()-1);
5172     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5173     break;
5174   case X86ISD::PSHUFD:
5175   case X86ISD::VPERMILP:
5176     ImmN = N->getOperand(N->getNumOperands()-1);
5177     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5178     IsUnary = true;
5179     break;
5180   case X86ISD::PSHUFHW:
5181     ImmN = N->getOperand(N->getNumOperands()-1);
5182     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5183     IsUnary = true;
5184     break;
5185   case X86ISD::PSHUFLW:
5186     ImmN = N->getOperand(N->getNumOperands()-1);
5187     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5188     IsUnary = true;
5189     break;
5190   case X86ISD::PSHUFB: {
5191     IsUnary = true;
5192     SDValue MaskNode = N->getOperand(1);
5193     while (MaskNode->getOpcode() == ISD::BITCAST)
5194       MaskNode = MaskNode->getOperand(0);
5195
5196     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5197       // If we have a build-vector, then things are easy.
5198       EVT VT = MaskNode.getValueType();
5199       assert(VT.isVector() &&
5200              "Can't produce a non-vector with a build_vector!");
5201       if (!VT.isInteger())
5202         return false;
5203
5204       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5205
5206       SmallVector<uint64_t, 32> RawMask;
5207       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5208         auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5209         if (!CN)
5210           return false;
5211         APInt MaskElement = CN->getAPIntValue();
5212
5213         // We now have to decode the element which could be any integer size and
5214         // extract each byte of it.
5215         for (int j = 0; j < NumBytesPerElement; ++j) {
5216           // Note that this is x86 and so always little endian: the low byte is
5217           // the first byte of the mask.
5218           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5219           MaskElement = MaskElement.lshr(8);
5220         }
5221       }
5222       DecodePSHUFBMask(RawMask, Mask);
5223       break;
5224     }
5225
5226     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5227     if (!MaskLoad)
5228       return false;
5229
5230     SDValue Ptr = MaskLoad->getBasePtr();
5231     if (Ptr->getOpcode() == X86ISD::Wrapper)
5232       Ptr = Ptr->getOperand(0);
5233
5234     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5235     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5236       return false;
5237
5238     if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5239       // FIXME: Support AVX-512 here.
5240       if (!C->getType()->isVectorTy() ||
5241           (C->getNumElements() != 16 && C->getNumElements() != 32))
5242         return false;
5243
5244       assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5245       DecodePSHUFBMask(C, Mask);
5246       break;
5247     }
5248
5249     return false;
5250   }
5251   case X86ISD::VPERMI:
5252     ImmN = N->getOperand(N->getNumOperands()-1);
5253     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5254     IsUnary = true;
5255     break;
5256   case X86ISD::MOVSS:
5257   case X86ISD::MOVSD: {
5258     // The index 0 always comes from the first element of the second source,
5259     // this is why MOVSS and MOVSD are used in the first place. The other
5260     // elements come from the other positions of the first source vector
5261     Mask.push_back(NumElems);
5262     for (unsigned i = 1; i != NumElems; ++i) {
5263       Mask.push_back(i);
5264     }
5265     break;
5266   }
5267   case X86ISD::VPERM2X128:
5268     ImmN = N->getOperand(N->getNumOperands()-1);
5269     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5270     if (Mask.empty()) return false;
5271     break;
5272   case X86ISD::MOVDDUP:
5273   case X86ISD::MOVLHPD:
5274   case X86ISD::MOVLPD:
5275   case X86ISD::MOVLPS:
5276   case X86ISD::MOVSHDUP:
5277   case X86ISD::MOVSLDUP:
5278     // Not yet implemented
5279     return false;
5280   default: llvm_unreachable("unknown target shuffle node");
5281   }
5282
5283   // If we have a fake unary shuffle, the shuffle mask is spread across two
5284   // inputs that are actually the same node. Re-map the mask to always point
5285   // into the first input.
5286   if (IsFakeUnary)
5287     for (int &M : Mask)
5288       if (M >= (int)Mask.size())
5289         M -= Mask.size();
5290
5291   return true;
5292 }
5293
5294 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5295 /// element of the result of the vector shuffle.
5296 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5297                                    unsigned Depth) {
5298   if (Depth == 6)
5299     return SDValue();  // Limit search depth.
5300
5301   SDValue V = SDValue(N, 0);
5302   EVT VT = V.getValueType();
5303   unsigned Opcode = V.getOpcode();
5304
5305   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5306   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5307     int Elt = SV->getMaskElt(Index);
5308
5309     if (Elt < 0)
5310       return DAG.getUNDEF(VT.getVectorElementType());
5311
5312     unsigned NumElems = VT.getVectorNumElements();
5313     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5314                                          : SV->getOperand(1);
5315     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5316   }
5317
5318   // Recurse into target specific vector shuffles to find scalars.
5319   if (isTargetShuffle(Opcode)) {
5320     MVT ShufVT = V.getSimpleValueType();
5321     unsigned NumElems = ShufVT.getVectorNumElements();
5322     SmallVector<int, 16> ShuffleMask;
5323     bool IsUnary;
5324
5325     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5326       return SDValue();
5327
5328     int Elt = ShuffleMask[Index];
5329     if (Elt < 0)
5330       return DAG.getUNDEF(ShufVT.getVectorElementType());
5331
5332     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5333                                          : N->getOperand(1);
5334     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5335                                Depth+1);
5336   }
5337
5338   // Actual nodes that may contain scalar elements
5339   if (Opcode == ISD::BITCAST) {
5340     V = V.getOperand(0);
5341     EVT SrcVT = V.getValueType();
5342     unsigned NumElems = VT.getVectorNumElements();
5343
5344     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5345       return SDValue();
5346   }
5347
5348   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5349     return (Index == 0) ? V.getOperand(0)
5350                         : DAG.getUNDEF(VT.getVectorElementType());
5351
5352   if (V.getOpcode() == ISD::BUILD_VECTOR)
5353     return V.getOperand(Index);
5354
5355   return SDValue();
5356 }
5357
5358 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5359 /// shuffle operation which come from a consecutively from a zero. The
5360 /// search can start in two different directions, from left or right.
5361 /// We count undefs as zeros until PreferredNum is reached.
5362 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5363                                          unsigned NumElems, bool ZerosFromLeft,
5364                                          SelectionDAG &DAG,
5365                                          unsigned PreferredNum = -1U) {
5366   unsigned NumZeros = 0;
5367   for (unsigned i = 0; i != NumElems; ++i) {
5368     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5369     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5370     if (!Elt.getNode())
5371       break;
5372
5373     if (X86::isZeroNode(Elt))
5374       ++NumZeros;
5375     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5376       NumZeros = std::min(NumZeros + 1, PreferredNum);
5377     else
5378       break;
5379   }
5380
5381   return NumZeros;
5382 }
5383
5384 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5385 /// correspond consecutively to elements from one of the vector operands,
5386 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5387 static
5388 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5389                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5390                               unsigned NumElems, unsigned &OpNum) {
5391   bool SeenV1 = false;
5392   bool SeenV2 = false;
5393
5394   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5395     int Idx = SVOp->getMaskElt(i);
5396     // Ignore undef indicies
5397     if (Idx < 0)
5398       continue;
5399
5400     if (Idx < (int)NumElems)
5401       SeenV1 = true;
5402     else
5403       SeenV2 = true;
5404
5405     // Only accept consecutive elements from the same vector
5406     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5407       return false;
5408   }
5409
5410   OpNum = SeenV1 ? 0 : 1;
5411   return true;
5412 }
5413
5414 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5415 /// logical left shift of a vector.
5416 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5417                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5418   unsigned NumElems =
5419     SVOp->getSimpleValueType(0).getVectorNumElements();
5420   unsigned NumZeros = getNumOfConsecutiveZeros(
5421       SVOp, NumElems, false /* check zeros from right */, DAG,
5422       SVOp->getMaskElt(0));
5423   unsigned OpSrc;
5424
5425   if (!NumZeros)
5426     return false;
5427
5428   // Considering the elements in the mask that are not consecutive zeros,
5429   // check if they consecutively come from only one of the source vectors.
5430   //
5431   //               V1 = {X, A, B, C}     0
5432   //                         \  \  \    /
5433   //   vector_shuffle V1, V2 <1, 2, 3, X>
5434   //
5435   if (!isShuffleMaskConsecutive(SVOp,
5436             0,                   // Mask Start Index
5437             NumElems-NumZeros,   // Mask End Index(exclusive)
5438             NumZeros,            // Where to start looking in the src vector
5439             NumElems,            // Number of elements in vector
5440             OpSrc))              // Which source operand ?
5441     return false;
5442
5443   isLeft = false;
5444   ShAmt = NumZeros;
5445   ShVal = SVOp->getOperand(OpSrc);
5446   return true;
5447 }
5448
5449 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5450 /// logical left shift of a vector.
5451 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5452                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5453   unsigned NumElems =
5454     SVOp->getSimpleValueType(0).getVectorNumElements();
5455   unsigned NumZeros = getNumOfConsecutiveZeros(
5456       SVOp, NumElems, true /* check zeros from left */, DAG,
5457       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5458   unsigned OpSrc;
5459
5460   if (!NumZeros)
5461     return false;
5462
5463   // Considering the elements in the mask that are not consecutive zeros,
5464   // check if they consecutively come from only one of the source vectors.
5465   //
5466   //                           0    { A, B, X, X } = V2
5467   //                          / \    /  /
5468   //   vector_shuffle V1, V2 <X, X, 4, 5>
5469   //
5470   if (!isShuffleMaskConsecutive(SVOp,
5471             NumZeros,     // Mask Start Index
5472             NumElems,     // Mask End Index(exclusive)
5473             0,            // Where to start looking in the src vector
5474             NumElems,     // Number of elements in vector
5475             OpSrc))       // Which source operand ?
5476     return false;
5477
5478   isLeft = true;
5479   ShAmt = NumZeros;
5480   ShVal = SVOp->getOperand(OpSrc);
5481   return true;
5482 }
5483
5484 /// isVectorShift - Returns true if the shuffle can be implemented as a
5485 /// logical left or right shift of a vector.
5486 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5487                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5488   // Although the logic below support any bitwidth size, there are no
5489   // shift instructions which handle more than 128-bit vectors.
5490   if (!SVOp->getSimpleValueType(0).is128BitVector())
5491     return false;
5492
5493   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5494       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5495     return true;
5496
5497   return false;
5498 }
5499
5500 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5501 ///
5502 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5503                                        unsigned NumNonZero, unsigned NumZero,
5504                                        SelectionDAG &DAG,
5505                                        const X86Subtarget* Subtarget,
5506                                        const TargetLowering &TLI) {
5507   if (NumNonZero > 8)
5508     return SDValue();
5509
5510   SDLoc dl(Op);
5511   SDValue V;
5512   bool First = true;
5513   for (unsigned i = 0; i < 16; ++i) {
5514     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5515     if (ThisIsNonZero && First) {
5516       if (NumZero)
5517         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5518       else
5519         V = DAG.getUNDEF(MVT::v8i16);
5520       First = false;
5521     }
5522
5523     if ((i & 1) != 0) {
5524       SDValue ThisElt, LastElt;
5525       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5526       if (LastIsNonZero) {
5527         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5528                               MVT::i16, Op.getOperand(i-1));
5529       }
5530       if (ThisIsNonZero) {
5531         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5532         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5533                               ThisElt, DAG.getConstant(8, MVT::i8));
5534         if (LastIsNonZero)
5535           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5536       } else
5537         ThisElt = LastElt;
5538
5539       if (ThisElt.getNode())
5540         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5541                         DAG.getIntPtrConstant(i/2));
5542     }
5543   }
5544
5545   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5546 }
5547
5548 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5549 ///
5550 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5551                                      unsigned NumNonZero, unsigned NumZero,
5552                                      SelectionDAG &DAG,
5553                                      const X86Subtarget* Subtarget,
5554                                      const TargetLowering &TLI) {
5555   if (NumNonZero > 4)
5556     return SDValue();
5557
5558   SDLoc dl(Op);
5559   SDValue V;
5560   bool First = true;
5561   for (unsigned i = 0; i < 8; ++i) {
5562     bool isNonZero = (NonZeros & (1 << i)) != 0;
5563     if (isNonZero) {
5564       if (First) {
5565         if (NumZero)
5566           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5567         else
5568           V = DAG.getUNDEF(MVT::v8i16);
5569         First = false;
5570       }
5571       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5572                       MVT::v8i16, V, Op.getOperand(i),
5573                       DAG.getIntPtrConstant(i));
5574     }
5575   }
5576
5577   return V;
5578 }
5579
5580 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5581 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5582                                      unsigned NonZeros, unsigned NumNonZero,
5583                                      unsigned NumZero, SelectionDAG &DAG,
5584                                      const X86Subtarget *Subtarget,
5585                                      const TargetLowering &TLI) {
5586   // We know there's at least one non-zero element
5587   unsigned FirstNonZeroIdx = 0;
5588   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5589   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5590          X86::isZeroNode(FirstNonZero)) {
5591     ++FirstNonZeroIdx;
5592     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5593   }
5594
5595   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5596       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5597     return SDValue();
5598
5599   SDValue V = FirstNonZero.getOperand(0);
5600   MVT VVT = V.getSimpleValueType();
5601   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5602     return SDValue();
5603
5604   unsigned FirstNonZeroDst =
5605       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5606   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5607   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5608   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5609
5610   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5611     SDValue Elem = Op.getOperand(Idx);
5612     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5613       continue;
5614
5615     // TODO: What else can be here? Deal with it.
5616     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5617       return SDValue();
5618
5619     // TODO: Some optimizations are still possible here
5620     // ex: Getting one element from a vector, and the rest from another.
5621     if (Elem.getOperand(0) != V)
5622       return SDValue();
5623
5624     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5625     if (Dst == Idx)
5626       ++CorrectIdx;
5627     else if (IncorrectIdx == -1U) {
5628       IncorrectIdx = Idx;
5629       IncorrectDst = Dst;
5630     } else
5631       // There was already one element with an incorrect index.
5632       // We can't optimize this case to an insertps.
5633       return SDValue();
5634   }
5635
5636   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5637     SDLoc dl(Op);
5638     EVT VT = Op.getSimpleValueType();
5639     unsigned ElementMoveMask = 0;
5640     if (IncorrectIdx == -1U)
5641       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5642     else
5643       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5644
5645     SDValue InsertpsMask =
5646         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5647     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5648   }
5649
5650   return SDValue();
5651 }
5652
5653 /// getVShift - Return a vector logical shift node.
5654 ///
5655 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5656                          unsigned NumBits, SelectionDAG &DAG,
5657                          const TargetLowering &TLI, SDLoc dl) {
5658   assert(VT.is128BitVector() && "Unknown type for VShift");
5659   EVT ShVT = MVT::v2i64;
5660   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5661   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5662   return DAG.getNode(ISD::BITCAST, dl, VT,
5663                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5664                              DAG.getConstant(NumBits,
5665                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5666 }
5667
5668 static SDValue
5669 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5670
5671   // Check if the scalar load can be widened into a vector load. And if
5672   // the address is "base + cst" see if the cst can be "absorbed" into
5673   // the shuffle mask.
5674   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5675     SDValue Ptr = LD->getBasePtr();
5676     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5677       return SDValue();
5678     EVT PVT = LD->getValueType(0);
5679     if (PVT != MVT::i32 && PVT != MVT::f32)
5680       return SDValue();
5681
5682     int FI = -1;
5683     int64_t Offset = 0;
5684     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5685       FI = FINode->getIndex();
5686       Offset = 0;
5687     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5688                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5689       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5690       Offset = Ptr.getConstantOperandVal(1);
5691       Ptr = Ptr.getOperand(0);
5692     } else {
5693       return SDValue();
5694     }
5695
5696     // FIXME: 256-bit vector instructions don't require a strict alignment,
5697     // improve this code to support it better.
5698     unsigned RequiredAlign = VT.getSizeInBits()/8;
5699     SDValue Chain = LD->getChain();
5700     // Make sure the stack object alignment is at least 16 or 32.
5701     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5702     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5703       if (MFI->isFixedObjectIndex(FI)) {
5704         // Can't change the alignment. FIXME: It's possible to compute
5705         // the exact stack offset and reference FI + adjust offset instead.
5706         // If someone *really* cares about this. That's the way to implement it.
5707         return SDValue();
5708       } else {
5709         MFI->setObjectAlignment(FI, RequiredAlign);
5710       }
5711     }
5712
5713     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5714     // Ptr + (Offset & ~15).
5715     if (Offset < 0)
5716       return SDValue();
5717     if ((Offset % RequiredAlign) & 3)
5718       return SDValue();
5719     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5720     if (StartOffset)
5721       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5722                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5723
5724     int EltNo = (Offset - StartOffset) >> 2;
5725     unsigned NumElems = VT.getVectorNumElements();
5726
5727     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5728     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5729                              LD->getPointerInfo().getWithOffset(StartOffset),
5730                              false, false, false, 0);
5731
5732     SmallVector<int, 8> Mask;
5733     for (unsigned i = 0; i != NumElems; ++i)
5734       Mask.push_back(EltNo);
5735
5736     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5737   }
5738
5739   return SDValue();
5740 }
5741
5742 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5743 /// vector of type 'VT', see if the elements can be replaced by a single large
5744 /// load which has the same value as a build_vector whose operands are 'elts'.
5745 ///
5746 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5747 ///
5748 /// FIXME: we'd also like to handle the case where the last elements are zero
5749 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5750 /// There's even a handy isZeroNode for that purpose.
5751 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5752                                         SDLoc &DL, SelectionDAG &DAG,
5753                                         bool isAfterLegalize) {
5754   EVT EltVT = VT.getVectorElementType();
5755   unsigned NumElems = Elts.size();
5756
5757   LoadSDNode *LDBase = nullptr;
5758   unsigned LastLoadedElt = -1U;
5759
5760   // For each element in the initializer, see if we've found a load or an undef.
5761   // If we don't find an initial load element, or later load elements are
5762   // non-consecutive, bail out.
5763   for (unsigned i = 0; i < NumElems; ++i) {
5764     SDValue Elt = Elts[i];
5765
5766     if (!Elt.getNode() ||
5767         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5768       return SDValue();
5769     if (!LDBase) {
5770       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5771         return SDValue();
5772       LDBase = cast<LoadSDNode>(Elt.getNode());
5773       LastLoadedElt = i;
5774       continue;
5775     }
5776     if (Elt.getOpcode() == ISD::UNDEF)
5777       continue;
5778
5779     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5780     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5781       return SDValue();
5782     LastLoadedElt = i;
5783   }
5784
5785   // If we have found an entire vector of loads and undefs, then return a large
5786   // load of the entire vector width starting at the base pointer.  If we found
5787   // consecutive loads for the low half, generate a vzext_load node.
5788   if (LastLoadedElt == NumElems - 1) {
5789
5790     if (isAfterLegalize &&
5791         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5792       return SDValue();
5793
5794     SDValue NewLd = SDValue();
5795
5796     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5797       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5798                           LDBase->getPointerInfo(),
5799                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5800                           LDBase->isInvariant(), 0);
5801     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5802                         LDBase->getPointerInfo(),
5803                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5804                         LDBase->isInvariant(), LDBase->getAlignment());
5805
5806     if (LDBase->hasAnyUseOfValue(1)) {
5807       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5808                                      SDValue(LDBase, 1),
5809                                      SDValue(NewLd.getNode(), 1));
5810       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5811       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5812                              SDValue(NewLd.getNode(), 1));
5813     }
5814
5815     return NewLd;
5816   }
5817   if (NumElems == 4 && LastLoadedElt == 1 &&
5818       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5819     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5820     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5821     SDValue ResNode =
5822         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5823                                 LDBase->getPointerInfo(),
5824                                 LDBase->getAlignment(),
5825                                 false/*isVolatile*/, true/*ReadMem*/,
5826                                 false/*WriteMem*/);
5827
5828     // Make sure the newly-created LOAD is in the same position as LDBase in
5829     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5830     // update uses of LDBase's output chain to use the TokenFactor.
5831     if (LDBase->hasAnyUseOfValue(1)) {
5832       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5833                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5834       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5835       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5836                              SDValue(ResNode.getNode(), 1));
5837     }
5838
5839     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5840   }
5841   return SDValue();
5842 }
5843
5844 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5845 /// to generate a splat value for the following cases:
5846 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5847 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5848 /// a scalar load, or a constant.
5849 /// The VBROADCAST node is returned when a pattern is found,
5850 /// or SDValue() otherwise.
5851 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5852                                     SelectionDAG &DAG) {
5853   if (!Subtarget->hasFp256())
5854     return SDValue();
5855
5856   MVT VT = Op.getSimpleValueType();
5857   SDLoc dl(Op);
5858
5859   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5860          "Unsupported vector type for broadcast.");
5861
5862   SDValue Ld;
5863   bool ConstSplatVal;
5864
5865   switch (Op.getOpcode()) {
5866     default:
5867       // Unknown pattern found.
5868       return SDValue();
5869
5870     case ISD::BUILD_VECTOR: {
5871       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5872       BitVector UndefElements;
5873       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5874
5875       // We need a splat of a single value to use broadcast, and it doesn't
5876       // make any sense if the value is only in one element of the vector.
5877       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5878         return SDValue();
5879
5880       Ld = Splat;
5881       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5882                        Ld.getOpcode() == ISD::ConstantFP);
5883
5884       // Make sure that all of the users of a non-constant load are from the
5885       // BUILD_VECTOR node.
5886       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5887         return SDValue();
5888       break;
5889     }
5890
5891     case ISD::VECTOR_SHUFFLE: {
5892       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5893
5894       // Shuffles must have a splat mask where the first element is
5895       // broadcasted.
5896       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5897         return SDValue();
5898
5899       SDValue Sc = Op.getOperand(0);
5900       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5901           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5902
5903         if (!Subtarget->hasInt256())
5904           return SDValue();
5905
5906         // Use the register form of the broadcast instruction available on AVX2.
5907         if (VT.getSizeInBits() >= 256)
5908           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5909         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5910       }
5911
5912       Ld = Sc.getOperand(0);
5913       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5914                        Ld.getOpcode() == ISD::ConstantFP);
5915
5916       // The scalar_to_vector node and the suspected
5917       // load node must have exactly one user.
5918       // Constants may have multiple users.
5919
5920       // AVX-512 has register version of the broadcast
5921       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5922         Ld.getValueType().getSizeInBits() >= 32;
5923       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5924           !hasRegVer))
5925         return SDValue();
5926       break;
5927     }
5928   }
5929
5930   bool IsGE256 = (VT.getSizeInBits() >= 256);
5931
5932   // Handle the broadcasting a single constant scalar from the constant pool
5933   // into a vector. On Sandybridge it is still better to load a constant vector
5934   // from the constant pool and not to broadcast it from a scalar.
5935   if (ConstSplatVal && Subtarget->hasInt256()) {
5936     EVT CVT = Ld.getValueType();
5937     assert(!CVT.isVector() && "Must not broadcast a vector type");
5938     unsigned ScalarSize = CVT.getSizeInBits();
5939
5940     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5941       const Constant *C = nullptr;
5942       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5943         C = CI->getConstantIntValue();
5944       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5945         C = CF->getConstantFPValue();
5946
5947       assert(C && "Invalid constant type");
5948
5949       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5950       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5951       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5952       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5953                        MachinePointerInfo::getConstantPool(),
5954                        false, false, false, Alignment);
5955
5956       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5957     }
5958   }
5959
5960   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5961   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5962
5963   // Handle AVX2 in-register broadcasts.
5964   if (!IsLoad && Subtarget->hasInt256() &&
5965       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5966     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5967
5968   // The scalar source must be a normal load.
5969   if (!IsLoad)
5970     return SDValue();
5971
5972   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5973     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5974
5975   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5976   // double since there is no vbroadcastsd xmm
5977   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5978     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5979       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5980   }
5981
5982   // Unsupported broadcast.
5983   return SDValue();
5984 }
5985
5986 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5987 /// underlying vector and index.
5988 ///
5989 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5990 /// index.
5991 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5992                                          SDValue ExtIdx) {
5993   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5994   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5995     return Idx;
5996
5997   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5998   // lowered this:
5999   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6000   // to:
6001   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6002   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6003   //                           undef)
6004   //                       Constant<0>)
6005   // In this case the vector is the extract_subvector expression and the index
6006   // is 2, as specified by the shuffle.
6007   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6008   SDValue ShuffleVec = SVOp->getOperand(0);
6009   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6010   assert(ShuffleVecVT.getVectorElementType() ==
6011          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6012
6013   int ShuffleIdx = SVOp->getMaskElt(Idx);
6014   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6015     ExtractedFromVec = ShuffleVec;
6016     return ShuffleIdx;
6017   }
6018   return Idx;
6019 }
6020
6021 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6022   MVT VT = Op.getSimpleValueType();
6023
6024   // Skip if insert_vec_elt is not supported.
6025   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6026   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6027     return SDValue();
6028
6029   SDLoc DL(Op);
6030   unsigned NumElems = Op.getNumOperands();
6031
6032   SDValue VecIn1;
6033   SDValue VecIn2;
6034   SmallVector<unsigned, 4> InsertIndices;
6035   SmallVector<int, 8> Mask(NumElems, -1);
6036
6037   for (unsigned i = 0; i != NumElems; ++i) {
6038     unsigned Opc = Op.getOperand(i).getOpcode();
6039
6040     if (Opc == ISD::UNDEF)
6041       continue;
6042
6043     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6044       // Quit if more than 1 elements need inserting.
6045       if (InsertIndices.size() > 1)
6046         return SDValue();
6047
6048       InsertIndices.push_back(i);
6049       continue;
6050     }
6051
6052     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6053     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6054     // Quit if non-constant index.
6055     if (!isa<ConstantSDNode>(ExtIdx))
6056       return SDValue();
6057     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6058
6059     // Quit if extracted from vector of different type.
6060     if (ExtractedFromVec.getValueType() != VT)
6061       return SDValue();
6062
6063     if (!VecIn1.getNode())
6064       VecIn1 = ExtractedFromVec;
6065     else if (VecIn1 != ExtractedFromVec) {
6066       if (!VecIn2.getNode())
6067         VecIn2 = ExtractedFromVec;
6068       else if (VecIn2 != ExtractedFromVec)
6069         // Quit if more than 2 vectors to shuffle
6070         return SDValue();
6071     }
6072
6073     if (ExtractedFromVec == VecIn1)
6074       Mask[i] = Idx;
6075     else if (ExtractedFromVec == VecIn2)
6076       Mask[i] = Idx + NumElems;
6077   }
6078
6079   if (!VecIn1.getNode())
6080     return SDValue();
6081
6082   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6083   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6084   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6085     unsigned Idx = InsertIndices[i];
6086     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6087                      DAG.getIntPtrConstant(Idx));
6088   }
6089
6090   return NV;
6091 }
6092
6093 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6094 SDValue
6095 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6096
6097   MVT VT = Op.getSimpleValueType();
6098   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6099          "Unexpected type in LowerBUILD_VECTORvXi1!");
6100
6101   SDLoc dl(Op);
6102   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6103     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6104     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6105     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6106   }
6107
6108   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6109     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6110     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6111     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6112   }
6113
6114   bool AllContants = true;
6115   uint64_t Immediate = 0;
6116   int NonConstIdx = -1;
6117   bool IsSplat = true;
6118   unsigned NumNonConsts = 0;
6119   unsigned NumConsts = 0;
6120   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6121     SDValue In = Op.getOperand(idx);
6122     if (In.getOpcode() == ISD::UNDEF)
6123       continue;
6124     if (!isa<ConstantSDNode>(In)) {
6125       AllContants = false;
6126       NonConstIdx = idx;
6127       NumNonConsts++;
6128     }
6129     else {
6130       NumConsts++;
6131       if (cast<ConstantSDNode>(In)->getZExtValue())
6132       Immediate |= (1ULL << idx);
6133     }
6134     if (In != Op.getOperand(0))
6135       IsSplat = false;
6136   }
6137
6138   if (AllContants) {
6139     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6140       DAG.getConstant(Immediate, MVT::i16));
6141     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6142                        DAG.getIntPtrConstant(0));
6143   }
6144
6145   if (NumNonConsts == 1 && NonConstIdx != 0) {
6146     SDValue DstVec;
6147     if (NumConsts) {
6148       SDValue VecAsImm = DAG.getConstant(Immediate,
6149                                          MVT::getIntegerVT(VT.getSizeInBits()));
6150       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6151     }
6152     else 
6153       DstVec = DAG.getUNDEF(VT);
6154     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6155                        Op.getOperand(NonConstIdx),
6156                        DAG.getIntPtrConstant(NonConstIdx));
6157   }
6158   if (!IsSplat && (NonConstIdx != 0))
6159     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6160   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6161   SDValue Select;
6162   if (IsSplat)
6163     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6164                           DAG.getConstant(-1, SelectVT),
6165                           DAG.getConstant(0, SelectVT));
6166   else
6167     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6168                          DAG.getConstant((Immediate | 1), SelectVT),
6169                          DAG.getConstant(Immediate, SelectVT));
6170   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6171 }
6172
6173 /// \brief Return true if \p N implements a horizontal binop and return the
6174 /// operands for the horizontal binop into V0 and V1.
6175 /// 
6176 /// This is a helper function of PerformBUILD_VECTORCombine.
6177 /// This function checks that the build_vector \p N in input implements a
6178 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6179 /// operation to match.
6180 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6181 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6182 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6183 /// arithmetic sub.
6184 ///
6185 /// This function only analyzes elements of \p N whose indices are
6186 /// in range [BaseIdx, LastIdx).
6187 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6188                               SelectionDAG &DAG,
6189                               unsigned BaseIdx, unsigned LastIdx,
6190                               SDValue &V0, SDValue &V1) {
6191   EVT VT = N->getValueType(0);
6192
6193   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6194   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6195          "Invalid Vector in input!");
6196   
6197   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6198   bool CanFold = true;
6199   unsigned ExpectedVExtractIdx = BaseIdx;
6200   unsigned NumElts = LastIdx - BaseIdx;
6201   V0 = DAG.getUNDEF(VT);
6202   V1 = DAG.getUNDEF(VT);
6203
6204   // Check if N implements a horizontal binop.
6205   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6206     SDValue Op = N->getOperand(i + BaseIdx);
6207
6208     // Skip UNDEFs.
6209     if (Op->getOpcode() == ISD::UNDEF) {
6210       // Update the expected vector extract index.
6211       if (i * 2 == NumElts)
6212         ExpectedVExtractIdx = BaseIdx;
6213       ExpectedVExtractIdx += 2;
6214       continue;
6215     }
6216
6217     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6218
6219     if (!CanFold)
6220       break;
6221
6222     SDValue Op0 = Op.getOperand(0);
6223     SDValue Op1 = Op.getOperand(1);
6224
6225     // Try to match the following pattern:
6226     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6227     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6228         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6229         Op0.getOperand(0) == Op1.getOperand(0) &&
6230         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6231         isa<ConstantSDNode>(Op1.getOperand(1)));
6232     if (!CanFold)
6233       break;
6234
6235     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6236     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6237
6238     if (i * 2 < NumElts) {
6239       if (V0.getOpcode() == ISD::UNDEF)
6240         V0 = Op0.getOperand(0);
6241     } else {
6242       if (V1.getOpcode() == ISD::UNDEF)
6243         V1 = Op0.getOperand(0);
6244       if (i * 2 == NumElts)
6245         ExpectedVExtractIdx = BaseIdx;
6246     }
6247
6248     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6249     if (I0 == ExpectedVExtractIdx)
6250       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6251     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6252       // Try to match the following dag sequence:
6253       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6254       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6255     } else
6256       CanFold = false;
6257
6258     ExpectedVExtractIdx += 2;
6259   }
6260
6261   return CanFold;
6262 }
6263
6264 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6265 /// a concat_vector. 
6266 ///
6267 /// This is a helper function of PerformBUILD_VECTORCombine.
6268 /// This function expects two 256-bit vectors called V0 and V1.
6269 /// At first, each vector is split into two separate 128-bit vectors.
6270 /// Then, the resulting 128-bit vectors are used to implement two
6271 /// horizontal binary operations. 
6272 ///
6273 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6274 ///
6275 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6276 /// the two new horizontal binop.
6277 /// When Mode is set, the first horizontal binop dag node would take as input
6278 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6279 /// horizontal binop dag node would take as input the lower 128-bit of V1
6280 /// and the upper 128-bit of V1.
6281 ///   Example:
6282 ///     HADD V0_LO, V0_HI
6283 ///     HADD V1_LO, V1_HI
6284 ///
6285 /// Otherwise, the first horizontal binop dag node takes as input the lower
6286 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6287 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6288 ///   Example:
6289 ///     HADD V0_LO, V1_LO
6290 ///     HADD V0_HI, V1_HI
6291 ///
6292 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6293 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6294 /// the upper 128-bits of the result.
6295 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6296                                      SDLoc DL, SelectionDAG &DAG,
6297                                      unsigned X86Opcode, bool Mode,
6298                                      bool isUndefLO, bool isUndefHI) {
6299   EVT VT = V0.getValueType();
6300   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6301          "Invalid nodes in input!");
6302
6303   unsigned NumElts = VT.getVectorNumElements();
6304   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6305   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6306   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6307   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6308   EVT NewVT = V0_LO.getValueType();
6309
6310   SDValue LO = DAG.getUNDEF(NewVT);
6311   SDValue HI = DAG.getUNDEF(NewVT);
6312
6313   if (Mode) {
6314     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6315     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6316       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6317     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6318       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6319   } else {
6320     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6321     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6322                        V1_LO->getOpcode() != ISD::UNDEF))
6323       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6324
6325     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6326                        V1_HI->getOpcode() != ISD::UNDEF))
6327       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6328   }
6329
6330   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6331 }
6332
6333 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6334 /// sequence of 'vadd + vsub + blendi'.
6335 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6336                            const X86Subtarget *Subtarget) {
6337   SDLoc DL(BV);
6338   EVT VT = BV->getValueType(0);
6339   unsigned NumElts = VT.getVectorNumElements();
6340   SDValue InVec0 = DAG.getUNDEF(VT);
6341   SDValue InVec1 = DAG.getUNDEF(VT);
6342
6343   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6344           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6345
6346   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6348   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6349     return SDValue();
6350
6351   // Odd-numbered elements in the input build vector are obtained from
6352   // adding two integer/float elements.
6353   // Even-numbered elements in the input build vector are obtained from
6354   // subtracting two integer/float elements.
6355   unsigned ExpectedOpcode = ISD::FSUB;
6356   unsigned NextExpectedOpcode = ISD::FADD;
6357   bool AddFound = false;
6358   bool SubFound = false;
6359
6360   for (unsigned i = 0, e = NumElts; i != e; i++) {
6361     SDValue Op = BV->getOperand(i);
6362       
6363     // Skip 'undef' values.
6364     unsigned Opcode = Op.getOpcode();
6365     if (Opcode == ISD::UNDEF) {
6366       std::swap(ExpectedOpcode, NextExpectedOpcode);
6367       continue;
6368     }
6369       
6370     // Early exit if we found an unexpected opcode.
6371     if (Opcode != ExpectedOpcode)
6372       return SDValue();
6373
6374     SDValue Op0 = Op.getOperand(0);
6375     SDValue Op1 = Op.getOperand(1);
6376
6377     // Try to match the following pattern:
6378     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6379     // Early exit if we cannot match that sequence.
6380     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6381         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6382         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6383         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6384         Op0.getOperand(1) != Op1.getOperand(1))
6385       return SDValue();
6386
6387     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6388     if (I0 != i)
6389       return SDValue();
6390
6391     // We found a valid add/sub node. Update the information accordingly.
6392     if (i & 1)
6393       AddFound = true;
6394     else
6395       SubFound = true;
6396
6397     // Update InVec0 and InVec1.
6398     if (InVec0.getOpcode() == ISD::UNDEF)
6399       InVec0 = Op0.getOperand(0);
6400     if (InVec1.getOpcode() == ISD::UNDEF)
6401       InVec1 = Op1.getOperand(0);
6402
6403     // Make sure that operands in input to each add/sub node always
6404     // come from a same pair of vectors.
6405     if (InVec0 != Op0.getOperand(0)) {
6406       if (ExpectedOpcode == ISD::FSUB)
6407         return SDValue();
6408
6409       // FADD is commutable. Try to commute the operands
6410       // and then test again.
6411       std::swap(Op0, Op1);
6412       if (InVec0 != Op0.getOperand(0))
6413         return SDValue();
6414     }
6415
6416     if (InVec1 != Op1.getOperand(0))
6417       return SDValue();
6418
6419     // Update the pair of expected opcodes.
6420     std::swap(ExpectedOpcode, NextExpectedOpcode);
6421   }
6422
6423   // Don't try to fold this build_vector into a VSELECT if it has
6424   // too many UNDEF operands.
6425   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6426       InVec1.getOpcode() != ISD::UNDEF) {
6427     // Emit a sequence of vector add and sub followed by a VSELECT.
6428     // The new VSELECT will be lowered into a BLENDI.
6429     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6430     // and emit a single ADDSUB instruction.
6431     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6432     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6433
6434     // Construct the VSELECT mask.
6435     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6436     EVT SVT = MaskVT.getVectorElementType();
6437     unsigned SVTBits = SVT.getSizeInBits();
6438     SmallVector<SDValue, 8> Ops;
6439
6440     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6441       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6442                             APInt::getAllOnesValue(SVTBits);
6443       SDValue Constant = DAG.getConstant(Value, SVT);
6444       Ops.push_back(Constant);
6445     }
6446
6447     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6448     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6449   }
6450   
6451   return SDValue();
6452 }
6453
6454 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6455                                           const X86Subtarget *Subtarget) {
6456   SDLoc DL(N);
6457   EVT VT = N->getValueType(0);
6458   unsigned NumElts = VT.getVectorNumElements();
6459   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6460   SDValue InVec0, InVec1;
6461
6462   // Try to match an ADDSUB.
6463   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6464       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6465     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6466     if (Value.getNode())
6467       return Value;
6468   }
6469
6470   // Try to match horizontal ADD/SUB.
6471   unsigned NumUndefsLO = 0;
6472   unsigned NumUndefsHI = 0;
6473   unsigned Half = NumElts/2;
6474
6475   // Count the number of UNDEF operands in the build_vector in input.
6476   for (unsigned i = 0, e = Half; i != e; ++i)
6477     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6478       NumUndefsLO++;
6479
6480   for (unsigned i = Half, e = NumElts; i != e; ++i)
6481     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6482       NumUndefsHI++;
6483
6484   // Early exit if this is either a build_vector of all UNDEFs or all the
6485   // operands but one are UNDEF.
6486   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6487     return SDValue();
6488
6489   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6490     // Try to match an SSE3 float HADD/HSUB.
6491     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6492       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6493     
6494     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6495       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6496   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6497     // Try to match an SSSE3 integer HADD/HSUB.
6498     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6499       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6500     
6501     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6502       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6503   }
6504   
6505   if (!Subtarget->hasAVX())
6506     return SDValue();
6507
6508   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6509     // Try to match an AVX horizontal add/sub of packed single/double
6510     // precision floating point values from 256-bit vectors.
6511     SDValue InVec2, InVec3;
6512     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6513         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6514         ((InVec0.getOpcode() == ISD::UNDEF ||
6515           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6516         ((InVec1.getOpcode() == ISD::UNDEF ||
6517           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6518       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6519
6520     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6521         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6522         ((InVec0.getOpcode() == ISD::UNDEF ||
6523           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6524         ((InVec1.getOpcode() == ISD::UNDEF ||
6525           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6526       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6527   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6528     // Try to match an AVX2 horizontal add/sub of signed integers.
6529     SDValue InVec2, InVec3;
6530     unsigned X86Opcode;
6531     bool CanFold = true;
6532
6533     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6534         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6535         ((InVec0.getOpcode() == ISD::UNDEF ||
6536           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6537         ((InVec1.getOpcode() == ISD::UNDEF ||
6538           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6539       X86Opcode = X86ISD::HADD;
6540     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6541         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6542         ((InVec0.getOpcode() == ISD::UNDEF ||
6543           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6544         ((InVec1.getOpcode() == ISD::UNDEF ||
6545           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6546       X86Opcode = X86ISD::HSUB;
6547     else
6548       CanFold = false;
6549
6550     if (CanFold) {
6551       // Fold this build_vector into a single horizontal add/sub.
6552       // Do this only if the target has AVX2.
6553       if (Subtarget->hasAVX2())
6554         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6555  
6556       // Do not try to expand this build_vector into a pair of horizontal
6557       // add/sub if we can emit a pair of scalar add/sub.
6558       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6559         return SDValue();
6560
6561       // Convert this build_vector into a pair of horizontal binop followed by
6562       // a concat vector.
6563       bool isUndefLO = NumUndefsLO == Half;
6564       bool isUndefHI = NumUndefsHI == Half;
6565       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6566                                    isUndefLO, isUndefHI);
6567     }
6568   }
6569
6570   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6571        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6572     unsigned X86Opcode;
6573     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6574       X86Opcode = X86ISD::HADD;
6575     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6576       X86Opcode = X86ISD::HSUB;
6577     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6578       X86Opcode = X86ISD::FHADD;
6579     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6580       X86Opcode = X86ISD::FHSUB;
6581     else
6582       return SDValue();
6583
6584     // Don't try to expand this build_vector into a pair of horizontal add/sub
6585     // if we can simply emit a pair of scalar add/sub.
6586     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6587       return SDValue();
6588
6589     // Convert this build_vector into two horizontal add/sub followed by
6590     // a concat vector.
6591     bool isUndefLO = NumUndefsLO == Half;
6592     bool isUndefHI = NumUndefsHI == Half;
6593     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6594                                  isUndefLO, isUndefHI);
6595   }
6596
6597   return SDValue();
6598 }
6599
6600 SDValue
6601 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6602   SDLoc dl(Op);
6603
6604   MVT VT = Op.getSimpleValueType();
6605   MVT ExtVT = VT.getVectorElementType();
6606   unsigned NumElems = Op.getNumOperands();
6607
6608   // Generate vectors for predicate vectors.
6609   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6610     return LowerBUILD_VECTORvXi1(Op, DAG);
6611
6612   // Vectors containing all zeros can be matched by pxor and xorps later
6613   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6614     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6615     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6616     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6617       return Op;
6618
6619     return getZeroVector(VT, Subtarget, DAG, dl);
6620   }
6621
6622   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6623   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6624   // vpcmpeqd on 256-bit vectors.
6625   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6626     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6627       return Op;
6628
6629     if (!VT.is512BitVector())
6630       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6631   }
6632
6633   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6634   if (Broadcast.getNode())
6635     return Broadcast;
6636
6637   unsigned EVTBits = ExtVT.getSizeInBits();
6638
6639   unsigned NumZero  = 0;
6640   unsigned NumNonZero = 0;
6641   unsigned NonZeros = 0;
6642   bool IsAllConstants = true;
6643   SmallSet<SDValue, 8> Values;
6644   for (unsigned i = 0; i < NumElems; ++i) {
6645     SDValue Elt = Op.getOperand(i);
6646     if (Elt.getOpcode() == ISD::UNDEF)
6647       continue;
6648     Values.insert(Elt);
6649     if (Elt.getOpcode() != ISD::Constant &&
6650         Elt.getOpcode() != ISD::ConstantFP)
6651       IsAllConstants = false;
6652     if (X86::isZeroNode(Elt))
6653       NumZero++;
6654     else {
6655       NonZeros |= (1 << i);
6656       NumNonZero++;
6657     }
6658   }
6659
6660   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6661   if (NumNonZero == 0)
6662     return DAG.getUNDEF(VT);
6663
6664   // Special case for single non-zero, non-undef, element.
6665   if (NumNonZero == 1) {
6666     unsigned Idx = countTrailingZeros(NonZeros);
6667     SDValue Item = Op.getOperand(Idx);
6668
6669     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6670     // the value are obviously zero, truncate the value to i32 and do the
6671     // insertion that way.  Only do this if the value is non-constant or if the
6672     // value is a constant being inserted into element 0.  It is cheaper to do
6673     // a constant pool load than it is to do a movd + shuffle.
6674     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6675         (!IsAllConstants || Idx == 0)) {
6676       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6677         // Handle SSE only.
6678         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6679         EVT VecVT = MVT::v4i32;
6680         unsigned VecElts = 4;
6681
6682         // Truncate the value (which may itself be a constant) to i32, and
6683         // convert it to a vector with movd (S2V+shuffle to zero extend).
6684         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6685         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6686         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6687
6688         // Now we have our 32-bit value zero extended in the low element of
6689         // a vector.  If Idx != 0, swizzle it into place.
6690         if (Idx != 0) {
6691           SmallVector<int, 4> Mask;
6692           Mask.push_back(Idx);
6693           for (unsigned i = 1; i != VecElts; ++i)
6694             Mask.push_back(i);
6695           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6696                                       &Mask[0]);
6697         }
6698         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6699       }
6700     }
6701
6702     // If we have a constant or non-constant insertion into the low element of
6703     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6704     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6705     // depending on what the source datatype is.
6706     if (Idx == 0) {
6707       if (NumZero == 0)
6708         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6709
6710       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6711           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6712         if (VT.is256BitVector() || VT.is512BitVector()) {
6713           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6714           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6715                              Item, DAG.getIntPtrConstant(0));
6716         }
6717         assert(VT.is128BitVector() && "Expected an SSE value type!");
6718         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6719         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6720         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6721       }
6722
6723       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6724         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6725         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6726         if (VT.is256BitVector()) {
6727           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6728           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6729         } else {
6730           assert(VT.is128BitVector() && "Expected an SSE value type!");
6731           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6732         }
6733         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6734       }
6735     }
6736
6737     // Is it a vector logical left shift?
6738     if (NumElems == 2 && Idx == 1 &&
6739         X86::isZeroNode(Op.getOperand(0)) &&
6740         !X86::isZeroNode(Op.getOperand(1))) {
6741       unsigned NumBits = VT.getSizeInBits();
6742       return getVShift(true, VT,
6743                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6744                                    VT, Op.getOperand(1)),
6745                        NumBits/2, DAG, *this, dl);
6746     }
6747
6748     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6749       return SDValue();
6750
6751     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6752     // is a non-constant being inserted into an element other than the low one,
6753     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6754     // movd/movss) to move this into the low element, then shuffle it into
6755     // place.
6756     if (EVTBits == 32) {
6757       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6758
6759       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6760       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6761       SmallVector<int, 8> MaskVec;
6762       for (unsigned i = 0; i != NumElems; ++i)
6763         MaskVec.push_back(i == Idx ? 0 : 1);
6764       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6765     }
6766   }
6767
6768   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6769   if (Values.size() == 1) {
6770     if (EVTBits == 32) {
6771       // Instead of a shuffle like this:
6772       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6773       // Check if it's possible to issue this instead.
6774       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6775       unsigned Idx = countTrailingZeros(NonZeros);
6776       SDValue Item = Op.getOperand(Idx);
6777       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6778         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6779     }
6780     return SDValue();
6781   }
6782
6783   // A vector full of immediates; various special cases are already
6784   // handled, so this is best done with a single constant-pool load.
6785   if (IsAllConstants)
6786     return SDValue();
6787
6788   // For AVX-length vectors, build the individual 128-bit pieces and use
6789   // shuffles to put them in place.
6790   if (VT.is256BitVector() || VT.is512BitVector()) {
6791     SmallVector<SDValue, 64> V;
6792     for (unsigned i = 0; i != NumElems; ++i)
6793       V.push_back(Op.getOperand(i));
6794
6795     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6796
6797     // Build both the lower and upper subvector.
6798     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6799                                 makeArrayRef(&V[0], NumElems/2));
6800     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6801                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6802
6803     // Recreate the wider vector with the lower and upper part.
6804     if (VT.is256BitVector())
6805       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6806     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6807   }
6808
6809   // Let legalizer expand 2-wide build_vectors.
6810   if (EVTBits == 64) {
6811     if (NumNonZero == 1) {
6812       // One half is zero or undef.
6813       unsigned Idx = countTrailingZeros(NonZeros);
6814       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6815                                  Op.getOperand(Idx));
6816       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6817     }
6818     return SDValue();
6819   }
6820
6821   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6822   if (EVTBits == 8 && NumElems == 16) {
6823     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6824                                         Subtarget, *this);
6825     if (V.getNode()) return V;
6826   }
6827
6828   if (EVTBits == 16 && NumElems == 8) {
6829     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6830                                       Subtarget, *this);
6831     if (V.getNode()) return V;
6832   }
6833
6834   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6835   if (EVTBits == 32 && NumElems == 4) {
6836     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6837                                       NumZero, DAG, Subtarget, *this);
6838     if (V.getNode())
6839       return V;
6840   }
6841
6842   // If element VT is == 32 bits, turn it into a number of shuffles.
6843   SmallVector<SDValue, 8> V(NumElems);
6844   if (NumElems == 4 && NumZero > 0) {
6845     for (unsigned i = 0; i < 4; ++i) {
6846       bool isZero = !(NonZeros & (1 << i));
6847       if (isZero)
6848         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6849       else
6850         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6851     }
6852
6853     for (unsigned i = 0; i < 2; ++i) {
6854       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6855         default: break;
6856         case 0:
6857           V[i] = V[i*2];  // Must be a zero vector.
6858           break;
6859         case 1:
6860           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6861           break;
6862         case 2:
6863           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6864           break;
6865         case 3:
6866           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6867           break;
6868       }
6869     }
6870
6871     bool Reverse1 = (NonZeros & 0x3) == 2;
6872     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6873     int MaskVec[] = {
6874       Reverse1 ? 1 : 0,
6875       Reverse1 ? 0 : 1,
6876       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6877       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6878     };
6879     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6880   }
6881
6882   if (Values.size() > 1 && VT.is128BitVector()) {
6883     // Check for a build vector of consecutive loads.
6884     for (unsigned i = 0; i < NumElems; ++i)
6885       V[i] = Op.getOperand(i);
6886
6887     // Check for elements which are consecutive loads.
6888     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6889     if (LD.getNode())
6890       return LD;
6891
6892     // Check for a build vector from mostly shuffle plus few inserting.
6893     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6894     if (Sh.getNode())
6895       return Sh;
6896
6897     // For SSE 4.1, use insertps to put the high elements into the low element.
6898     if (getSubtarget()->hasSSE41()) {
6899       SDValue Result;
6900       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6901         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6902       else
6903         Result = DAG.getUNDEF(VT);
6904
6905       for (unsigned i = 1; i < NumElems; ++i) {
6906         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6907         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6908                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6909       }
6910       return Result;
6911     }
6912
6913     // Otherwise, expand into a number of unpckl*, start by extending each of
6914     // our (non-undef) elements to the full vector width with the element in the
6915     // bottom slot of the vector (which generates no code for SSE).
6916     for (unsigned i = 0; i < NumElems; ++i) {
6917       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6918         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6919       else
6920         V[i] = DAG.getUNDEF(VT);
6921     }
6922
6923     // Next, we iteratively mix elements, e.g. for v4f32:
6924     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6925     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6926     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6927     unsigned EltStride = NumElems >> 1;
6928     while (EltStride != 0) {
6929       for (unsigned i = 0; i < EltStride; ++i) {
6930         // If V[i+EltStride] is undef and this is the first round of mixing,
6931         // then it is safe to just drop this shuffle: V[i] is already in the
6932         // right place, the one element (since it's the first round) being
6933         // inserted as undef can be dropped.  This isn't safe for successive
6934         // rounds because they will permute elements within both vectors.
6935         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6936             EltStride == NumElems/2)
6937           continue;
6938
6939         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6940       }
6941       EltStride >>= 1;
6942     }
6943     return V[0];
6944   }
6945   return SDValue();
6946 }
6947
6948 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6949 // to create 256-bit vectors from two other 128-bit ones.
6950 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6951   SDLoc dl(Op);
6952   MVT ResVT = Op.getSimpleValueType();
6953
6954   assert((ResVT.is256BitVector() ||
6955           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6956
6957   SDValue V1 = Op.getOperand(0);
6958   SDValue V2 = Op.getOperand(1);
6959   unsigned NumElems = ResVT.getVectorNumElements();
6960   if(ResVT.is256BitVector())
6961     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6962
6963   if (Op.getNumOperands() == 4) {
6964     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6965                                 ResVT.getVectorNumElements()/2);
6966     SDValue V3 = Op.getOperand(2);
6967     SDValue V4 = Op.getOperand(3);
6968     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6969       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6970   }
6971   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6972 }
6973
6974 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6975   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6976   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6977          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6978           Op.getNumOperands() == 4)));
6979
6980   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6981   // from two other 128-bit ones.
6982
6983   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6984   return LowerAVXCONCAT_VECTORS(Op, DAG);
6985 }
6986
6987
6988 //===----------------------------------------------------------------------===//
6989 // Vector shuffle lowering
6990 //
6991 // This is an experimental code path for lowering vector shuffles on x86. It is
6992 // designed to handle arbitrary vector shuffles and blends, gracefully
6993 // degrading performance as necessary. It works hard to recognize idiomatic
6994 // shuffles and lower them to optimal instruction patterns without leaving
6995 // a framework that allows reasonably efficient handling of all vector shuffle
6996 // patterns.
6997 //===----------------------------------------------------------------------===//
6998
6999 /// \brief Tiny helper function to identify a no-op mask.
7000 ///
7001 /// This is a somewhat boring predicate function. It checks whether the mask
7002 /// array input, which is assumed to be a single-input shuffle mask of the kind
7003 /// used by the X86 shuffle instructions (not a fully general
7004 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7005 /// in-place shuffle are 'no-op's.
7006 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7007   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7008     if (Mask[i] != -1 && Mask[i] != i)
7009       return false;
7010   return true;
7011 }
7012
7013 /// \brief Helper function to classify a mask as a single-input mask.
7014 ///
7015 /// This isn't a generic single-input test because in the vector shuffle
7016 /// lowering we canonicalize single inputs to be the first input operand. This
7017 /// means we can more quickly test for a single input by only checking whether
7018 /// an input from the second operand exists. We also assume that the size of
7019 /// mask corresponds to the size of the input vectors which isn't true in the
7020 /// fully general case.
7021 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7022   for (int M : Mask)
7023     if (M >= (int)Mask.size())
7024       return false;
7025   return true;
7026 }
7027
7028 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7029 ///
7030 /// This helper function produces an 8-bit shuffle immediate corresponding to
7031 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7032 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7033 /// example.
7034 ///
7035 /// NB: We rely heavily on "undef" masks preserving the input lane.
7036 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7037                                           SelectionDAG &DAG) {
7038   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7039   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7040   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7041   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7042   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7043
7044   unsigned Imm = 0;
7045   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7046   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7047   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7048   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7049   return DAG.getConstant(Imm, MVT::i8);
7050 }
7051
7052 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7053 ///
7054 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7055 /// support for floating point shuffles but not integer shuffles. These
7056 /// instructions will incur a domain crossing penalty on some chips though so
7057 /// it is better to avoid lowering through this for integer vectors where
7058 /// possible.
7059 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7060                                        const X86Subtarget *Subtarget,
7061                                        SelectionDAG &DAG) {
7062   SDLoc DL(Op);
7063   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7064   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7065   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7066   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7067   ArrayRef<int> Mask = SVOp->getMask();
7068   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7069
7070   if (isSingleInputShuffleMask(Mask)) {
7071     // Straight shuffle of a single input vector. Simulate this by using the
7072     // single input as both of the "inputs" to this instruction..
7073     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7074     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7075                        DAG.getConstant(SHUFPDMask, MVT::i8));
7076   }
7077   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7078   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7079
7080   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7081   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7082                      DAG.getConstant(SHUFPDMask, MVT::i8));
7083 }
7084
7085 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7086 ///
7087 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7088 /// the integer unit to minimize domain crossing penalties. However, for blends
7089 /// it falls back to the floating point shuffle operation with appropriate bit
7090 /// casting.
7091 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7092                                        const X86Subtarget *Subtarget,
7093                                        SelectionDAG &DAG) {
7094   SDLoc DL(Op);
7095   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7096   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7097   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7098   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7099   ArrayRef<int> Mask = SVOp->getMask();
7100   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7101
7102   if (isSingleInputShuffleMask(Mask)) {
7103     // Straight shuffle of a single input vector. For everything from SSE2
7104     // onward this has a single fast instruction with no scary immediates.
7105     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7106     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7107     int WidenedMask[4] = {
7108         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7109         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7110     return DAG.getNode(
7111         ISD::BITCAST, DL, MVT::v2i64,
7112         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7113                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7114   }
7115
7116   // We implement this with SHUFPD which is pretty lame because it will likely
7117   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7118   // However, all the alternatives are still more cycles and newer chips don't
7119   // have this problem. It would be really nice if x86 had better shuffles here.
7120   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7121   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7122   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7123                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7124 }
7125
7126 /// \brief Lower 4-lane 32-bit floating point shuffles.
7127 ///
7128 /// Uses instructions exclusively from the floating point unit to minimize
7129 /// domain crossing penalties, as these are sufficient to implement all v4f32
7130 /// shuffles.
7131 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7132                                        const X86Subtarget *Subtarget,
7133                                        SelectionDAG &DAG) {
7134   SDLoc DL(Op);
7135   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7136   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7137   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7138   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7139   ArrayRef<int> Mask = SVOp->getMask();
7140   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7141
7142   SDValue LowV = V1, HighV = V2;
7143   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7144
7145   int NumV2Elements =
7146       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7147
7148   if (NumV2Elements == 0)
7149     // Straight shuffle of a single input vector. We pass the input vector to
7150     // both operands to simulate this with a SHUFPS.
7151     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7152                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7153
7154   if (NumV2Elements == 1) {
7155     int V2Index =
7156         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7157         Mask.begin();
7158     // Compute the index adjacent to V2Index and in the same half by toggling
7159     // the low bit.
7160     int V2AdjIndex = V2Index ^ 1;
7161
7162     if (Mask[V2AdjIndex] == -1) {
7163       // Handles all the cases where we have a single V2 element and an undef.
7164       // This will only ever happen in the high lanes because we commute the
7165       // vector otherwise.
7166       if (V2Index < 2)
7167         std::swap(LowV, HighV);
7168       NewMask[V2Index] -= 4;
7169     } else {
7170       // Handle the case where the V2 element ends up adjacent to a V1 element.
7171       // To make this work, blend them together as the first step.
7172       int V1Index = V2AdjIndex;
7173       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7174       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7175                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7176
7177       // Now proceed to reconstruct the final blend as we have the necessary
7178       // high or low half formed.
7179       if (V2Index < 2) {
7180         LowV = V2;
7181         HighV = V1;
7182       } else {
7183         HighV = V2;
7184       }
7185       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7186       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7187     }
7188   } else if (NumV2Elements == 2) {
7189     if (Mask[0] < 4 && Mask[1] < 4) {
7190       // Handle the easy case where we have V1 in the low lanes and V2 in the
7191       // high lanes. We never see this reversed because we sort the shuffle.
7192       NewMask[2] -= 4;
7193       NewMask[3] -= 4;
7194     } else {
7195       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7196       // trying to place elements directly, just blend them and set up the final
7197       // shuffle to place them.
7198
7199       // The first two blend mask elements are for V1, the second two are for
7200       // V2.
7201       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7202                           Mask[2] < 4 ? Mask[2] : Mask[3],
7203                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7204                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7205       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7206                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7207
7208       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7209       // a blend.
7210       LowV = HighV = V1;
7211       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7212       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7213       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7214       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7215     }
7216   }
7217   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7218                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7219 }
7220
7221 /// \brief Lower 4-lane i32 vector shuffles.
7222 ///
7223 /// We try to handle these with integer-domain shuffles where we can, but for
7224 /// blends we use the floating point domain blend instructions.
7225 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7226                                        const X86Subtarget *Subtarget,
7227                                        SelectionDAG &DAG) {
7228   SDLoc DL(Op);
7229   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7230   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7231   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7232   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7233   ArrayRef<int> Mask = SVOp->getMask();
7234   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7235
7236   if (isSingleInputShuffleMask(Mask))
7237     // Straight shuffle of a single input vector. For everything from SSE2
7238     // onward this has a single fast instruction with no scary immediates.
7239     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7240                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7241
7242   // We implement this with SHUFPS because it can blend from two vectors.
7243   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7244   // up the inputs, bypassing domain shift penalties that we would encur if we
7245   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7246   // relevant.
7247   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7248                      DAG.getVectorShuffle(
7249                          MVT::v4f32, DL,
7250                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7251                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7252 }
7253
7254 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7255 /// shuffle lowering, and the most complex part.
7256 ///
7257 /// The lowering strategy is to try to form pairs of input lanes which are
7258 /// targeted at the same half of the final vector, and then use a dword shuffle
7259 /// to place them onto the right half, and finally unpack the paired lanes into
7260 /// their final position.
7261 ///
7262 /// The exact breakdown of how to form these dword pairs and align them on the
7263 /// correct sides is really tricky. See the comments within the function for
7264 /// more of the details.
7265 static SDValue lowerV8I16SingleInputVectorShuffle(
7266     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7267     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7268   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7269   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7270   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7271
7272   SmallVector<int, 4> LoInputs;
7273   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7274                [](int M) { return M >= 0; });
7275   std::sort(LoInputs.begin(), LoInputs.end());
7276   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7277   SmallVector<int, 4> HiInputs;
7278   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7279                [](int M) { return M >= 0; });
7280   std::sort(HiInputs.begin(), HiInputs.end());
7281   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7282   int NumLToL =
7283       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7284   int NumHToL = LoInputs.size() - NumLToL;
7285   int NumLToH =
7286       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7287   int NumHToH = HiInputs.size() - NumLToH;
7288   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7289   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7290   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7291   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7292
7293   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7294   // such inputs we can swap two of the dwords across the half mark and end up
7295   // with <=2 inputs to each half in each half. Once there, we can fall through
7296   // to the generic code below. For example:
7297   //
7298   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7299   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7300   //
7301   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7302   // and 2-2.
7303   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7304                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7305     // Compute the index of dword with only one word among the three inputs in
7306     // a half by taking the sum of the half with three inputs and subtracting
7307     // the sum of the actual three inputs. The difference is the remaining
7308     // slot.
7309     int DWordA = (ThreeInputHalfSum -
7310                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7311                  2;
7312     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7313
7314     int PSHUFDMask[] = {0, 1, 2, 3};
7315     PSHUFDMask[DWordA] = DWordB;
7316     PSHUFDMask[DWordB] = DWordA;
7317     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7318                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7319                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7320                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7321
7322     // Adjust the mask to match the new locations of A and B.
7323     for (int &M : Mask)
7324       if (M != -1 && M/2 == DWordA)
7325         M = 2 * DWordB + M % 2;
7326       else if (M != -1 && M/2 == DWordB)
7327         M = 2 * DWordA + M % 2;
7328
7329     // Recurse back into this routine to re-compute state now that this isn't
7330     // a 3 and 1 problem.
7331     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7332                                 Mask);
7333   };
7334   if (NumLToL == 3 && NumHToL == 1)
7335     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7336   else if (NumLToL == 1 && NumHToL == 3)
7337     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7338   else if (NumLToH == 1 && NumHToH == 3)
7339     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7340   else if (NumLToH == 3 && NumHToH == 1)
7341     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7342
7343   // At this point there are at most two inputs to the low and high halves from
7344   // each half. That means the inputs can always be grouped into dwords and
7345   // those dwords can then be moved to the correct half with a dword shuffle.
7346   // We use at most one low and one high word shuffle to collect these paired
7347   // inputs into dwords, and finally a dword shuffle to place them.
7348   int PSHUFLMask[4] = {-1, -1, -1, -1};
7349   int PSHUFHMask[4] = {-1, -1, -1, -1};
7350   int PSHUFDMask[4] = {-1, -1, -1, -1};
7351
7352   // First fix the masks for all the inputs that are staying in their
7353   // original halves. This will then dictate the targets of the cross-half
7354   // shuffles.
7355   auto fixInPlaceInputs = [&PSHUFDMask](
7356       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7357       MutableArrayRef<int> HalfMask, int HalfOffset) {
7358     if (InPlaceInputs.empty())
7359       return;
7360     if (InPlaceInputs.size() == 1) {
7361       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7362           InPlaceInputs[0] - HalfOffset;
7363       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7364       return;
7365     }
7366
7367     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7368     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7369         InPlaceInputs[0] - HalfOffset;
7370     // Put the second input next to the first so that they are packed into
7371     // a dword. We find the adjacent index by toggling the low bit.
7372     int AdjIndex = InPlaceInputs[0] ^ 1;
7373     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7374     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7375     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7376   };
7377   if (!HToLInputs.empty())
7378     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7379   if (!LToHInputs.empty())
7380     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7381
7382   // Now gather the cross-half inputs and place them into a free dword of
7383   // their target half.
7384   // FIXME: This operation could almost certainly be simplified dramatically to
7385   // look more like the 3-1 fixing operation.
7386   auto moveInputsToRightHalf = [&PSHUFDMask](
7387       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7388       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7389       int SourceOffset, int DestOffset) {
7390     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7391       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7392     };
7393     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7394                                                int Word) {
7395       int LowWord = Word & ~1;
7396       int HighWord = Word | 1;
7397       return isWordClobbered(SourceHalfMask, LowWord) ||
7398              isWordClobbered(SourceHalfMask, HighWord);
7399     };
7400
7401     if (IncomingInputs.empty())
7402       return;
7403
7404     if (ExistingInputs.empty()) {
7405       // Map any dwords with inputs from them into the right half.
7406       for (int Input : IncomingInputs) {
7407         // If the source half mask maps over the inputs, turn those into
7408         // swaps and use the swapped lane.
7409         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7410           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7411             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7412                 Input - SourceOffset;
7413             // We have to swap the uses in our half mask in one sweep.
7414             for (int &M : HalfMask)
7415               if (M == SourceHalfMask[Input - SourceOffset])
7416                 M = Input;
7417               else if (M == Input)
7418                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7419           } else {
7420             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7421                        Input - SourceOffset &&
7422                    "Previous placement doesn't match!");
7423           }
7424           // Note that this correctly re-maps both when we do a swap and when
7425           // we observe the other side of the swap above. We rely on that to
7426           // avoid swapping the members of the input list directly.
7427           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7428         }
7429
7430         // Map the input's dword into the correct half.
7431         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7432           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7433         else
7434           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7435                      Input / 2 &&
7436                  "Previous placement doesn't match!");
7437       }
7438
7439       // And just directly shift any other-half mask elements to be same-half
7440       // as we will have mirrored the dword containing the element into the
7441       // same position within that half.
7442       for (int &M : HalfMask)
7443         if (M >= SourceOffset && M < SourceOffset + 4) {
7444           M = M - SourceOffset + DestOffset;
7445           assert(M >= 0 && "This should never wrap below zero!");
7446         }
7447       return;
7448     }
7449
7450     // Ensure we have the input in a viable dword of its current half. This
7451     // is particularly tricky because the original position may be clobbered
7452     // by inputs being moved and *staying* in that half.
7453     if (IncomingInputs.size() == 1) {
7454       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7455         int InputFixed = std::find(std::begin(SourceHalfMask),
7456                                    std::end(SourceHalfMask), -1) -
7457                          std::begin(SourceHalfMask) + SourceOffset;
7458         SourceHalfMask[InputFixed - SourceOffset] =
7459             IncomingInputs[0] - SourceOffset;
7460         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7461                      InputFixed);
7462         IncomingInputs[0] = InputFixed;
7463       }
7464     } else if (IncomingInputs.size() == 2) {
7465       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7466           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7467         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7468         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7469                "Not all dwords can be clobbered!");
7470         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7471         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7472         for (int &M : HalfMask)
7473           if (M == IncomingInputs[0])
7474             M = SourceDWordBase + SourceOffset;
7475           else if (M == IncomingInputs[1])
7476             M = SourceDWordBase + 1 + SourceOffset;
7477         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7478         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7479       }
7480     } else {
7481       llvm_unreachable("Unhandled input size!");
7482     }
7483
7484     // Now hoist the DWord down to the right half.
7485     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7486     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7487     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7488     for (int Input : IncomingInputs)
7489       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7490                    FreeDWord * 2 + Input % 2);
7491   };
7492   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7493                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7494   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7495                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7496
7497   // Now enact all the shuffles we've computed to move the inputs into their
7498   // target half.
7499   if (!isNoopShuffleMask(PSHUFLMask))
7500     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7501                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7502   if (!isNoopShuffleMask(PSHUFHMask))
7503     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7504                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7505   if (!isNoopShuffleMask(PSHUFDMask))
7506     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7507                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7508                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7509                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7510
7511   // At this point, each half should contain all its inputs, and we can then
7512   // just shuffle them into their final position.
7513   assert(std::count_if(LoMask.begin(), LoMask.end(),
7514                        [](int M) { return M >= 4; }) == 0 &&
7515          "Failed to lift all the high half inputs to the low mask!");
7516   assert(std::count_if(HiMask.begin(), HiMask.end(),
7517                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7518          "Failed to lift all the low half inputs to the high mask!");
7519
7520   // Do a half shuffle for the low mask.
7521   if (!isNoopShuffleMask(LoMask))
7522     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7523                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7524
7525   // Do a half shuffle with the high mask after shifting its values down.
7526   for (int &M : HiMask)
7527     if (M >= 0)
7528       M -= 4;
7529   if (!isNoopShuffleMask(HiMask))
7530     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7531                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7532
7533   return V;
7534 }
7535
7536 /// \brief Detect whether the mask pattern should be lowered through
7537 /// interleaving.
7538 ///
7539 /// This essentially tests whether viewing the mask as an interleaving of two
7540 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7541 /// lowering it through interleaving is a significantly better strategy.
7542 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7543   int NumEvenInputs[2] = {0, 0};
7544   int NumOddInputs[2] = {0, 0};
7545   int NumLoInputs[2] = {0, 0};
7546   int NumHiInputs[2] = {0, 0};
7547   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7548     if (Mask[i] < 0)
7549       continue;
7550
7551     int InputIdx = Mask[i] >= Size;
7552
7553     if (i < Size / 2)
7554       ++NumLoInputs[InputIdx];
7555     else
7556       ++NumHiInputs[InputIdx];
7557
7558     if ((i % 2) == 0)
7559       ++NumEvenInputs[InputIdx];
7560     else
7561       ++NumOddInputs[InputIdx];
7562   }
7563
7564   // The minimum number of cross-input results for both the interleaved and
7565   // split cases. If interleaving results in fewer cross-input results, return
7566   // true.
7567   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7568                                     NumEvenInputs[0] + NumOddInputs[1]);
7569   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7570                               NumLoInputs[0] + NumHiInputs[1]);
7571   return InterleavedCrosses < SplitCrosses;
7572 }
7573
7574 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7575 ///
7576 /// This strategy only works when the inputs from each vector fit into a single
7577 /// half of that vector, and generally there are not so many inputs as to leave
7578 /// the in-place shuffles required highly constrained (and thus expensive). It
7579 /// shifts all the inputs into a single side of both input vectors and then
7580 /// uses an unpack to interleave these inputs in a single vector. At that
7581 /// point, we will fall back on the generic single input shuffle lowering.
7582 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7583                                                  SDValue V2,
7584                                                  MutableArrayRef<int> Mask,
7585                                                  const X86Subtarget *Subtarget,
7586                                                  SelectionDAG &DAG) {
7587   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7588   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7589   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7590   for (int i = 0; i < 8; ++i)
7591     if (Mask[i] >= 0 && Mask[i] < 4)
7592       LoV1Inputs.push_back(i);
7593     else if (Mask[i] >= 4 && Mask[i] < 8)
7594       HiV1Inputs.push_back(i);
7595     else if (Mask[i] >= 8 && Mask[i] < 12)
7596       LoV2Inputs.push_back(i);
7597     else if (Mask[i] >= 12)
7598       HiV2Inputs.push_back(i);
7599
7600   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7601   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7602   (void)NumV1Inputs;
7603   (void)NumV2Inputs;
7604   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7605   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7606   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7607
7608   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7609                      HiV1Inputs.size() + HiV2Inputs.size();
7610
7611   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7612                               ArrayRef<int> HiInputs, bool MoveToLo,
7613                               int MaskOffset) {
7614     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7615     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7616     if (BadInputs.empty())
7617       return V;
7618
7619     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7620     int MoveOffset = MoveToLo ? 0 : 4;
7621
7622     if (GoodInputs.empty()) {
7623       for (int BadInput : BadInputs) {
7624         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7625         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7626       }
7627     } else {
7628       if (GoodInputs.size() == 2) {
7629         // If the low inputs are spread across two dwords, pack them into
7630         // a single dword.
7631         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7632             Mask[GoodInputs[0]] - MaskOffset;
7633         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7634             Mask[GoodInputs[1]] - MaskOffset;
7635         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7636         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7637       } else {
7638         // Otherwise pin the low inputs.
7639         for (int GoodInput : GoodInputs)
7640           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7641       }
7642
7643       int MoveMaskIdx =
7644           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7645           std::begin(MoveMask);
7646       assert(MoveMaskIdx >= MoveOffset && "Established above");
7647
7648       if (BadInputs.size() == 2) {
7649         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7650         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7651         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7652             Mask[BadInputs[0]] - MaskOffset;
7653         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7654             Mask[BadInputs[1]] - MaskOffset;
7655         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7656         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7657       } else {
7658         assert(BadInputs.size() == 1 && "All sizes handled");
7659         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7660         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7661       }
7662     }
7663
7664     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7665                                 MoveMask);
7666   };
7667   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7668                         /*MaskOffset*/ 0);
7669   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7670                         /*MaskOffset*/ 8);
7671
7672   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7673   // cross-half traffic in the final shuffle.
7674
7675   // Munge the mask to be a single-input mask after the unpack merges the
7676   // results.
7677   for (int &M : Mask)
7678     if (M != -1)
7679       M = 2 * (M % 4) + (M / 8);
7680
7681   return DAG.getVectorShuffle(
7682       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7683                                   DL, MVT::v8i16, V1, V2),
7684       DAG.getUNDEF(MVT::v8i16), Mask);
7685 }
7686
7687 /// \brief Generic lowering of 8-lane i16 shuffles.
7688 ///
7689 /// This handles both single-input shuffles and combined shuffle/blends with
7690 /// two inputs. The single input shuffles are immediately delegated to
7691 /// a dedicated lowering routine.
7692 ///
7693 /// The blends are lowered in one of three fundamental ways. If there are few
7694 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7695 /// of the input is significantly cheaper when lowered as an interleaving of
7696 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7697 /// halves of the inputs separately (making them have relatively few inputs)
7698 /// and then concatenate them.
7699 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7700                                        const X86Subtarget *Subtarget,
7701                                        SelectionDAG &DAG) {
7702   SDLoc DL(Op);
7703   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7704   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7705   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7706   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7707   ArrayRef<int> OrigMask = SVOp->getMask();
7708   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7709                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7710   MutableArrayRef<int> Mask(MaskStorage);
7711
7712   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7713
7714   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7715   auto isV2 = [](int M) { return M >= 8; };
7716
7717   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7718   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7719
7720   if (NumV2Inputs == 0)
7721     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7722
7723   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7724                             "to be V1-input shuffles.");
7725
7726   if (NumV1Inputs + NumV2Inputs <= 4)
7727     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7728
7729   // Check whether an interleaving lowering is likely to be more efficient.
7730   // This isn't perfect but it is a strong heuristic that tends to work well on
7731   // the kinds of shuffles that show up in practice.
7732   //
7733   // FIXME: Handle 1x, 2x, and 4x interleaving.
7734   if (shouldLowerAsInterleaving(Mask)) {
7735     // FIXME: Figure out whether we should pack these into the low or high
7736     // halves.
7737
7738     int EMask[8], OMask[8];
7739     for (int i = 0; i < 4; ++i) {
7740       EMask[i] = Mask[2*i];
7741       OMask[i] = Mask[2*i + 1];
7742       EMask[i + 4] = -1;
7743       OMask[i + 4] = -1;
7744     }
7745
7746     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7747     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7748
7749     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7750   }
7751
7752   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7753   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7754
7755   for (int i = 0; i < 4; ++i) {
7756     LoBlendMask[i] = Mask[i];
7757     HiBlendMask[i] = Mask[i + 4];
7758   }
7759
7760   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7761   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7762   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7763   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7764
7765   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7766                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7767 }
7768
7769 /// \brief Generic lowering of v16i8 shuffles.
7770 ///
7771 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7772 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7773 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7774 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7775 /// back together.
7776 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7777                                        const X86Subtarget *Subtarget,
7778                                        SelectionDAG &DAG) {
7779   SDLoc DL(Op);
7780   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7781   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7782   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7783   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7784   ArrayRef<int> OrigMask = SVOp->getMask();
7785   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7786   int MaskStorage[16] = {
7787       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7788       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7789       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7790       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7791   MutableArrayRef<int> Mask(MaskStorage);
7792   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7793   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7794
7795   // For single-input shuffles, there are some nicer lowering tricks we can use.
7796   if (isSingleInputShuffleMask(Mask)) {
7797     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7798     // Notably, this handles splat and partial-splat shuffles more efficiently.
7799     // However, it only makes sense if the pre-duplication shuffle simplifies
7800     // things significantly. Currently, this means we need to be able to
7801     // express the pre-duplication shuffle as an i16 shuffle.
7802     //
7803     // FIXME: We should check for other patterns which can be widened into an
7804     // i16 shuffle as well.
7805     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7806       for (int i = 0; i < 16; i += 2) {
7807         if (Mask[i] != Mask[i + 1])
7808           return false;
7809       }
7810       return true;
7811     };
7812     auto tryToWidenViaDuplication = [&]() -> SDValue {
7813       if (!canWidenViaDuplication(Mask))
7814         return SDValue();
7815       SmallVector<int, 4> LoInputs;
7816       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7817                    [](int M) { return M >= 0 && M < 8; });
7818       std::sort(LoInputs.begin(), LoInputs.end());
7819       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7820                      LoInputs.end());
7821       SmallVector<int, 4> HiInputs;
7822       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7823                    [](int M) { return M >= 8; });
7824       std::sort(HiInputs.begin(), HiInputs.end());
7825       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7826                      HiInputs.end());
7827
7828       bool TargetLo = LoInputs.size() >= HiInputs.size();
7829       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7830       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7831
7832       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7833       SmallDenseMap<int, int, 8> LaneMap;
7834       for (int I : InPlaceInputs) {
7835         PreDupI16Shuffle[I/2] = I/2;
7836         LaneMap[I] = I;
7837       }
7838       int j = TargetLo ? 0 : 4, je = j + 4;
7839       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7840         // Check if j is already a shuffle of this input. This happens when
7841         // there are two adjacent bytes after we move the low one.
7842         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7843           // If we haven't yet mapped the input, search for a slot into which
7844           // we can map it.
7845           while (j < je && PreDupI16Shuffle[j] != -1)
7846             ++j;
7847
7848           if (j == je)
7849             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7850             return SDValue();
7851
7852           // Map this input with the i16 shuffle.
7853           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7854         }
7855
7856         // Update the lane map based on the mapping we ended up with.
7857         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7858       }
7859       V1 = DAG.getNode(
7860           ISD::BITCAST, DL, MVT::v16i8,
7861           DAG.getVectorShuffle(MVT::v8i16, DL,
7862                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7863                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7864
7865       // Unpack the bytes to form the i16s that will be shuffled into place.
7866       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7867                        MVT::v16i8, V1, V1);
7868
7869       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7870       for (int i = 0; i < 16; i += 2) {
7871         if (Mask[i] != -1)
7872           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7873         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7874       }
7875       return DAG.getNode(
7876           ISD::BITCAST, DL, MVT::v16i8,
7877           DAG.getVectorShuffle(MVT::v8i16, DL,
7878                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7879                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7880     };
7881     if (SDValue V = tryToWidenViaDuplication())
7882       return V;
7883   }
7884
7885   // Check whether an interleaving lowering is likely to be more efficient.
7886   // This isn't perfect but it is a strong heuristic that tends to work well on
7887   // the kinds of shuffles that show up in practice.
7888   //
7889   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7890   if (shouldLowerAsInterleaving(Mask)) {
7891     // FIXME: Figure out whether we should pack these into the low or high
7892     // halves.
7893
7894     int EMask[16], OMask[16];
7895     for (int i = 0; i < 8; ++i) {
7896       EMask[i] = Mask[2*i];
7897       OMask[i] = Mask[2*i + 1];
7898       EMask[i + 8] = -1;
7899       OMask[i + 8] = -1;
7900     }
7901
7902     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7903     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7904
7905     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7906   }
7907
7908   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
7909   // with PSHUFB. It is important to do this before we attempt to generate any
7910   // blends but after all of the single-input lowerings. If the single input
7911   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
7912   // want to preserve that and we can DAG combine any longer sequences into
7913   // a PSHUFB in the end. But once we start blending from multiple inputs,
7914   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
7915   // and there are *very* few patterns that would actually be faster than the
7916   // PSHUFB approach because of its ability to zero lanes.
7917   //
7918   // FIXME: The only exceptions to the above are blends which are exact
7919   // interleavings with direct instructions supporting them. We currently don't
7920   // handle those well here.
7921   if (Subtarget->hasSSSE3()) {
7922     SDValue V1Mask[16];
7923     SDValue V2Mask[16];
7924     for (int i = 0; i < 16; ++i)
7925       if (Mask[i] == -1) {
7926         V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
7927       } else {
7928         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
7929         V2Mask[i] =
7930             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
7931       }
7932     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
7933                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
7934     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
7935                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
7936     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
7937   }
7938
7939   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7940   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7941   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7942   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7943
7944   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7945                             MutableArrayRef<int> V1HalfBlendMask,
7946                             MutableArrayRef<int> V2HalfBlendMask) {
7947     for (int i = 0; i < 8; ++i)
7948       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7949         V1HalfBlendMask[i] = HalfMask[i];
7950         HalfMask[i] = i;
7951       } else if (HalfMask[i] >= 16) {
7952         V2HalfBlendMask[i] = HalfMask[i] - 16;
7953         HalfMask[i] = i + 8;
7954       }
7955   };
7956   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7957   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7958
7959   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7960
7961   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
7962                              MutableArrayRef<int> HiBlendMask) {
7963     SDValue V1, V2;
7964     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
7965     // them out and avoid using UNPCK{L,H} to extract the elements of V as
7966     // i16s.
7967     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
7968                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
7969         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
7970                      [](int M) { return M >= 0 && M % 2 == 1; })) {
7971       // Use a mask to drop the high bytes.
7972       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
7973       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
7974                        DAG.getConstant(0x00FF, MVT::v8i16));
7975
7976       // This will be a single vector shuffle instead of a blend so nuke V2.
7977       V2 = DAG.getUNDEF(MVT::v8i16);
7978
7979       // Squash the masks to point directly into V1.
7980       for (int &M : LoBlendMask)
7981         if (M >= 0)
7982           M /= 2;
7983       for (int &M : HiBlendMask)
7984         if (M >= 0)
7985           M /= 2;
7986     } else {
7987       // Otherwise just unpack the low half of V into V1 and the high half into
7988       // V2 so that we can blend them as i16s.
7989       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7990                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
7991       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7992                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
7993     }
7994
7995     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7996     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7997     return std::make_pair(BlendedLo, BlendedHi);
7998   };
7999   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8000   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8001   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8002
8003   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8004   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8005
8006   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8007 }
8008
8009 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8010 ///
8011 /// This routine breaks down the specific type of 128-bit shuffle and
8012 /// dispatches to the lowering routines accordingly.
8013 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8014                                         MVT VT, const X86Subtarget *Subtarget,
8015                                         SelectionDAG &DAG) {
8016   switch (VT.SimpleTy) {
8017   case MVT::v2i64:
8018     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8019   case MVT::v2f64:
8020     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8021   case MVT::v4i32:
8022     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8023   case MVT::v4f32:
8024     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8025   case MVT::v8i16:
8026     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8027   case MVT::v16i8:
8028     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8029
8030   default:
8031     llvm_unreachable("Unimplemented!");
8032   }
8033 }
8034
8035 /// \brief Tiny helper function to test whether adjacent masks are sequential.
8036 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
8037   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8038     if (Mask[i] + 1 != Mask[i+1])
8039       return false;
8040
8041   return true;
8042 }
8043
8044 /// \brief Top-level lowering for x86 vector shuffles.
8045 ///
8046 /// This handles decomposition, canonicalization, and lowering of all x86
8047 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8048 /// above in helper routines. The canonicalization attempts to widen shuffles
8049 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8050 /// s.t. only one of the two inputs needs to be tested, etc.
8051 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8052                                   SelectionDAG &DAG) {
8053   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8054   ArrayRef<int> Mask = SVOp->getMask();
8055   SDValue V1 = Op.getOperand(0);
8056   SDValue V2 = Op.getOperand(1);
8057   MVT VT = Op.getSimpleValueType();
8058   int NumElements = VT.getVectorNumElements();
8059   SDLoc dl(Op);
8060
8061   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8062
8063   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8064   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8065   if (V1IsUndef && V2IsUndef)
8066     return DAG.getUNDEF(VT);
8067
8068   // When we create a shuffle node we put the UNDEF node to second operand,
8069   // but in some cases the first operand may be transformed to UNDEF.
8070   // In this case we should just commute the node.
8071   if (V1IsUndef)
8072     return DAG.getCommutedVectorShuffle(*SVOp);
8073
8074   // Check for non-undef masks pointing at an undef vector and make the masks
8075   // undef as well. This makes it easier to match the shuffle based solely on
8076   // the mask.
8077   if (V2IsUndef)
8078     for (int M : Mask)
8079       if (M >= NumElements) {
8080         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8081         for (int &M : NewMask)
8082           if (M >= NumElements)
8083             M = -1;
8084         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8085       }
8086
8087   // For integer vector shuffles, try to collapse them into a shuffle of fewer
8088   // lanes but wider integers. We cap this to not form integers larger than i64
8089   // but it might be interesting to form i128 integers to handle flipping the
8090   // low and high halves of AVX 256-bit vectors.
8091   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8092       areAdjacentMasksSequential(Mask)) {
8093     SmallVector<int, 8> NewMask;
8094     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8095       NewMask.push_back(Mask[i] / 2);
8096     MVT NewVT =
8097         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8098                          VT.getVectorNumElements() / 2);
8099     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8100     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8101     return DAG.getNode(ISD::BITCAST, dl, VT,
8102                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8103   }
8104
8105   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8106   for (int M : SVOp->getMask())
8107     if (M < 0)
8108       ++NumUndefElements;
8109     else if (M < NumElements)
8110       ++NumV1Elements;
8111     else
8112       ++NumV2Elements;
8113
8114   // Commute the shuffle as needed such that more elements come from V1 than
8115   // V2. This allows us to match the shuffle pattern strictly on how many
8116   // elements come from V1 without handling the symmetric cases.
8117   if (NumV2Elements > NumV1Elements)
8118     return DAG.getCommutedVectorShuffle(*SVOp);
8119
8120   // When the number of V1 and V2 elements are the same, try to minimize the
8121   // number of uses of V2 in the low half of the vector.
8122   if (NumV1Elements == NumV2Elements) {
8123     int LowV1Elements = 0, LowV2Elements = 0;
8124     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8125       if (M >= NumElements)
8126         ++LowV2Elements;
8127       else if (M >= 0)
8128         ++LowV1Elements;
8129     if (LowV2Elements > LowV1Elements)
8130       return DAG.getCommutedVectorShuffle(*SVOp);
8131   }
8132
8133   // For each vector width, delegate to a specialized lowering routine.
8134   if (VT.getSizeInBits() == 128)
8135     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8136
8137   llvm_unreachable("Unimplemented!");
8138 }
8139
8140
8141 //===----------------------------------------------------------------------===//
8142 // Legacy vector shuffle lowering
8143 //
8144 // This code is the legacy code handling vector shuffles until the above
8145 // replaces its functionality and performance.
8146 //===----------------------------------------------------------------------===//
8147
8148 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8149                         bool hasInt256, unsigned *MaskOut = nullptr) {
8150   MVT EltVT = VT.getVectorElementType();
8151
8152   // There is no blend with immediate in AVX-512.
8153   if (VT.is512BitVector())
8154     return false;
8155
8156   if (!hasSSE41 || EltVT == MVT::i8)
8157     return false;
8158   if (!hasInt256 && VT == MVT::v16i16)
8159     return false;
8160
8161   unsigned MaskValue = 0;
8162   unsigned NumElems = VT.getVectorNumElements();
8163   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8164   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8165   unsigned NumElemsInLane = NumElems / NumLanes;
8166
8167   // Blend for v16i16 should be symetric for the both lanes.
8168   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8169
8170     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8171     int EltIdx = MaskVals[i];
8172
8173     if ((EltIdx < 0 || EltIdx == (int)i) &&
8174         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8175       continue;
8176
8177     if (((unsigned)EltIdx == (i + NumElems)) &&
8178         (SndLaneEltIdx < 0 ||
8179          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8180       MaskValue |= (1 << i);
8181     else
8182       return false;
8183   }
8184
8185   if (MaskOut)
8186     *MaskOut = MaskValue;
8187   return true;
8188 }
8189
8190 // Try to lower a shuffle node into a simple blend instruction.
8191 // This function assumes isBlendMask returns true for this
8192 // SuffleVectorSDNode
8193 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8194                                           unsigned MaskValue,
8195                                           const X86Subtarget *Subtarget,
8196                                           SelectionDAG &DAG) {
8197   MVT VT = SVOp->getSimpleValueType(0);
8198   MVT EltVT = VT.getVectorElementType();
8199   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8200                      Subtarget->hasInt256() && "Trying to lower a "
8201                                                "VECTOR_SHUFFLE to a Blend but "
8202                                                "with the wrong mask"));
8203   SDValue V1 = SVOp->getOperand(0);
8204   SDValue V2 = SVOp->getOperand(1);
8205   SDLoc dl(SVOp);
8206   unsigned NumElems = VT.getVectorNumElements();
8207
8208   // Convert i32 vectors to floating point if it is not AVX2.
8209   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8210   MVT BlendVT = VT;
8211   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8212     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8213                                NumElems);
8214     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8215     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8216   }
8217
8218   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8219                             DAG.getConstant(MaskValue, MVT::i32));
8220   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8221 }
8222
8223 /// In vector type \p VT, return true if the element at index \p InputIdx
8224 /// falls on a different 128-bit lane than \p OutputIdx.
8225 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8226                                      unsigned OutputIdx) {
8227   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8228   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8229 }
8230
8231 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8232 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8233 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8234 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8235 /// zero.
8236 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8237                          SelectionDAG &DAG) {
8238   MVT VT = V1.getSimpleValueType();
8239   assert(VT.is128BitVector() || VT.is256BitVector());
8240
8241   MVT EltVT = VT.getVectorElementType();
8242   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8243   unsigned NumElts = VT.getVectorNumElements();
8244
8245   SmallVector<SDValue, 32> PshufbMask;
8246   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8247     int InputIdx = MaskVals[OutputIdx];
8248     unsigned InputByteIdx;
8249
8250     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8251       InputByteIdx = 0x80;
8252     else {
8253       // Cross lane is not allowed.
8254       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8255         return SDValue();
8256       InputByteIdx = InputIdx * EltSizeInBytes;
8257       // Index is an byte offset within the 128-bit lane.
8258       InputByteIdx &= 0xf;
8259     }
8260
8261     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8262       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8263       if (InputByteIdx != 0x80)
8264         ++InputByteIdx;
8265     }
8266   }
8267
8268   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8269   if (ShufVT != VT)
8270     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8271   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8272                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8273 }
8274
8275 // v8i16 shuffles - Prefer shuffles in the following order:
8276 // 1. [all]   pshuflw, pshufhw, optional move
8277 // 2. [ssse3] 1 x pshufb
8278 // 3. [ssse3] 2 x pshufb + 1 x por
8279 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8280 static SDValue
8281 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8282                          SelectionDAG &DAG) {
8283   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8284   SDValue V1 = SVOp->getOperand(0);
8285   SDValue V2 = SVOp->getOperand(1);
8286   SDLoc dl(SVOp);
8287   SmallVector<int, 8> MaskVals;
8288
8289   // Determine if more than 1 of the words in each of the low and high quadwords
8290   // of the result come from the same quadword of one of the two inputs.  Undef
8291   // mask values count as coming from any quadword, for better codegen.
8292   //
8293   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8294   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8295   unsigned LoQuad[] = { 0, 0, 0, 0 };
8296   unsigned HiQuad[] = { 0, 0, 0, 0 };
8297   // Indices of quads used.
8298   std::bitset<4> InputQuads;
8299   for (unsigned i = 0; i < 8; ++i) {
8300     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8301     int EltIdx = SVOp->getMaskElt(i);
8302     MaskVals.push_back(EltIdx);
8303     if (EltIdx < 0) {
8304       ++Quad[0];
8305       ++Quad[1];
8306       ++Quad[2];
8307       ++Quad[3];
8308       continue;
8309     }
8310     ++Quad[EltIdx / 4];
8311     InputQuads.set(EltIdx / 4);
8312   }
8313
8314   int BestLoQuad = -1;
8315   unsigned MaxQuad = 1;
8316   for (unsigned i = 0; i < 4; ++i) {
8317     if (LoQuad[i] > MaxQuad) {
8318       BestLoQuad = i;
8319       MaxQuad = LoQuad[i];
8320     }
8321   }
8322
8323   int BestHiQuad = -1;
8324   MaxQuad = 1;
8325   for (unsigned i = 0; i < 4; ++i) {
8326     if (HiQuad[i] > MaxQuad) {
8327       BestHiQuad = i;
8328       MaxQuad = HiQuad[i];
8329     }
8330   }
8331
8332   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8333   // of the two input vectors, shuffle them into one input vector so only a
8334   // single pshufb instruction is necessary. If there are more than 2 input
8335   // quads, disable the next transformation since it does not help SSSE3.
8336   bool V1Used = InputQuads[0] || InputQuads[1];
8337   bool V2Used = InputQuads[2] || InputQuads[3];
8338   if (Subtarget->hasSSSE3()) {
8339     if (InputQuads.count() == 2 && V1Used && V2Used) {
8340       BestLoQuad = InputQuads[0] ? 0 : 1;
8341       BestHiQuad = InputQuads[2] ? 2 : 3;
8342     }
8343     if (InputQuads.count() > 2) {
8344       BestLoQuad = -1;
8345       BestHiQuad = -1;
8346     }
8347   }
8348
8349   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8350   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8351   // words from all 4 input quadwords.
8352   SDValue NewV;
8353   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8354     int MaskV[] = {
8355       BestLoQuad < 0 ? 0 : BestLoQuad,
8356       BestHiQuad < 0 ? 1 : BestHiQuad
8357     };
8358     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8359                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8360                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8361     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8362
8363     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8364     // source words for the shuffle, to aid later transformations.
8365     bool AllWordsInNewV = true;
8366     bool InOrder[2] = { true, true };
8367     for (unsigned i = 0; i != 8; ++i) {
8368       int idx = MaskVals[i];
8369       if (idx != (int)i)
8370         InOrder[i/4] = false;
8371       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8372         continue;
8373       AllWordsInNewV = false;
8374       break;
8375     }
8376
8377     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8378     if (AllWordsInNewV) {
8379       for (int i = 0; i != 8; ++i) {
8380         int idx = MaskVals[i];
8381         if (idx < 0)
8382           continue;
8383         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8384         if ((idx != i) && idx < 4)
8385           pshufhw = false;
8386         if ((idx != i) && idx > 3)
8387           pshuflw = false;
8388       }
8389       V1 = NewV;
8390       V2Used = false;
8391       BestLoQuad = 0;
8392       BestHiQuad = 1;
8393     }
8394
8395     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8396     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8397     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8398       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8399       unsigned TargetMask = 0;
8400       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8401                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8402       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8403       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8404                              getShufflePSHUFLWImmediate(SVOp);
8405       V1 = NewV.getOperand(0);
8406       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8407     }
8408   }
8409
8410   // Promote splats to a larger type which usually leads to more efficient code.
8411   // FIXME: Is this true if pshufb is available?
8412   if (SVOp->isSplat())
8413     return PromoteSplat(SVOp, DAG);
8414
8415   // If we have SSSE3, and all words of the result are from 1 input vector,
8416   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8417   // is present, fall back to case 4.
8418   if (Subtarget->hasSSSE3()) {
8419     SmallVector<SDValue,16> pshufbMask;
8420
8421     // If we have elements from both input vectors, set the high bit of the
8422     // shuffle mask element to zero out elements that come from V2 in the V1
8423     // mask, and elements that come from V1 in the V2 mask, so that the two
8424     // results can be OR'd together.
8425     bool TwoInputs = V1Used && V2Used;
8426     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8427     if (!TwoInputs)
8428       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8429
8430     // Calculate the shuffle mask for the second input, shuffle it, and
8431     // OR it with the first shuffled input.
8432     CommuteVectorShuffleMask(MaskVals, 8);
8433     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8434     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8435     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8436   }
8437
8438   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8439   // and update MaskVals with new element order.
8440   std::bitset<8> InOrder;
8441   if (BestLoQuad >= 0) {
8442     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8443     for (int i = 0; i != 4; ++i) {
8444       int idx = MaskVals[i];
8445       if (idx < 0) {
8446         InOrder.set(i);
8447       } else if ((idx / 4) == BestLoQuad) {
8448         MaskV[i] = idx & 3;
8449         InOrder.set(i);
8450       }
8451     }
8452     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8453                                 &MaskV[0]);
8454
8455     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8456       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8457       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8458                                   NewV.getOperand(0),
8459                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8460     }
8461   }
8462
8463   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8464   // and update MaskVals with the new element order.
8465   if (BestHiQuad >= 0) {
8466     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8467     for (unsigned i = 4; i != 8; ++i) {
8468       int idx = MaskVals[i];
8469       if (idx < 0) {
8470         InOrder.set(i);
8471       } else if ((idx / 4) == BestHiQuad) {
8472         MaskV[i] = (idx & 3) + 4;
8473         InOrder.set(i);
8474       }
8475     }
8476     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8477                                 &MaskV[0]);
8478
8479     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8480       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8481       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8482                                   NewV.getOperand(0),
8483                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8484     }
8485   }
8486
8487   // In case BestHi & BestLo were both -1, which means each quadword has a word
8488   // from each of the four input quadwords, calculate the InOrder bitvector now
8489   // before falling through to the insert/extract cleanup.
8490   if (BestLoQuad == -1 && BestHiQuad == -1) {
8491     NewV = V1;
8492     for (int i = 0; i != 8; ++i)
8493       if (MaskVals[i] < 0 || MaskVals[i] == i)
8494         InOrder.set(i);
8495   }
8496
8497   // The other elements are put in the right place using pextrw and pinsrw.
8498   for (unsigned i = 0; i != 8; ++i) {
8499     if (InOrder[i])
8500       continue;
8501     int EltIdx = MaskVals[i];
8502     if (EltIdx < 0)
8503       continue;
8504     SDValue ExtOp = (EltIdx < 8) ?
8505       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8506                   DAG.getIntPtrConstant(EltIdx)) :
8507       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8508                   DAG.getIntPtrConstant(EltIdx - 8));
8509     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8510                        DAG.getIntPtrConstant(i));
8511   }
8512   return NewV;
8513 }
8514
8515 /// \brief v16i16 shuffles
8516 ///
8517 /// FIXME: We only support generation of a single pshufb currently.  We can
8518 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8519 /// well (e.g 2 x pshufb + 1 x por).
8520 static SDValue
8521 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8522   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8523   SDValue V1 = SVOp->getOperand(0);
8524   SDValue V2 = SVOp->getOperand(1);
8525   SDLoc dl(SVOp);
8526
8527   if (V2.getOpcode() != ISD::UNDEF)
8528     return SDValue();
8529
8530   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8531   return getPSHUFB(MaskVals, V1, dl, DAG);
8532 }
8533
8534 // v16i8 shuffles - Prefer shuffles in the following order:
8535 // 1. [ssse3] 1 x pshufb
8536 // 2. [ssse3] 2 x pshufb + 1 x por
8537 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8538 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8539                                         const X86Subtarget* Subtarget,
8540                                         SelectionDAG &DAG) {
8541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8542   SDValue V1 = SVOp->getOperand(0);
8543   SDValue V2 = SVOp->getOperand(1);
8544   SDLoc dl(SVOp);
8545   ArrayRef<int> MaskVals = SVOp->getMask();
8546
8547   // Promote splats to a larger type which usually leads to more efficient code.
8548   // FIXME: Is this true if pshufb is available?
8549   if (SVOp->isSplat())
8550     return PromoteSplat(SVOp, DAG);
8551
8552   // If we have SSSE3, case 1 is generated when all result bytes come from
8553   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8554   // present, fall back to case 3.
8555
8556   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8557   if (Subtarget->hasSSSE3()) {
8558     SmallVector<SDValue,16> pshufbMask;
8559
8560     // If all result elements are from one input vector, then only translate
8561     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8562     //
8563     // Otherwise, we have elements from both input vectors, and must zero out
8564     // elements that come from V2 in the first mask, and V1 in the second mask
8565     // so that we can OR them together.
8566     for (unsigned i = 0; i != 16; ++i) {
8567       int EltIdx = MaskVals[i];
8568       if (EltIdx < 0 || EltIdx >= 16)
8569         EltIdx = 0x80;
8570       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8571     }
8572     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8573                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8574                                  MVT::v16i8, pshufbMask));
8575
8576     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8577     // the 2nd operand if it's undefined or zero.
8578     if (V2.getOpcode() == ISD::UNDEF ||
8579         ISD::isBuildVectorAllZeros(V2.getNode()))
8580       return V1;
8581
8582     // Calculate the shuffle mask for the second input, shuffle it, and
8583     // OR it with the first shuffled input.
8584     pshufbMask.clear();
8585     for (unsigned i = 0; i != 16; ++i) {
8586       int EltIdx = MaskVals[i];
8587       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8588       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8589     }
8590     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8591                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8592                                  MVT::v16i8, pshufbMask));
8593     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8594   }
8595
8596   // No SSSE3 - Calculate in place words and then fix all out of place words
8597   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8598   // the 16 different words that comprise the two doublequadword input vectors.
8599   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8600   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8601   SDValue NewV = V1;
8602   for (int i = 0; i != 8; ++i) {
8603     int Elt0 = MaskVals[i*2];
8604     int Elt1 = MaskVals[i*2+1];
8605
8606     // This word of the result is all undef, skip it.
8607     if (Elt0 < 0 && Elt1 < 0)
8608       continue;
8609
8610     // This word of the result is already in the correct place, skip it.
8611     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8612       continue;
8613
8614     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8615     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8616     SDValue InsElt;
8617
8618     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8619     // using a single extract together, load it and store it.
8620     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8621       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8622                            DAG.getIntPtrConstant(Elt1 / 2));
8623       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8624                         DAG.getIntPtrConstant(i));
8625       continue;
8626     }
8627
8628     // If Elt1 is defined, extract it from the appropriate source.  If the
8629     // source byte is not also odd, shift the extracted word left 8 bits
8630     // otherwise clear the bottom 8 bits if we need to do an or.
8631     if (Elt1 >= 0) {
8632       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8633                            DAG.getIntPtrConstant(Elt1 / 2));
8634       if ((Elt1 & 1) == 0)
8635         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8636                              DAG.getConstant(8,
8637                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8638       else if (Elt0 >= 0)
8639         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8640                              DAG.getConstant(0xFF00, MVT::i16));
8641     }
8642     // If Elt0 is defined, extract it from the appropriate source.  If the
8643     // source byte is not also even, shift the extracted word right 8 bits. If
8644     // Elt1 was also defined, OR the extracted values together before
8645     // inserting them in the result.
8646     if (Elt0 >= 0) {
8647       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8648                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8649       if ((Elt0 & 1) != 0)
8650         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8651                               DAG.getConstant(8,
8652                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8653       else if (Elt1 >= 0)
8654         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8655                              DAG.getConstant(0x00FF, MVT::i16));
8656       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8657                          : InsElt0;
8658     }
8659     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8660                        DAG.getIntPtrConstant(i));
8661   }
8662   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8663 }
8664
8665 // v32i8 shuffles - Translate to VPSHUFB if possible.
8666 static
8667 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8668                                  const X86Subtarget *Subtarget,
8669                                  SelectionDAG &DAG) {
8670   MVT VT = SVOp->getSimpleValueType(0);
8671   SDValue V1 = SVOp->getOperand(0);
8672   SDValue V2 = SVOp->getOperand(1);
8673   SDLoc dl(SVOp);
8674   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8675
8676   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8677   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8678   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8679
8680   // VPSHUFB may be generated if
8681   // (1) one of input vector is undefined or zeroinitializer.
8682   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8683   // And (2) the mask indexes don't cross the 128-bit lane.
8684   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8685       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8686     return SDValue();
8687
8688   if (V1IsAllZero && !V2IsAllZero) {
8689     CommuteVectorShuffleMask(MaskVals, 32);
8690     V1 = V2;
8691   }
8692   return getPSHUFB(MaskVals, V1, dl, DAG);
8693 }
8694
8695 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8696 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8697 /// done when every pair / quad of shuffle mask elements point to elements in
8698 /// the right sequence. e.g.
8699 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8700 static
8701 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8702                                  SelectionDAG &DAG) {
8703   MVT VT = SVOp->getSimpleValueType(0);
8704   SDLoc dl(SVOp);
8705   unsigned NumElems = VT.getVectorNumElements();
8706   MVT NewVT;
8707   unsigned Scale;
8708   switch (VT.SimpleTy) {
8709   default: llvm_unreachable("Unexpected!");
8710   case MVT::v2i64:
8711   case MVT::v2f64:
8712            return SDValue(SVOp, 0);
8713   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8714   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8715   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8716   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8717   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8718   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8719   }
8720
8721   SmallVector<int, 8> MaskVec;
8722   for (unsigned i = 0; i != NumElems; i += Scale) {
8723     int StartIdx = -1;
8724     for (unsigned j = 0; j != Scale; ++j) {
8725       int EltIdx = SVOp->getMaskElt(i+j);
8726       if (EltIdx < 0)
8727         continue;
8728       if (StartIdx < 0)
8729         StartIdx = (EltIdx / Scale);
8730       if (EltIdx != (int)(StartIdx*Scale + j))
8731         return SDValue();
8732     }
8733     MaskVec.push_back(StartIdx);
8734   }
8735
8736   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8737   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8738   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8739 }
8740
8741 /// getVZextMovL - Return a zero-extending vector move low node.
8742 ///
8743 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8744                             SDValue SrcOp, SelectionDAG &DAG,
8745                             const X86Subtarget *Subtarget, SDLoc dl) {
8746   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8747     LoadSDNode *LD = nullptr;
8748     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8749       LD = dyn_cast<LoadSDNode>(SrcOp);
8750     if (!LD) {
8751       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8752       // instead.
8753       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8754       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8755           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8756           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8757           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8758         // PR2108
8759         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8760         return DAG.getNode(ISD::BITCAST, dl, VT,
8761                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8762                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8763                                                    OpVT,
8764                                                    SrcOp.getOperand(0)
8765                                                           .getOperand(0))));
8766       }
8767     }
8768   }
8769
8770   return DAG.getNode(ISD::BITCAST, dl, VT,
8771                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8772                                  DAG.getNode(ISD::BITCAST, dl,
8773                                              OpVT, SrcOp)));
8774 }
8775
8776 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8777 /// which could not be matched by any known target speficic shuffle
8778 static SDValue
8779 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8780
8781   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8782   if (NewOp.getNode())
8783     return NewOp;
8784
8785   MVT VT = SVOp->getSimpleValueType(0);
8786
8787   unsigned NumElems = VT.getVectorNumElements();
8788   unsigned NumLaneElems = NumElems / 2;
8789
8790   SDLoc dl(SVOp);
8791   MVT EltVT = VT.getVectorElementType();
8792   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8793   SDValue Output[2];
8794
8795   SmallVector<int, 16> Mask;
8796   for (unsigned l = 0; l < 2; ++l) {
8797     // Build a shuffle mask for the output, discovering on the fly which
8798     // input vectors to use as shuffle operands (recorded in InputUsed).
8799     // If building a suitable shuffle vector proves too hard, then bail
8800     // out with UseBuildVector set.
8801     bool UseBuildVector = false;
8802     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8803     unsigned LaneStart = l * NumLaneElems;
8804     for (unsigned i = 0; i != NumLaneElems; ++i) {
8805       // The mask element.  This indexes into the input.
8806       int Idx = SVOp->getMaskElt(i+LaneStart);
8807       if (Idx < 0) {
8808         // the mask element does not index into any input vector.
8809         Mask.push_back(-1);
8810         continue;
8811       }
8812
8813       // The input vector this mask element indexes into.
8814       int Input = Idx / NumLaneElems;
8815
8816       // Turn the index into an offset from the start of the input vector.
8817       Idx -= Input * NumLaneElems;
8818
8819       // Find or create a shuffle vector operand to hold this input.
8820       unsigned OpNo;
8821       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8822         if (InputUsed[OpNo] == Input)
8823           // This input vector is already an operand.
8824           break;
8825         if (InputUsed[OpNo] < 0) {
8826           // Create a new operand for this input vector.
8827           InputUsed[OpNo] = Input;
8828           break;
8829         }
8830       }
8831
8832       if (OpNo >= array_lengthof(InputUsed)) {
8833         // More than two input vectors used!  Give up on trying to create a
8834         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8835         UseBuildVector = true;
8836         break;
8837       }
8838
8839       // Add the mask index for the new shuffle vector.
8840       Mask.push_back(Idx + OpNo * NumLaneElems);
8841     }
8842
8843     if (UseBuildVector) {
8844       SmallVector<SDValue, 16> SVOps;
8845       for (unsigned i = 0; i != NumLaneElems; ++i) {
8846         // The mask element.  This indexes into the input.
8847         int Idx = SVOp->getMaskElt(i+LaneStart);
8848         if (Idx < 0) {
8849           SVOps.push_back(DAG.getUNDEF(EltVT));
8850           continue;
8851         }
8852
8853         // The input vector this mask element indexes into.
8854         int Input = Idx / NumElems;
8855
8856         // Turn the index into an offset from the start of the input vector.
8857         Idx -= Input * NumElems;
8858
8859         // Extract the vector element by hand.
8860         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8861                                     SVOp->getOperand(Input),
8862                                     DAG.getIntPtrConstant(Idx)));
8863       }
8864
8865       // Construct the output using a BUILD_VECTOR.
8866       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8867     } else if (InputUsed[0] < 0) {
8868       // No input vectors were used! The result is undefined.
8869       Output[l] = DAG.getUNDEF(NVT);
8870     } else {
8871       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8872                                         (InputUsed[0] % 2) * NumLaneElems,
8873                                         DAG, dl);
8874       // If only one input was used, use an undefined vector for the other.
8875       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8876         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8877                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8878       // At least one input vector was used. Create a new shuffle vector.
8879       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8880     }
8881
8882     Mask.clear();
8883   }
8884
8885   // Concatenate the result back
8886   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8887 }
8888
8889 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8890 /// 4 elements, and match them with several different shuffle types.
8891 static SDValue
8892 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8893   SDValue V1 = SVOp->getOperand(0);
8894   SDValue V2 = SVOp->getOperand(1);
8895   SDLoc dl(SVOp);
8896   MVT VT = SVOp->getSimpleValueType(0);
8897
8898   assert(VT.is128BitVector() && "Unsupported vector size");
8899
8900   std::pair<int, int> Locs[4];
8901   int Mask1[] = { -1, -1, -1, -1 };
8902   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8903
8904   unsigned NumHi = 0;
8905   unsigned NumLo = 0;
8906   for (unsigned i = 0; i != 4; ++i) {
8907     int Idx = PermMask[i];
8908     if (Idx < 0) {
8909       Locs[i] = std::make_pair(-1, -1);
8910     } else {
8911       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8912       if (Idx < 4) {
8913         Locs[i] = std::make_pair(0, NumLo);
8914         Mask1[NumLo] = Idx;
8915         NumLo++;
8916       } else {
8917         Locs[i] = std::make_pair(1, NumHi);
8918         if (2+NumHi < 4)
8919           Mask1[2+NumHi] = Idx;
8920         NumHi++;
8921       }
8922     }
8923   }
8924
8925   if (NumLo <= 2 && NumHi <= 2) {
8926     // If no more than two elements come from either vector. This can be
8927     // implemented with two shuffles. First shuffle gather the elements.
8928     // The second shuffle, which takes the first shuffle as both of its
8929     // vector operands, put the elements into the right order.
8930     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8931
8932     int Mask2[] = { -1, -1, -1, -1 };
8933
8934     for (unsigned i = 0; i != 4; ++i)
8935       if (Locs[i].first != -1) {
8936         unsigned Idx = (i < 2) ? 0 : 4;
8937         Idx += Locs[i].first * 2 + Locs[i].second;
8938         Mask2[i] = Idx;
8939       }
8940
8941     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8942   }
8943
8944   if (NumLo == 3 || NumHi == 3) {
8945     // Otherwise, we must have three elements from one vector, call it X, and
8946     // one element from the other, call it Y.  First, use a shufps to build an
8947     // intermediate vector with the one element from Y and the element from X
8948     // that will be in the same half in the final destination (the indexes don't
8949     // matter). Then, use a shufps to build the final vector, taking the half
8950     // containing the element from Y from the intermediate, and the other half
8951     // from X.
8952     if (NumHi == 3) {
8953       // Normalize it so the 3 elements come from V1.
8954       CommuteVectorShuffleMask(PermMask, 4);
8955       std::swap(V1, V2);
8956     }
8957
8958     // Find the element from V2.
8959     unsigned HiIndex;
8960     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8961       int Val = PermMask[HiIndex];
8962       if (Val < 0)
8963         continue;
8964       if (Val >= 4)
8965         break;
8966     }
8967
8968     Mask1[0] = PermMask[HiIndex];
8969     Mask1[1] = -1;
8970     Mask1[2] = PermMask[HiIndex^1];
8971     Mask1[3] = -1;
8972     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8973
8974     if (HiIndex >= 2) {
8975       Mask1[0] = PermMask[0];
8976       Mask1[1] = PermMask[1];
8977       Mask1[2] = HiIndex & 1 ? 6 : 4;
8978       Mask1[3] = HiIndex & 1 ? 4 : 6;
8979       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8980     }
8981
8982     Mask1[0] = HiIndex & 1 ? 2 : 0;
8983     Mask1[1] = HiIndex & 1 ? 0 : 2;
8984     Mask1[2] = PermMask[2];
8985     Mask1[3] = PermMask[3];
8986     if (Mask1[2] >= 0)
8987       Mask1[2] += 4;
8988     if (Mask1[3] >= 0)
8989       Mask1[3] += 4;
8990     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8991   }
8992
8993   // Break it into (shuffle shuffle_hi, shuffle_lo).
8994   int LoMask[] = { -1, -1, -1, -1 };
8995   int HiMask[] = { -1, -1, -1, -1 };
8996
8997   int *MaskPtr = LoMask;
8998   unsigned MaskIdx = 0;
8999   unsigned LoIdx = 0;
9000   unsigned HiIdx = 2;
9001   for (unsigned i = 0; i != 4; ++i) {
9002     if (i == 2) {
9003       MaskPtr = HiMask;
9004       MaskIdx = 1;
9005       LoIdx = 0;
9006       HiIdx = 2;
9007     }
9008     int Idx = PermMask[i];
9009     if (Idx < 0) {
9010       Locs[i] = std::make_pair(-1, -1);
9011     } else if (Idx < 4) {
9012       Locs[i] = std::make_pair(MaskIdx, LoIdx);
9013       MaskPtr[LoIdx] = Idx;
9014       LoIdx++;
9015     } else {
9016       Locs[i] = std::make_pair(MaskIdx, HiIdx);
9017       MaskPtr[HiIdx] = Idx;
9018       HiIdx++;
9019     }
9020   }
9021
9022   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9023   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9024   int MaskOps[] = { -1, -1, -1, -1 };
9025   for (unsigned i = 0; i != 4; ++i)
9026     if (Locs[i].first != -1)
9027       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9028   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9029 }
9030
9031 static bool MayFoldVectorLoad(SDValue V) {
9032   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9033     V = V.getOperand(0);
9034
9035   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9036     V = V.getOperand(0);
9037   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9038       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9039     // BUILD_VECTOR (load), undef
9040     V = V.getOperand(0);
9041
9042   return MayFoldLoad(V);
9043 }
9044
9045 static
9046 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9047   MVT VT = Op.getSimpleValueType();
9048
9049   // Canonizalize to v2f64.
9050   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9051   return DAG.getNode(ISD::BITCAST, dl, VT,
9052                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9053                                           V1, DAG));
9054 }
9055
9056 static
9057 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9058                         bool HasSSE2) {
9059   SDValue V1 = Op.getOperand(0);
9060   SDValue V2 = Op.getOperand(1);
9061   MVT VT = Op.getSimpleValueType();
9062
9063   assert(VT != MVT::v2i64 && "unsupported shuffle type");
9064
9065   if (HasSSE2 && VT == MVT::v2f64)
9066     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9067
9068   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9069   return DAG.getNode(ISD::BITCAST, dl, VT,
9070                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9071                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9072                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9073 }
9074
9075 static
9076 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9077   SDValue V1 = Op.getOperand(0);
9078   SDValue V2 = Op.getOperand(1);
9079   MVT VT = Op.getSimpleValueType();
9080
9081   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9082          "unsupported shuffle type");
9083
9084   if (V2.getOpcode() == ISD::UNDEF)
9085     V2 = V1;
9086
9087   // v4i32 or v4f32
9088   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9089 }
9090
9091 static
9092 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9093   SDValue V1 = Op.getOperand(0);
9094   SDValue V2 = Op.getOperand(1);
9095   MVT VT = Op.getSimpleValueType();
9096   unsigned NumElems = VT.getVectorNumElements();
9097
9098   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9099   // operand of these instructions is only memory, so check if there's a
9100   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9101   // same masks.
9102   bool CanFoldLoad = false;
9103
9104   // Trivial case, when V2 comes from a load.
9105   if (MayFoldVectorLoad(V2))
9106     CanFoldLoad = true;
9107
9108   // When V1 is a load, it can be folded later into a store in isel, example:
9109   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9110   //    turns into:
9111   //  (MOVLPSmr addr:$src1, VR128:$src2)
9112   // So, recognize this potential and also use MOVLPS or MOVLPD
9113   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9114     CanFoldLoad = true;
9115
9116   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9117   if (CanFoldLoad) {
9118     if (HasSSE2 && NumElems == 2)
9119       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9120
9121     if (NumElems == 4)
9122       // If we don't care about the second element, proceed to use movss.
9123       if (SVOp->getMaskElt(1) != -1)
9124         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9125   }
9126
9127   // movl and movlp will both match v2i64, but v2i64 is never matched by
9128   // movl earlier because we make it strict to avoid messing with the movlp load
9129   // folding logic (see the code above getMOVLP call). Match it here then,
9130   // this is horrible, but will stay like this until we move all shuffle
9131   // matching to x86 specific nodes. Note that for the 1st condition all
9132   // types are matched with movsd.
9133   if (HasSSE2) {
9134     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9135     // as to remove this logic from here, as much as possible
9136     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9137       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9138     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9139   }
9140
9141   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9142
9143   // Invert the operand order and use SHUFPS to match it.
9144   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9145                               getShuffleSHUFImmediate(SVOp), DAG);
9146 }
9147
9148 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9149                                          SelectionDAG &DAG) {
9150   SDLoc dl(Load);
9151   MVT VT = Load->getSimpleValueType(0);
9152   MVT EVT = VT.getVectorElementType();
9153   SDValue Addr = Load->getOperand(1);
9154   SDValue NewAddr = DAG.getNode(
9155       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9156       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9157
9158   SDValue NewLoad =
9159       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9160                   DAG.getMachineFunction().getMachineMemOperand(
9161                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9162   return NewLoad;
9163 }
9164
9165 // It is only safe to call this function if isINSERTPSMask is true for
9166 // this shufflevector mask.
9167 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9168                            SelectionDAG &DAG) {
9169   // Generate an insertps instruction when inserting an f32 from memory onto a
9170   // v4f32 or when copying a member from one v4f32 to another.
9171   // We also use it for transferring i32 from one register to another,
9172   // since it simply copies the same bits.
9173   // If we're transferring an i32 from memory to a specific element in a
9174   // register, we output a generic DAG that will match the PINSRD
9175   // instruction.
9176   MVT VT = SVOp->getSimpleValueType(0);
9177   MVT EVT = VT.getVectorElementType();
9178   SDValue V1 = SVOp->getOperand(0);
9179   SDValue V2 = SVOp->getOperand(1);
9180   auto Mask = SVOp->getMask();
9181   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9182          "unsupported vector type for insertps/pinsrd");
9183
9184   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9185   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9186   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9187
9188   SDValue From;
9189   SDValue To;
9190   unsigned DestIndex;
9191   if (FromV1 == 1) {
9192     From = V1;
9193     To = V2;
9194     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9195                 Mask.begin();
9196
9197     // If we have 1 element from each vector, we have to check if we're
9198     // changing V1's element's place. If so, we're done. Otherwise, we
9199     // should assume we're changing V2's element's place and behave
9200     // accordingly.
9201     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9202     assert(DestIndex <= INT32_MAX && "truncated destination index");
9203     if (FromV1 == FromV2 &&
9204         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9205       From = V2;
9206       To = V1;
9207       DestIndex =
9208           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9209     }
9210   } else {
9211     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9212            "More than one element from V1 and from V2, or no elements from one "
9213            "of the vectors. This case should not have returned true from "
9214            "isINSERTPSMask");
9215     From = V2;
9216     To = V1;
9217     DestIndex =
9218         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9219   }
9220
9221   // Get an index into the source vector in the range [0,4) (the mask is
9222   // in the range [0,8) because it can address V1 and V2)
9223   unsigned SrcIndex = Mask[DestIndex] % 4;
9224   if (MayFoldLoad(From)) {
9225     // Trivial case, when From comes from a load and is only used by the
9226     // shuffle. Make it use insertps from the vector that we need from that
9227     // load.
9228     SDValue NewLoad =
9229         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9230     if (!NewLoad.getNode())
9231       return SDValue();
9232
9233     if (EVT == MVT::f32) {
9234       // Create this as a scalar to vector to match the instruction pattern.
9235       SDValue LoadScalarToVector =
9236           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9237       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9238       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9239                          InsertpsMask);
9240     } else { // EVT == MVT::i32
9241       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9242       // instruction, to match the PINSRD instruction, which loads an i32 to a
9243       // certain vector element.
9244       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9245                          DAG.getConstant(DestIndex, MVT::i32));
9246     }
9247   }
9248
9249   // Vector-element-to-vector
9250   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9251   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9252 }
9253
9254 // Reduce a vector shuffle to zext.
9255 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9256                                     SelectionDAG &DAG) {
9257   // PMOVZX is only available from SSE41.
9258   if (!Subtarget->hasSSE41())
9259     return SDValue();
9260
9261   MVT VT = Op.getSimpleValueType();
9262
9263   // Only AVX2 support 256-bit vector integer extending.
9264   if (!Subtarget->hasInt256() && VT.is256BitVector())
9265     return SDValue();
9266
9267   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9268   SDLoc DL(Op);
9269   SDValue V1 = Op.getOperand(0);
9270   SDValue V2 = Op.getOperand(1);
9271   unsigned NumElems = VT.getVectorNumElements();
9272
9273   // Extending is an unary operation and the element type of the source vector
9274   // won't be equal to or larger than i64.
9275   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9276       VT.getVectorElementType() == MVT::i64)
9277     return SDValue();
9278
9279   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9280   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9281   while ((1U << Shift) < NumElems) {
9282     if (SVOp->getMaskElt(1U << Shift) == 1)
9283       break;
9284     Shift += 1;
9285     // The maximal ratio is 8, i.e. from i8 to i64.
9286     if (Shift > 3)
9287       return SDValue();
9288   }
9289
9290   // Check the shuffle mask.
9291   unsigned Mask = (1U << Shift) - 1;
9292   for (unsigned i = 0; i != NumElems; ++i) {
9293     int EltIdx = SVOp->getMaskElt(i);
9294     if ((i & Mask) != 0 && EltIdx != -1)
9295       return SDValue();
9296     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9297       return SDValue();
9298   }
9299
9300   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9301   MVT NeVT = MVT::getIntegerVT(NBits);
9302   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9303
9304   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9305     return SDValue();
9306
9307   // Simplify the operand as it's prepared to be fed into shuffle.
9308   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9309   if (V1.getOpcode() == ISD::BITCAST &&
9310       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9311       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9312       V1.getOperand(0).getOperand(0)
9313         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9314     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9315     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9316     ConstantSDNode *CIdx =
9317       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9318     // If it's foldable, i.e. normal load with single use, we will let code
9319     // selection to fold it. Otherwise, we will short the conversion sequence.
9320     if (CIdx && CIdx->getZExtValue() == 0 &&
9321         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9322       MVT FullVT = V.getSimpleValueType();
9323       MVT V1VT = V1.getSimpleValueType();
9324       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9325         // The "ext_vec_elt" node is wider than the result node.
9326         // In this case we should extract subvector from V.
9327         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9328         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9329         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9330                                         FullVT.getVectorNumElements()/Ratio);
9331         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9332                         DAG.getIntPtrConstant(0));
9333       }
9334       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9335     }
9336   }
9337
9338   return DAG.getNode(ISD::BITCAST, DL, VT,
9339                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9340 }
9341
9342 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9343                                       SelectionDAG &DAG) {
9344   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9345   MVT VT = Op.getSimpleValueType();
9346   SDLoc dl(Op);
9347   SDValue V1 = Op.getOperand(0);
9348   SDValue V2 = Op.getOperand(1);
9349
9350   if (isZeroShuffle(SVOp))
9351     return getZeroVector(VT, Subtarget, DAG, dl);
9352
9353   // Handle splat operations
9354   if (SVOp->isSplat()) {
9355     // Use vbroadcast whenever the splat comes from a foldable load
9356     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9357     if (Broadcast.getNode())
9358       return Broadcast;
9359   }
9360
9361   // Check integer expanding shuffles.
9362   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9363   if (NewOp.getNode())
9364     return NewOp;
9365
9366   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9367   // do it!
9368   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9369       VT == MVT::v32i8) {
9370     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9371     if (NewOp.getNode())
9372       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9373   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9374     // FIXME: Figure out a cleaner way to do this.
9375     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9376       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9377       if (NewOp.getNode()) {
9378         MVT NewVT = NewOp.getSimpleValueType();
9379         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9380                                NewVT, true, false))
9381           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9382                               dl);
9383       }
9384     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9385       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9386       if (NewOp.getNode()) {
9387         MVT NewVT = NewOp.getSimpleValueType();
9388         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9389           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9390                               dl);
9391       }
9392     }
9393   }
9394   return SDValue();
9395 }
9396
9397 SDValue
9398 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9399   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9400   SDValue V1 = Op.getOperand(0);
9401   SDValue V2 = Op.getOperand(1);
9402   MVT VT = Op.getSimpleValueType();
9403   SDLoc dl(Op);
9404   unsigned NumElems = VT.getVectorNumElements();
9405   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9406   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9407   bool V1IsSplat = false;
9408   bool V2IsSplat = false;
9409   bool HasSSE2 = Subtarget->hasSSE2();
9410   bool HasFp256    = Subtarget->hasFp256();
9411   bool HasInt256   = Subtarget->hasInt256();
9412   MachineFunction &MF = DAG.getMachineFunction();
9413   bool OptForSize = MF.getFunction()->getAttributes().
9414     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9415
9416   // Check if we should use the experimental vector shuffle lowering. If so,
9417   // delegate completely to that code path.
9418   if (ExperimentalVectorShuffleLowering)
9419     return lowerVectorShuffle(Op, Subtarget, DAG);
9420
9421   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9422
9423   if (V1IsUndef && V2IsUndef)
9424     return DAG.getUNDEF(VT);
9425
9426   // When we create a shuffle node we put the UNDEF node to second operand,
9427   // but in some cases the first operand may be transformed to UNDEF.
9428   // In this case we should just commute the node.
9429   if (V1IsUndef)
9430     return DAG.getCommutedVectorShuffle(*SVOp);
9431
9432   // Vector shuffle lowering takes 3 steps:
9433   //
9434   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9435   //    narrowing and commutation of operands should be handled.
9436   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9437   //    shuffle nodes.
9438   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9439   //    so the shuffle can be broken into other shuffles and the legalizer can
9440   //    try the lowering again.
9441   //
9442   // The general idea is that no vector_shuffle operation should be left to
9443   // be matched during isel, all of them must be converted to a target specific
9444   // node here.
9445
9446   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9447   // narrowing and commutation of operands should be handled. The actual code
9448   // doesn't include all of those, work in progress...
9449   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9450   if (NewOp.getNode())
9451     return NewOp;
9452
9453   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9454
9455   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9456   // unpckh_undef). Only use pshufd if speed is more important than size.
9457   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9458     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9459   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9460     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9461
9462   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9463       V2IsUndef && MayFoldVectorLoad(V1))
9464     return getMOVDDup(Op, dl, V1, DAG);
9465
9466   if (isMOVHLPS_v_undef_Mask(M, VT))
9467     return getMOVHighToLow(Op, dl, DAG);
9468
9469   // Use to match splats
9470   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9471       (VT == MVT::v2f64 || VT == MVT::v2i64))
9472     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9473
9474   if (isPSHUFDMask(M, VT)) {
9475     // The actual implementation will match the mask in the if above and then
9476     // during isel it can match several different instructions, not only pshufd
9477     // as its name says, sad but true, emulate the behavior for now...
9478     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9479       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9480
9481     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9482
9483     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9484       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9485
9486     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9487       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9488                                   DAG);
9489
9490     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9491                                 TargetMask, DAG);
9492   }
9493
9494   if (isPALIGNRMask(M, VT, Subtarget))
9495     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9496                                 getShufflePALIGNRImmediate(SVOp),
9497                                 DAG);
9498
9499   // Check if this can be converted into a logical shift.
9500   bool isLeft = false;
9501   unsigned ShAmt = 0;
9502   SDValue ShVal;
9503   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9504   if (isShift && ShVal.hasOneUse()) {
9505     // If the shifted value has multiple uses, it may be cheaper to use
9506     // v_set0 + movlhps or movhlps, etc.
9507     MVT EltVT = VT.getVectorElementType();
9508     ShAmt *= EltVT.getSizeInBits();
9509     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9510   }
9511
9512   if (isMOVLMask(M, VT)) {
9513     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9514       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9515     if (!isMOVLPMask(M, VT)) {
9516       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9517         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9518
9519       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9520         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9521     }
9522   }
9523
9524   // FIXME: fold these into legal mask.
9525   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9526     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9527
9528   if (isMOVHLPSMask(M, VT))
9529     return getMOVHighToLow(Op, dl, DAG);
9530
9531   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9532     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9533
9534   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9535     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9536
9537   if (isMOVLPMask(M, VT))
9538     return getMOVLP(Op, dl, DAG, HasSSE2);
9539
9540   if (ShouldXformToMOVHLPS(M, VT) ||
9541       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9542     return DAG.getCommutedVectorShuffle(*SVOp);
9543
9544   if (isShift) {
9545     // No better options. Use a vshldq / vsrldq.
9546     MVT EltVT = VT.getVectorElementType();
9547     ShAmt *= EltVT.getSizeInBits();
9548     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9549   }
9550
9551   bool Commuted = false;
9552   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9553   // 1,1,1,1 -> v8i16 though.
9554   BitVector UndefElements;
9555   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9556     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9557       V1IsSplat = true;
9558   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9559     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9560       V2IsSplat = true;
9561
9562   // Canonicalize the splat or undef, if present, to be on the RHS.
9563   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9564     CommuteVectorShuffleMask(M, NumElems);
9565     std::swap(V1, V2);
9566     std::swap(V1IsSplat, V2IsSplat);
9567     Commuted = true;
9568   }
9569
9570   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9571     // Shuffling low element of v1 into undef, just return v1.
9572     if (V2IsUndef)
9573       return V1;
9574     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9575     // the instruction selector will not match, so get a canonical MOVL with
9576     // swapped operands to undo the commute.
9577     return getMOVL(DAG, dl, VT, V2, V1);
9578   }
9579
9580   if (isUNPCKLMask(M, VT, HasInt256))
9581     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9582
9583   if (isUNPCKHMask(M, VT, HasInt256))
9584     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9585
9586   if (V2IsSplat) {
9587     // Normalize mask so all entries that point to V2 points to its first
9588     // element then try to match unpck{h|l} again. If match, return a
9589     // new vector_shuffle with the corrected mask.p
9590     SmallVector<int, 8> NewMask(M.begin(), M.end());
9591     NormalizeMask(NewMask, NumElems);
9592     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9593       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9594     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9595       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9596   }
9597
9598   if (Commuted) {
9599     // Commute is back and try unpck* again.
9600     // FIXME: this seems wrong.
9601     CommuteVectorShuffleMask(M, NumElems);
9602     std::swap(V1, V2);
9603     std::swap(V1IsSplat, V2IsSplat);
9604
9605     if (isUNPCKLMask(M, VT, HasInt256))
9606       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9607
9608     if (isUNPCKHMask(M, VT, HasInt256))
9609       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9610   }
9611
9612   // Normalize the node to match x86 shuffle ops if needed
9613   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9614     return DAG.getCommutedVectorShuffle(*SVOp);
9615
9616   // The checks below are all present in isShuffleMaskLegal, but they are
9617   // inlined here right now to enable us to directly emit target specific
9618   // nodes, and remove one by one until they don't return Op anymore.
9619
9620   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9621       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9622     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9623       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9624   }
9625
9626   if (isPSHUFHWMask(M, VT, HasInt256))
9627     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9628                                 getShufflePSHUFHWImmediate(SVOp),
9629                                 DAG);
9630
9631   if (isPSHUFLWMask(M, VT, HasInt256))
9632     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9633                                 getShufflePSHUFLWImmediate(SVOp),
9634                                 DAG);
9635
9636   unsigned MaskValue;
9637   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9638                   &MaskValue))
9639     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9640
9641   if (isSHUFPMask(M, VT))
9642     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9643                                 getShuffleSHUFImmediate(SVOp), DAG);
9644
9645   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9646     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9647   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9648     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9649
9650   //===--------------------------------------------------------------------===//
9651   // Generate target specific nodes for 128 or 256-bit shuffles only
9652   // supported in the AVX instruction set.
9653   //
9654
9655   // Handle VMOVDDUPY permutations
9656   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9657     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9658
9659   // Handle VPERMILPS/D* permutations
9660   if (isVPERMILPMask(M, VT)) {
9661     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9662       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9663                                   getShuffleSHUFImmediate(SVOp), DAG);
9664     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9665                                 getShuffleSHUFImmediate(SVOp), DAG);
9666   }
9667
9668   unsigned Idx;
9669   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9670     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9671                               Idx*(NumElems/2), DAG, dl);
9672
9673   // Handle VPERM2F128/VPERM2I128 permutations
9674   if (isVPERM2X128Mask(M, VT, HasFp256))
9675     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9676                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9677
9678   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9679     return getINSERTPS(SVOp, dl, DAG);
9680
9681   unsigned Imm8;
9682   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9683     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9684
9685   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9686       VT.is512BitVector()) {
9687     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9688     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9689     SmallVector<SDValue, 16> permclMask;
9690     for (unsigned i = 0; i != NumElems; ++i) {
9691       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9692     }
9693
9694     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9695     if (V2IsUndef)
9696       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9697       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9698                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9699     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9700                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9701   }
9702
9703   //===--------------------------------------------------------------------===//
9704   // Since no target specific shuffle was selected for this generic one,
9705   // lower it into other known shuffles. FIXME: this isn't true yet, but
9706   // this is the plan.
9707   //
9708
9709   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9710   if (VT == MVT::v8i16) {
9711     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9712     if (NewOp.getNode())
9713       return NewOp;
9714   }
9715
9716   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9717     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9718     if (NewOp.getNode())
9719       return NewOp;
9720   }
9721
9722   if (VT == MVT::v16i8) {
9723     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9724     if (NewOp.getNode())
9725       return NewOp;
9726   }
9727
9728   if (VT == MVT::v32i8) {
9729     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9730     if (NewOp.getNode())
9731       return NewOp;
9732   }
9733
9734   // Handle all 128-bit wide vectors with 4 elements, and match them with
9735   // several different shuffle types.
9736   if (NumElems == 4 && VT.is128BitVector())
9737     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9738
9739   // Handle general 256-bit shuffles
9740   if (VT.is256BitVector())
9741     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9742
9743   return SDValue();
9744 }
9745
9746 // This function assumes its argument is a BUILD_VECTOR of constants or
9747 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9748 // true.
9749 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9750                                     unsigned &MaskValue) {
9751   MaskValue = 0;
9752   unsigned NumElems = BuildVector->getNumOperands();
9753   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9754   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9755   unsigned NumElemsInLane = NumElems / NumLanes;
9756
9757   // Blend for v16i16 should be symetric for the both lanes.
9758   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9759     SDValue EltCond = BuildVector->getOperand(i);
9760     SDValue SndLaneEltCond =
9761         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9762
9763     int Lane1Cond = -1, Lane2Cond = -1;
9764     if (isa<ConstantSDNode>(EltCond))
9765       Lane1Cond = !isZero(EltCond);
9766     if (isa<ConstantSDNode>(SndLaneEltCond))
9767       Lane2Cond = !isZero(SndLaneEltCond);
9768
9769     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9770       // Lane1Cond != 0, means we want the first argument.
9771       // Lane1Cond == 0, means we want the second argument.
9772       // The encoding of this argument is 0 for the first argument, 1
9773       // for the second. Therefore, invert the condition.
9774       MaskValue |= !Lane1Cond << i;
9775     else if (Lane1Cond < 0)
9776       MaskValue |= !Lane2Cond << i;
9777     else
9778       return false;
9779   }
9780   return true;
9781 }
9782
9783 // Try to lower a vselect node into a simple blend instruction.
9784 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9785                                    SelectionDAG &DAG) {
9786   SDValue Cond = Op.getOperand(0);
9787   SDValue LHS = Op.getOperand(1);
9788   SDValue RHS = Op.getOperand(2);
9789   SDLoc dl(Op);
9790   MVT VT = Op.getSimpleValueType();
9791   MVT EltVT = VT.getVectorElementType();
9792   unsigned NumElems = VT.getVectorNumElements();
9793
9794   // There is no blend with immediate in AVX-512.
9795   if (VT.is512BitVector())
9796     return SDValue();
9797
9798   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9799     return SDValue();
9800   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9801     return SDValue();
9802
9803   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9804     return SDValue();
9805
9806   // Check the mask for BLEND and build the value.
9807   unsigned MaskValue = 0;
9808   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9809     return SDValue();
9810
9811   // Convert i32 vectors to floating point if it is not AVX2.
9812   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9813   MVT BlendVT = VT;
9814   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9815     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9816                                NumElems);
9817     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9818     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9819   }
9820
9821   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9822                             DAG.getConstant(MaskValue, MVT::i32));
9823   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9824 }
9825
9826 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9827   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9828   if (BlendOp.getNode())
9829     return BlendOp;
9830
9831   // Some types for vselect were previously set to Expand, not Legal or
9832   // Custom. Return an empty SDValue so we fall-through to Expand, after
9833   // the Custom lowering phase.
9834   MVT VT = Op.getSimpleValueType();
9835   switch (VT.SimpleTy) {
9836   default:
9837     break;
9838   case MVT::v8i16:
9839   case MVT::v16i16:
9840     return SDValue();
9841   }
9842
9843   // We couldn't create a "Blend with immediate" node.
9844   // This node should still be legal, but we'll have to emit a blendv*
9845   // instruction.
9846   return Op;
9847 }
9848
9849 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9850   MVT VT = Op.getSimpleValueType();
9851   SDLoc dl(Op);
9852
9853   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9854     return SDValue();
9855
9856   if (VT.getSizeInBits() == 8) {
9857     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9858                                   Op.getOperand(0), Op.getOperand(1));
9859     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9860                                   DAG.getValueType(VT));
9861     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9862   }
9863
9864   if (VT.getSizeInBits() == 16) {
9865     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9866     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9867     if (Idx == 0)
9868       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9869                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9870                                      DAG.getNode(ISD::BITCAST, dl,
9871                                                  MVT::v4i32,
9872                                                  Op.getOperand(0)),
9873                                      Op.getOperand(1)));
9874     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9875                                   Op.getOperand(0), Op.getOperand(1));
9876     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9877                                   DAG.getValueType(VT));
9878     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9879   }
9880
9881   if (VT == MVT::f32) {
9882     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9883     // the result back to FR32 register. It's only worth matching if the
9884     // result has a single use which is a store or a bitcast to i32.  And in
9885     // the case of a store, it's not worth it if the index is a constant 0,
9886     // because a MOVSSmr can be used instead, which is smaller and faster.
9887     if (!Op.hasOneUse())
9888       return SDValue();
9889     SDNode *User = *Op.getNode()->use_begin();
9890     if ((User->getOpcode() != ISD::STORE ||
9891          (isa<ConstantSDNode>(Op.getOperand(1)) &&
9892           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9893         (User->getOpcode() != ISD::BITCAST ||
9894          User->getValueType(0) != MVT::i32))
9895       return SDValue();
9896     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9897                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9898                                               Op.getOperand(0)),
9899                                               Op.getOperand(1));
9900     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9901   }
9902
9903   if (VT == MVT::i32 || VT == MVT::i64) {
9904     // ExtractPS/pextrq works with constant index.
9905     if (isa<ConstantSDNode>(Op.getOperand(1)))
9906       return Op;
9907   }
9908   return SDValue();
9909 }
9910
9911 /// Extract one bit from mask vector, like v16i1 or v8i1.
9912 /// AVX-512 feature.
9913 SDValue
9914 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9915   SDValue Vec = Op.getOperand(0);
9916   SDLoc dl(Vec);
9917   MVT VecVT = Vec.getSimpleValueType();
9918   SDValue Idx = Op.getOperand(1);
9919   MVT EltVT = Op.getSimpleValueType();
9920
9921   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9922
9923   // variable index can't be handled in mask registers,
9924   // extend vector to VR512
9925   if (!isa<ConstantSDNode>(Idx)) {
9926     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9927     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9928     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9929                               ExtVT.getVectorElementType(), Ext, Idx);
9930     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9931   }
9932
9933   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9934   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9935   unsigned MaxSift = rc->getSize()*8 - 1;
9936   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9937                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9938   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9939                     DAG.getConstant(MaxSift, MVT::i8));
9940   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9941                        DAG.getIntPtrConstant(0));
9942 }
9943
9944 SDValue
9945 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9946                                            SelectionDAG &DAG) const {
9947   SDLoc dl(Op);
9948   SDValue Vec = Op.getOperand(0);
9949   MVT VecVT = Vec.getSimpleValueType();
9950   SDValue Idx = Op.getOperand(1);
9951
9952   if (Op.getSimpleValueType() == MVT::i1)
9953     return ExtractBitFromMaskVector(Op, DAG);
9954
9955   if (!isa<ConstantSDNode>(Idx)) {
9956     if (VecVT.is512BitVector() ||
9957         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9958          VecVT.getVectorElementType().getSizeInBits() == 32)) {
9959
9960       MVT MaskEltVT =
9961         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9962       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9963                                     MaskEltVT.getSizeInBits());
9964
9965       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9966       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9967                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
9968                                 Idx, DAG.getConstant(0, getPointerTy()));
9969       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9970       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9971                         Perm, DAG.getConstant(0, getPointerTy()));
9972     }
9973     return SDValue();
9974   }
9975
9976   // If this is a 256-bit vector result, first extract the 128-bit vector and
9977   // then extract the element from the 128-bit vector.
9978   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9979
9980     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9981     // Get the 128-bit vector.
9982     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9983     MVT EltVT = VecVT.getVectorElementType();
9984
9985     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9986
9987     //if (IdxVal >= NumElems/2)
9988     //  IdxVal -= NumElems/2;
9989     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9990     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9991                        DAG.getConstant(IdxVal, MVT::i32));
9992   }
9993
9994   assert(VecVT.is128BitVector() && "Unexpected vector length");
9995
9996   if (Subtarget->hasSSE41()) {
9997     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9998     if (Res.getNode())
9999       return Res;
10000   }
10001
10002   MVT VT = Op.getSimpleValueType();
10003   // TODO: handle v16i8.
10004   if (VT.getSizeInBits() == 16) {
10005     SDValue Vec = Op.getOperand(0);
10006     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10007     if (Idx == 0)
10008       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10009                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10010                                      DAG.getNode(ISD::BITCAST, dl,
10011                                                  MVT::v4i32, Vec),
10012                                      Op.getOperand(1)));
10013     // Transform it so it match pextrw which produces a 32-bit result.
10014     MVT EltVT = MVT::i32;
10015     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10016                                   Op.getOperand(0), Op.getOperand(1));
10017     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10018                                   DAG.getValueType(VT));
10019     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10020   }
10021
10022   if (VT.getSizeInBits() == 32) {
10023     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10024     if (Idx == 0)
10025       return Op;
10026
10027     // SHUFPS the element to the lowest double word, then movss.
10028     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10029     MVT VVT = Op.getOperand(0).getSimpleValueType();
10030     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10031                                        DAG.getUNDEF(VVT), Mask);
10032     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10033                        DAG.getIntPtrConstant(0));
10034   }
10035
10036   if (VT.getSizeInBits() == 64) {
10037     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10038     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10039     //        to match extract_elt for f64.
10040     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10041     if (Idx == 0)
10042       return Op;
10043
10044     // UNPCKHPD the element to the lowest double word, then movsd.
10045     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10046     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10047     int Mask[2] = { 1, -1 };
10048     MVT VVT = Op.getOperand(0).getSimpleValueType();
10049     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10050                                        DAG.getUNDEF(VVT), Mask);
10051     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10052                        DAG.getIntPtrConstant(0));
10053   }
10054
10055   return SDValue();
10056 }
10057
10058 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10059   MVT VT = Op.getSimpleValueType();
10060   MVT EltVT = VT.getVectorElementType();
10061   SDLoc dl(Op);
10062
10063   SDValue N0 = Op.getOperand(0);
10064   SDValue N1 = Op.getOperand(1);
10065   SDValue N2 = Op.getOperand(2);
10066
10067   if (!VT.is128BitVector())
10068     return SDValue();
10069
10070   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
10071       isa<ConstantSDNode>(N2)) {
10072     unsigned Opc;
10073     if (VT == MVT::v8i16)
10074       Opc = X86ISD::PINSRW;
10075     else if (VT == MVT::v16i8)
10076       Opc = X86ISD::PINSRB;
10077     else
10078       Opc = X86ISD::PINSRB;
10079
10080     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10081     // argument.
10082     if (N1.getValueType() != MVT::i32)
10083       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10084     if (N2.getValueType() != MVT::i32)
10085       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10086     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10087   }
10088
10089   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
10090     // Bits [7:6] of the constant are the source select.  This will always be
10091     //  zero here.  The DAG Combiner may combine an extract_elt index into these
10092     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
10093     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10094     // Bits [5:4] of the constant are the destination select.  This is the
10095     //  value of the incoming immediate.
10096     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10097     //   combine either bitwise AND or insert of float 0.0 to set these bits.
10098     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10099     // Create this as a scalar to vector..
10100     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10101     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10102   }
10103
10104   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10105     // PINSR* works with constant index.
10106     return Op;
10107   }
10108   return SDValue();
10109 }
10110
10111 /// Insert one bit to mask vector, like v16i1 or v8i1.
10112 /// AVX-512 feature.
10113 SDValue 
10114 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10115   SDLoc dl(Op);
10116   SDValue Vec = Op.getOperand(0);
10117   SDValue Elt = Op.getOperand(1);
10118   SDValue Idx = Op.getOperand(2);
10119   MVT VecVT = Vec.getSimpleValueType();
10120
10121   if (!isa<ConstantSDNode>(Idx)) {
10122     // Non constant index. Extend source and destination,
10123     // insert element and then truncate the result.
10124     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10125     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10126     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10127       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10128       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10129     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10130   }
10131
10132   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10133   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10134   if (Vec.getOpcode() == ISD::UNDEF)
10135     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10136                        DAG.getConstant(IdxVal, MVT::i8));
10137   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10138   unsigned MaxSift = rc->getSize()*8 - 1;
10139   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10140                     DAG.getConstant(MaxSift, MVT::i8));
10141   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10142                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10143   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10144 }
10145 SDValue
10146 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10147   MVT VT = Op.getSimpleValueType();
10148   MVT EltVT = VT.getVectorElementType();
10149   
10150   if (EltVT == MVT::i1)
10151     return InsertBitToMaskVector(Op, DAG);
10152
10153   SDLoc dl(Op);
10154   SDValue N0 = Op.getOperand(0);
10155   SDValue N1 = Op.getOperand(1);
10156   SDValue N2 = Op.getOperand(2);
10157
10158   // If this is a 256-bit vector result, first extract the 128-bit vector,
10159   // insert the element into the extracted half and then place it back.
10160   if (VT.is256BitVector() || VT.is512BitVector()) {
10161     if (!isa<ConstantSDNode>(N2))
10162       return SDValue();
10163
10164     // Get the desired 128-bit vector half.
10165     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10166     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10167
10168     // Insert the element into the desired half.
10169     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10170     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10171
10172     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10173                     DAG.getConstant(IdxIn128, MVT::i32));
10174
10175     // Insert the changed part back to the 256-bit vector
10176     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10177   }
10178
10179   if (Subtarget->hasSSE41())
10180     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10181
10182   if (EltVT == MVT::i8)
10183     return SDValue();
10184
10185   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10186     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10187     // as its second argument.
10188     if (N1.getValueType() != MVT::i32)
10189       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10190     if (N2.getValueType() != MVT::i32)
10191       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10192     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10193   }
10194   return SDValue();
10195 }
10196
10197 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10198   SDLoc dl(Op);
10199   MVT OpVT = Op.getSimpleValueType();
10200
10201   // If this is a 256-bit vector result, first insert into a 128-bit
10202   // vector and then insert into the 256-bit vector.
10203   if (!OpVT.is128BitVector()) {
10204     // Insert into a 128-bit vector.
10205     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10206     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10207                                  OpVT.getVectorNumElements() / SizeFactor);
10208
10209     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10210
10211     // Insert the 128-bit vector.
10212     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10213   }
10214
10215   if (OpVT == MVT::v1i64 &&
10216       Op.getOperand(0).getValueType() == MVT::i64)
10217     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10218
10219   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10220   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10221   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10222                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10223 }
10224
10225 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10226 // a simple subregister reference or explicit instructions to grab
10227 // upper bits of a vector.
10228 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10229                                       SelectionDAG &DAG) {
10230   SDLoc dl(Op);
10231   SDValue In =  Op.getOperand(0);
10232   SDValue Idx = Op.getOperand(1);
10233   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10234   MVT ResVT   = Op.getSimpleValueType();
10235   MVT InVT    = In.getSimpleValueType();
10236
10237   if (Subtarget->hasFp256()) {
10238     if (ResVT.is128BitVector() &&
10239         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10240         isa<ConstantSDNode>(Idx)) {
10241       return Extract128BitVector(In, IdxVal, DAG, dl);
10242     }
10243     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10244         isa<ConstantSDNode>(Idx)) {
10245       return Extract256BitVector(In, IdxVal, DAG, dl);
10246     }
10247   }
10248   return SDValue();
10249 }
10250
10251 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10252 // simple superregister reference or explicit instructions to insert
10253 // the upper bits of a vector.
10254 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10255                                      SelectionDAG &DAG) {
10256   if (Subtarget->hasFp256()) {
10257     SDLoc dl(Op.getNode());
10258     SDValue Vec = Op.getNode()->getOperand(0);
10259     SDValue SubVec = Op.getNode()->getOperand(1);
10260     SDValue Idx = Op.getNode()->getOperand(2);
10261
10262     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10263          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10264         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10265         isa<ConstantSDNode>(Idx)) {
10266       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10267       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10268     }
10269
10270     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10271         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10272         isa<ConstantSDNode>(Idx)) {
10273       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10274       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10275     }
10276   }
10277   return SDValue();
10278 }
10279
10280 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10281 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10282 // one of the above mentioned nodes. It has to be wrapped because otherwise
10283 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10284 // be used to form addressing mode. These wrapped nodes will be selected
10285 // into MOV32ri.
10286 SDValue
10287 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10288   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10289
10290   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10291   // global base reg.
10292   unsigned char OpFlag = 0;
10293   unsigned WrapperKind = X86ISD::Wrapper;
10294   CodeModel::Model M = DAG.getTarget().getCodeModel();
10295
10296   if (Subtarget->isPICStyleRIPRel() &&
10297       (M == CodeModel::Small || M == CodeModel::Kernel))
10298     WrapperKind = X86ISD::WrapperRIP;
10299   else if (Subtarget->isPICStyleGOT())
10300     OpFlag = X86II::MO_GOTOFF;
10301   else if (Subtarget->isPICStyleStubPIC())
10302     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10303
10304   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10305                                              CP->getAlignment(),
10306                                              CP->getOffset(), OpFlag);
10307   SDLoc DL(CP);
10308   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10309   // With PIC, the address is actually $g + Offset.
10310   if (OpFlag) {
10311     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10312                          DAG.getNode(X86ISD::GlobalBaseReg,
10313                                      SDLoc(), getPointerTy()),
10314                          Result);
10315   }
10316
10317   return Result;
10318 }
10319
10320 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10321   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10322
10323   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10324   // global base reg.
10325   unsigned char OpFlag = 0;
10326   unsigned WrapperKind = X86ISD::Wrapper;
10327   CodeModel::Model M = DAG.getTarget().getCodeModel();
10328
10329   if (Subtarget->isPICStyleRIPRel() &&
10330       (M == CodeModel::Small || M == CodeModel::Kernel))
10331     WrapperKind = X86ISD::WrapperRIP;
10332   else if (Subtarget->isPICStyleGOT())
10333     OpFlag = X86II::MO_GOTOFF;
10334   else if (Subtarget->isPICStyleStubPIC())
10335     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10336
10337   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10338                                           OpFlag);
10339   SDLoc DL(JT);
10340   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10341
10342   // With PIC, the address is actually $g + Offset.
10343   if (OpFlag)
10344     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10345                          DAG.getNode(X86ISD::GlobalBaseReg,
10346                                      SDLoc(), getPointerTy()),
10347                          Result);
10348
10349   return Result;
10350 }
10351
10352 SDValue
10353 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10354   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10355
10356   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10357   // global base reg.
10358   unsigned char OpFlag = 0;
10359   unsigned WrapperKind = X86ISD::Wrapper;
10360   CodeModel::Model M = DAG.getTarget().getCodeModel();
10361
10362   if (Subtarget->isPICStyleRIPRel() &&
10363       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10364     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10365       OpFlag = X86II::MO_GOTPCREL;
10366     WrapperKind = X86ISD::WrapperRIP;
10367   } else if (Subtarget->isPICStyleGOT()) {
10368     OpFlag = X86II::MO_GOT;
10369   } else if (Subtarget->isPICStyleStubPIC()) {
10370     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10371   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10372     OpFlag = X86II::MO_DARWIN_NONLAZY;
10373   }
10374
10375   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10376
10377   SDLoc DL(Op);
10378   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10379
10380   // With PIC, the address is actually $g + Offset.
10381   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10382       !Subtarget->is64Bit()) {
10383     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10384                          DAG.getNode(X86ISD::GlobalBaseReg,
10385                                      SDLoc(), getPointerTy()),
10386                          Result);
10387   }
10388
10389   // For symbols that require a load from a stub to get the address, emit the
10390   // load.
10391   if (isGlobalStubReference(OpFlag))
10392     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10393                          MachinePointerInfo::getGOT(), false, false, false, 0);
10394
10395   return Result;
10396 }
10397
10398 SDValue
10399 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10400   // Create the TargetBlockAddressAddress node.
10401   unsigned char OpFlags =
10402     Subtarget->ClassifyBlockAddressReference();
10403   CodeModel::Model M = DAG.getTarget().getCodeModel();
10404   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10405   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10406   SDLoc dl(Op);
10407   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10408                                              OpFlags);
10409
10410   if (Subtarget->isPICStyleRIPRel() &&
10411       (M == CodeModel::Small || M == CodeModel::Kernel))
10412     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10413   else
10414     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10415
10416   // With PIC, the address is actually $g + Offset.
10417   if (isGlobalRelativeToPICBase(OpFlags)) {
10418     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10419                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10420                          Result);
10421   }
10422
10423   return Result;
10424 }
10425
10426 SDValue
10427 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10428                                       int64_t Offset, SelectionDAG &DAG) const {
10429   // Create the TargetGlobalAddress node, folding in the constant
10430   // offset if it is legal.
10431   unsigned char OpFlags =
10432       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10433   CodeModel::Model M = DAG.getTarget().getCodeModel();
10434   SDValue Result;
10435   if (OpFlags == X86II::MO_NO_FLAG &&
10436       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10437     // A direct static reference to a global.
10438     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10439     Offset = 0;
10440   } else {
10441     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10442   }
10443
10444   if (Subtarget->isPICStyleRIPRel() &&
10445       (M == CodeModel::Small || M == CodeModel::Kernel))
10446     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10447   else
10448     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10449
10450   // With PIC, the address is actually $g + Offset.
10451   if (isGlobalRelativeToPICBase(OpFlags)) {
10452     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10453                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10454                          Result);
10455   }
10456
10457   // For globals that require a load from a stub to get the address, emit the
10458   // load.
10459   if (isGlobalStubReference(OpFlags))
10460     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10461                          MachinePointerInfo::getGOT(), false, false, false, 0);
10462
10463   // If there was a non-zero offset that we didn't fold, create an explicit
10464   // addition for it.
10465   if (Offset != 0)
10466     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10467                          DAG.getConstant(Offset, getPointerTy()));
10468
10469   return Result;
10470 }
10471
10472 SDValue
10473 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10474   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10475   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10476   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10477 }
10478
10479 static SDValue
10480 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10481            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10482            unsigned char OperandFlags, bool LocalDynamic = false) {
10483   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10484   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10485   SDLoc dl(GA);
10486   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10487                                            GA->getValueType(0),
10488                                            GA->getOffset(),
10489                                            OperandFlags);
10490
10491   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10492                                            : X86ISD::TLSADDR;
10493
10494   if (InFlag) {
10495     SDValue Ops[] = { Chain,  TGA, *InFlag };
10496     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10497   } else {
10498     SDValue Ops[]  = { Chain, TGA };
10499     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10500   }
10501
10502   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10503   MFI->setAdjustsStack(true);
10504
10505   SDValue Flag = Chain.getValue(1);
10506   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10507 }
10508
10509 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10510 static SDValue
10511 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10512                                 const EVT PtrVT) {
10513   SDValue InFlag;
10514   SDLoc dl(GA);  // ? function entry point might be better
10515   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10516                                    DAG.getNode(X86ISD::GlobalBaseReg,
10517                                                SDLoc(), PtrVT), InFlag);
10518   InFlag = Chain.getValue(1);
10519
10520   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10521 }
10522
10523 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10524 static SDValue
10525 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10526                                 const EVT PtrVT) {
10527   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10528                     X86::RAX, X86II::MO_TLSGD);
10529 }
10530
10531 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10532                                            SelectionDAG &DAG,
10533                                            const EVT PtrVT,
10534                                            bool is64Bit) {
10535   SDLoc dl(GA);
10536
10537   // Get the start address of the TLS block for this module.
10538   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10539       .getInfo<X86MachineFunctionInfo>();
10540   MFI->incNumLocalDynamicTLSAccesses();
10541
10542   SDValue Base;
10543   if (is64Bit) {
10544     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10545                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10546   } else {
10547     SDValue InFlag;
10548     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10549         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10550     InFlag = Chain.getValue(1);
10551     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10552                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10553   }
10554
10555   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10556   // of Base.
10557
10558   // Build x@dtpoff.
10559   unsigned char OperandFlags = X86II::MO_DTPOFF;
10560   unsigned WrapperKind = X86ISD::Wrapper;
10561   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10562                                            GA->getValueType(0),
10563                                            GA->getOffset(), OperandFlags);
10564   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10565
10566   // Add x@dtpoff with the base.
10567   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10568 }
10569
10570 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10571 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10572                                    const EVT PtrVT, TLSModel::Model model,
10573                                    bool is64Bit, bool isPIC) {
10574   SDLoc dl(GA);
10575
10576   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10577   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10578                                                          is64Bit ? 257 : 256));
10579
10580   SDValue ThreadPointer =
10581       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10582                   MachinePointerInfo(Ptr), false, false, false, 0);
10583
10584   unsigned char OperandFlags = 0;
10585   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10586   // initialexec.
10587   unsigned WrapperKind = X86ISD::Wrapper;
10588   if (model == TLSModel::LocalExec) {
10589     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10590   } else if (model == TLSModel::InitialExec) {
10591     if (is64Bit) {
10592       OperandFlags = X86II::MO_GOTTPOFF;
10593       WrapperKind = X86ISD::WrapperRIP;
10594     } else {
10595       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10596     }
10597   } else {
10598     llvm_unreachable("Unexpected model");
10599   }
10600
10601   // emit "addl x@ntpoff,%eax" (local exec)
10602   // or "addl x@indntpoff,%eax" (initial exec)
10603   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10604   SDValue TGA =
10605       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10606                                  GA->getOffset(), OperandFlags);
10607   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10608
10609   if (model == TLSModel::InitialExec) {
10610     if (isPIC && !is64Bit) {
10611       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10612                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10613                            Offset);
10614     }
10615
10616     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10617                          MachinePointerInfo::getGOT(), false, false, false, 0);
10618   }
10619
10620   // The address of the thread local variable is the add of the thread
10621   // pointer with the offset of the variable.
10622   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10623 }
10624
10625 SDValue
10626 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10627
10628   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10629   const GlobalValue *GV = GA->getGlobal();
10630
10631   if (Subtarget->isTargetELF()) {
10632     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10633
10634     switch (model) {
10635       case TLSModel::GeneralDynamic:
10636         if (Subtarget->is64Bit())
10637           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10638         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10639       case TLSModel::LocalDynamic:
10640         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10641                                            Subtarget->is64Bit());
10642       case TLSModel::InitialExec:
10643       case TLSModel::LocalExec:
10644         return LowerToTLSExecModel(
10645             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10646             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10647     }
10648     llvm_unreachable("Unknown TLS model.");
10649   }
10650
10651   if (Subtarget->isTargetDarwin()) {
10652     // Darwin only has one model of TLS.  Lower to that.
10653     unsigned char OpFlag = 0;
10654     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10655                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10656
10657     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10658     // global base reg.
10659     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10660                  !Subtarget->is64Bit();
10661     if (PIC32)
10662       OpFlag = X86II::MO_TLVP_PIC_BASE;
10663     else
10664       OpFlag = X86II::MO_TLVP;
10665     SDLoc DL(Op);
10666     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10667                                                 GA->getValueType(0),
10668                                                 GA->getOffset(), OpFlag);
10669     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10670
10671     // With PIC32, the address is actually $g + Offset.
10672     if (PIC32)
10673       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10674                            DAG.getNode(X86ISD::GlobalBaseReg,
10675                                        SDLoc(), getPointerTy()),
10676                            Offset);
10677
10678     // Lowering the machine isd will make sure everything is in the right
10679     // location.
10680     SDValue Chain = DAG.getEntryNode();
10681     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10682     SDValue Args[] = { Chain, Offset };
10683     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10684
10685     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10686     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10687     MFI->setAdjustsStack(true);
10688
10689     // And our return value (tls address) is in the standard call return value
10690     // location.
10691     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10692     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10693                               Chain.getValue(1));
10694   }
10695
10696   if (Subtarget->isTargetKnownWindowsMSVC() ||
10697       Subtarget->isTargetWindowsGNU()) {
10698     // Just use the implicit TLS architecture
10699     // Need to generate someting similar to:
10700     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10701     //                                  ; from TEB
10702     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10703     //   mov     rcx, qword [rdx+rcx*8]
10704     //   mov     eax, .tls$:tlsvar
10705     //   [rax+rcx] contains the address
10706     // Windows 64bit: gs:0x58
10707     // Windows 32bit: fs:__tls_array
10708
10709     SDLoc dl(GA);
10710     SDValue Chain = DAG.getEntryNode();
10711
10712     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10713     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10714     // use its literal value of 0x2C.
10715     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10716                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10717                                                              256)
10718                                         : Type::getInt32PtrTy(*DAG.getContext(),
10719                                                               257));
10720
10721     SDValue TlsArray =
10722         Subtarget->is64Bit()
10723             ? DAG.getIntPtrConstant(0x58)
10724             : (Subtarget->isTargetWindowsGNU()
10725                    ? DAG.getIntPtrConstant(0x2C)
10726                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10727
10728     SDValue ThreadPointer =
10729         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10730                     MachinePointerInfo(Ptr), false, false, false, 0);
10731
10732     // Load the _tls_index variable
10733     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10734     if (Subtarget->is64Bit())
10735       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10736                            IDX, MachinePointerInfo(), MVT::i32,
10737                            false, false, false, 0);
10738     else
10739       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10740                         false, false, false, 0);
10741
10742     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10743                                     getPointerTy());
10744     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10745
10746     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10747     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10748                       false, false, false, 0);
10749
10750     // Get the offset of start of .tls section
10751     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10752                                              GA->getValueType(0),
10753                                              GA->getOffset(), X86II::MO_SECREL);
10754     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10755
10756     // The address of the thread local variable is the add of the thread
10757     // pointer with the offset of the variable.
10758     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10759   }
10760
10761   llvm_unreachable("TLS not implemented for this target.");
10762 }
10763
10764 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10765 /// and take a 2 x i32 value to shift plus a shift amount.
10766 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10767   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10768   MVT VT = Op.getSimpleValueType();
10769   unsigned VTBits = VT.getSizeInBits();
10770   SDLoc dl(Op);
10771   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10772   SDValue ShOpLo = Op.getOperand(0);
10773   SDValue ShOpHi = Op.getOperand(1);
10774   SDValue ShAmt  = Op.getOperand(2);
10775   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10776   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10777   // during isel.
10778   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10779                                   DAG.getConstant(VTBits - 1, MVT::i8));
10780   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10781                                      DAG.getConstant(VTBits - 1, MVT::i8))
10782                        : DAG.getConstant(0, VT);
10783
10784   SDValue Tmp2, Tmp3;
10785   if (Op.getOpcode() == ISD::SHL_PARTS) {
10786     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10787     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10788   } else {
10789     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10790     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10791   }
10792
10793   // If the shift amount is larger or equal than the width of a part we can't
10794   // rely on the results of shld/shrd. Insert a test and select the appropriate
10795   // values for large shift amounts.
10796   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10797                                 DAG.getConstant(VTBits, MVT::i8));
10798   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10799                              AndNode, DAG.getConstant(0, MVT::i8));
10800
10801   SDValue Hi, Lo;
10802   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10803   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10804   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10805
10806   if (Op.getOpcode() == ISD::SHL_PARTS) {
10807     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10808     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10809   } else {
10810     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10811     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10812   }
10813
10814   SDValue Ops[2] = { Lo, Hi };
10815   return DAG.getMergeValues(Ops, dl);
10816 }
10817
10818 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10819                                            SelectionDAG &DAG) const {
10820   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10821
10822   if (SrcVT.isVector())
10823     return SDValue();
10824
10825   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10826          "Unknown SINT_TO_FP to lower!");
10827
10828   // These are really Legal; return the operand so the caller accepts it as
10829   // Legal.
10830   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10831     return Op;
10832   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10833       Subtarget->is64Bit()) {
10834     return Op;
10835   }
10836
10837   SDLoc dl(Op);
10838   unsigned Size = SrcVT.getSizeInBits()/8;
10839   MachineFunction &MF = DAG.getMachineFunction();
10840   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10841   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10842   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10843                                StackSlot,
10844                                MachinePointerInfo::getFixedStack(SSFI),
10845                                false, false, 0);
10846   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10847 }
10848
10849 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10850                                      SDValue StackSlot,
10851                                      SelectionDAG &DAG) const {
10852   // Build the FILD
10853   SDLoc DL(Op);
10854   SDVTList Tys;
10855   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10856   if (useSSE)
10857     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10858   else
10859     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10860
10861   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10862
10863   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10864   MachineMemOperand *MMO;
10865   if (FI) {
10866     int SSFI = FI->getIndex();
10867     MMO =
10868       DAG.getMachineFunction()
10869       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10870                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10871   } else {
10872     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10873     StackSlot = StackSlot.getOperand(1);
10874   }
10875   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10876   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10877                                            X86ISD::FILD, DL,
10878                                            Tys, Ops, SrcVT, MMO);
10879
10880   if (useSSE) {
10881     Chain = Result.getValue(1);
10882     SDValue InFlag = Result.getValue(2);
10883
10884     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10885     // shouldn't be necessary except that RFP cannot be live across
10886     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10887     MachineFunction &MF = DAG.getMachineFunction();
10888     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10889     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10890     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10891     Tys = DAG.getVTList(MVT::Other);
10892     SDValue Ops[] = {
10893       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10894     };
10895     MachineMemOperand *MMO =
10896       DAG.getMachineFunction()
10897       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10898                             MachineMemOperand::MOStore, SSFISize, SSFISize);
10899
10900     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10901                                     Ops, Op.getValueType(), MMO);
10902     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10903                          MachinePointerInfo::getFixedStack(SSFI),
10904                          false, false, false, 0);
10905   }
10906
10907   return Result;
10908 }
10909
10910 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10911 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10912                                                SelectionDAG &DAG) const {
10913   // This algorithm is not obvious. Here it is what we're trying to output:
10914   /*
10915      movq       %rax,  %xmm0
10916      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10917      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10918      #ifdef __SSE3__
10919        haddpd   %xmm0, %xmm0
10920      #else
10921        pshufd   $0x4e, %xmm0, %xmm1
10922        addpd    %xmm1, %xmm0
10923      #endif
10924   */
10925
10926   SDLoc dl(Op);
10927   LLVMContext *Context = DAG.getContext();
10928
10929   // Build some magic constants.
10930   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10931   Constant *C0 = ConstantDataVector::get(*Context, CV0);
10932   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10933
10934   SmallVector<Constant*,2> CV1;
10935   CV1.push_back(
10936     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10937                                       APInt(64, 0x4330000000000000ULL))));
10938   CV1.push_back(
10939     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10940                                       APInt(64, 0x4530000000000000ULL))));
10941   Constant *C1 = ConstantVector::get(CV1);
10942   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10943
10944   // Load the 64-bit value into an XMM register.
10945   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10946                             Op.getOperand(0));
10947   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10948                               MachinePointerInfo::getConstantPool(),
10949                               false, false, false, 16);
10950   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10951                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10952                               CLod0);
10953
10954   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10955                               MachinePointerInfo::getConstantPool(),
10956                               false, false, false, 16);
10957   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10958   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10959   SDValue Result;
10960
10961   if (Subtarget->hasSSE3()) {
10962     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10963     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10964   } else {
10965     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10966     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10967                                            S2F, 0x4E, DAG);
10968     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10969                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10970                          Sub);
10971   }
10972
10973   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10974                      DAG.getIntPtrConstant(0));
10975 }
10976
10977 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10978 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10979                                                SelectionDAG &DAG) const {
10980   SDLoc dl(Op);
10981   // FP constant to bias correct the final result.
10982   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10983                                    MVT::f64);
10984
10985   // Load the 32-bit value into an XMM register.
10986   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10987                              Op.getOperand(0));
10988
10989   // Zero out the upper parts of the register.
10990   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10991
10992   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10993                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10994                      DAG.getIntPtrConstant(0));
10995
10996   // Or the load with the bias.
10997   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10998                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10999                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11000                                                    MVT::v2f64, Load)),
11001                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11002                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11003                                                    MVT::v2f64, Bias)));
11004   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11005                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11006                    DAG.getIntPtrConstant(0));
11007
11008   // Subtract the bias.
11009   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11010
11011   // Handle final rounding.
11012   EVT DestVT = Op.getValueType();
11013
11014   if (DestVT.bitsLT(MVT::f64))
11015     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11016                        DAG.getIntPtrConstant(0));
11017   if (DestVT.bitsGT(MVT::f64))
11018     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11019
11020   // Handle final rounding.
11021   return Sub;
11022 }
11023
11024 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11025                                                SelectionDAG &DAG) const {
11026   SDValue N0 = Op.getOperand(0);
11027   MVT SVT = N0.getSimpleValueType();
11028   SDLoc dl(Op);
11029
11030   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11031           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11032          "Custom UINT_TO_FP is not supported!");
11033
11034   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11035   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11036                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11037 }
11038
11039 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11040                                            SelectionDAG &DAG) const {
11041   SDValue N0 = Op.getOperand(0);
11042   SDLoc dl(Op);
11043
11044   if (Op.getValueType().isVector())
11045     return lowerUINT_TO_FP_vec(Op, DAG);
11046
11047   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11048   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11049   // the optimization here.
11050   if (DAG.SignBitIsZero(N0))
11051     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11052
11053   MVT SrcVT = N0.getSimpleValueType();
11054   MVT DstVT = Op.getSimpleValueType();
11055   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11056     return LowerUINT_TO_FP_i64(Op, DAG);
11057   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11058     return LowerUINT_TO_FP_i32(Op, DAG);
11059   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11060     return SDValue();
11061
11062   // Make a 64-bit buffer, and use it to build an FILD.
11063   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11064   if (SrcVT == MVT::i32) {
11065     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11066     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11067                                      getPointerTy(), StackSlot, WordOff);
11068     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11069                                   StackSlot, MachinePointerInfo(),
11070                                   false, false, 0);
11071     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11072                                   OffsetSlot, MachinePointerInfo(),
11073                                   false, false, 0);
11074     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11075     return Fild;
11076   }
11077
11078   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11079   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11080                                StackSlot, MachinePointerInfo(),
11081                                false, false, 0);
11082   // For i64 source, we need to add the appropriate power of 2 if the input
11083   // was negative.  This is the same as the optimization in
11084   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11085   // we must be careful to do the computation in x87 extended precision, not
11086   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11087   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11088   MachineMemOperand *MMO =
11089     DAG.getMachineFunction()
11090     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11091                           MachineMemOperand::MOLoad, 8, 8);
11092
11093   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11094   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11095   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11096                                          MVT::i64, MMO);
11097
11098   APInt FF(32, 0x5F800000ULL);
11099
11100   // Check whether the sign bit is set.
11101   SDValue SignSet = DAG.getSetCC(dl,
11102                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11103                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11104                                  ISD::SETLT);
11105
11106   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11107   SDValue FudgePtr = DAG.getConstantPool(
11108                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11109                                          getPointerTy());
11110
11111   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11112   SDValue Zero = DAG.getIntPtrConstant(0);
11113   SDValue Four = DAG.getIntPtrConstant(4);
11114   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11115                                Zero, Four);
11116   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11117
11118   // Load the value out, extending it from f32 to f80.
11119   // FIXME: Avoid the extend by constructing the right constant pool?
11120   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11121                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11122                                  MVT::f32, false, false, false, 4);
11123   // Extend everything to 80 bits to force it to be done on x87.
11124   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11125   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11126 }
11127
11128 std::pair<SDValue,SDValue>
11129 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11130                                     bool IsSigned, bool IsReplace) const {
11131   SDLoc DL(Op);
11132
11133   EVT DstTy = Op.getValueType();
11134
11135   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11136     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11137     DstTy = MVT::i64;
11138   }
11139
11140   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11141          DstTy.getSimpleVT() >= MVT::i16 &&
11142          "Unknown FP_TO_INT to lower!");
11143
11144   // These are really Legal.
11145   if (DstTy == MVT::i32 &&
11146       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11147     return std::make_pair(SDValue(), SDValue());
11148   if (Subtarget->is64Bit() &&
11149       DstTy == MVT::i64 &&
11150       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11151     return std::make_pair(SDValue(), SDValue());
11152
11153   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11154   // stack slot, or into the FTOL runtime function.
11155   MachineFunction &MF = DAG.getMachineFunction();
11156   unsigned MemSize = DstTy.getSizeInBits()/8;
11157   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11158   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11159
11160   unsigned Opc;
11161   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11162     Opc = X86ISD::WIN_FTOL;
11163   else
11164     switch (DstTy.getSimpleVT().SimpleTy) {
11165     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11166     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11167     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11168     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11169     }
11170
11171   SDValue Chain = DAG.getEntryNode();
11172   SDValue Value = Op.getOperand(0);
11173   EVT TheVT = Op.getOperand(0).getValueType();
11174   // FIXME This causes a redundant load/store if the SSE-class value is already
11175   // in memory, such as if it is on the callstack.
11176   if (isScalarFPTypeInSSEReg(TheVT)) {
11177     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11178     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11179                          MachinePointerInfo::getFixedStack(SSFI),
11180                          false, false, 0);
11181     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11182     SDValue Ops[] = {
11183       Chain, StackSlot, DAG.getValueType(TheVT)
11184     };
11185
11186     MachineMemOperand *MMO =
11187       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11188                               MachineMemOperand::MOLoad, MemSize, MemSize);
11189     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11190     Chain = Value.getValue(1);
11191     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11192     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11193   }
11194
11195   MachineMemOperand *MMO =
11196     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11197                             MachineMemOperand::MOStore, MemSize, MemSize);
11198
11199   if (Opc != X86ISD::WIN_FTOL) {
11200     // Build the FP_TO_INT*_IN_MEM
11201     SDValue Ops[] = { Chain, Value, StackSlot };
11202     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11203                                            Ops, DstTy, MMO);
11204     return std::make_pair(FIST, StackSlot);
11205   } else {
11206     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11207       DAG.getVTList(MVT::Other, MVT::Glue),
11208       Chain, Value);
11209     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11210       MVT::i32, ftol.getValue(1));
11211     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11212       MVT::i32, eax.getValue(2));
11213     SDValue Ops[] = { eax, edx };
11214     SDValue pair = IsReplace
11215       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11216       : DAG.getMergeValues(Ops, DL);
11217     return std::make_pair(pair, SDValue());
11218   }
11219 }
11220
11221 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11222                               const X86Subtarget *Subtarget) {
11223   MVT VT = Op->getSimpleValueType(0);
11224   SDValue In = Op->getOperand(0);
11225   MVT InVT = In.getSimpleValueType();
11226   SDLoc dl(Op);
11227
11228   // Optimize vectors in AVX mode:
11229   //
11230   //   v8i16 -> v8i32
11231   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11232   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11233   //   Concat upper and lower parts.
11234   //
11235   //   v4i32 -> v4i64
11236   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11237   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11238   //   Concat upper and lower parts.
11239   //
11240
11241   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11242       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11243       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11244     return SDValue();
11245
11246   if (Subtarget->hasInt256())
11247     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11248
11249   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11250   SDValue Undef = DAG.getUNDEF(InVT);
11251   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11252   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11253   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11254
11255   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11256                              VT.getVectorNumElements()/2);
11257
11258   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11259   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11260
11261   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11262 }
11263
11264 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11265                                         SelectionDAG &DAG) {
11266   MVT VT = Op->getSimpleValueType(0);
11267   SDValue In = Op->getOperand(0);
11268   MVT InVT = In.getSimpleValueType();
11269   SDLoc DL(Op);
11270   unsigned int NumElts = VT.getVectorNumElements();
11271   if (NumElts != 8 && NumElts != 16)
11272     return SDValue();
11273
11274   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11275     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11276
11277   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11278   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11279   // Now we have only mask extension
11280   assert(InVT.getVectorElementType() == MVT::i1);
11281   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11282   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11283   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11284   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11285   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11286                            MachinePointerInfo::getConstantPool(),
11287                            false, false, false, Alignment);
11288
11289   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11290   if (VT.is512BitVector())
11291     return Brcst;
11292   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11293 }
11294
11295 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11296                                SelectionDAG &DAG) {
11297   if (Subtarget->hasFp256()) {
11298     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11299     if (Res.getNode())
11300       return Res;
11301   }
11302
11303   return SDValue();
11304 }
11305
11306 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11307                                 SelectionDAG &DAG) {
11308   SDLoc DL(Op);
11309   MVT VT = Op.getSimpleValueType();
11310   SDValue In = Op.getOperand(0);
11311   MVT SVT = In.getSimpleValueType();
11312
11313   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11314     return LowerZERO_EXTEND_AVX512(Op, DAG);
11315
11316   if (Subtarget->hasFp256()) {
11317     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11318     if (Res.getNode())
11319       return Res;
11320   }
11321
11322   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11323          VT.getVectorNumElements() != SVT.getVectorNumElements());
11324   return SDValue();
11325 }
11326
11327 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11328   SDLoc DL(Op);
11329   MVT VT = Op.getSimpleValueType();
11330   SDValue In = Op.getOperand(0);
11331   MVT InVT = In.getSimpleValueType();
11332
11333   if (VT == MVT::i1) {
11334     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11335            "Invalid scalar TRUNCATE operation");
11336     if (InVT == MVT::i32)
11337       return SDValue();
11338     if (InVT.getSizeInBits() == 64)
11339       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11340     else if (InVT.getSizeInBits() < 32)
11341       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11342     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11343   }
11344   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11345          "Invalid TRUNCATE operation");
11346
11347   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11348     if (VT.getVectorElementType().getSizeInBits() >=8)
11349       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11350
11351     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11352     unsigned NumElts = InVT.getVectorNumElements();
11353     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11354     if (InVT.getSizeInBits() < 512) {
11355       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11356       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11357       InVT = ExtVT;
11358     }
11359     
11360     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11361     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11362     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11363     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11364     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11365                            MachinePointerInfo::getConstantPool(),
11366                            false, false, false, Alignment);
11367     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11368     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11369     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11370   }
11371
11372   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11373     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11374     if (Subtarget->hasInt256()) {
11375       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11376       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11377       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11378                                 ShufMask);
11379       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11380                          DAG.getIntPtrConstant(0));
11381     }
11382
11383     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11384                                DAG.getIntPtrConstant(0));
11385     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11386                                DAG.getIntPtrConstant(2));
11387     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11388     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11389     static const int ShufMask[] = {0, 2, 4, 6};
11390     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11391   }
11392
11393   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11394     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11395     if (Subtarget->hasInt256()) {
11396       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11397
11398       SmallVector<SDValue,32> pshufbMask;
11399       for (unsigned i = 0; i < 2; ++i) {
11400         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11401         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11402         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11403         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11404         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11405         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11406         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11407         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11408         for (unsigned j = 0; j < 8; ++j)
11409           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11410       }
11411       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11412       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11413       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11414
11415       static const int ShufMask[] = {0,  2,  -1,  -1};
11416       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11417                                 &ShufMask[0]);
11418       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11419                        DAG.getIntPtrConstant(0));
11420       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11421     }
11422
11423     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11424                                DAG.getIntPtrConstant(0));
11425
11426     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11427                                DAG.getIntPtrConstant(4));
11428
11429     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11430     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11431
11432     // The PSHUFB mask:
11433     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11434                                    -1, -1, -1, -1, -1, -1, -1, -1};
11435
11436     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11437     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11438     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11439
11440     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11441     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11442
11443     // The MOVLHPS Mask:
11444     static const int ShufMask2[] = {0, 1, 4, 5};
11445     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11446     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11447   }
11448
11449   // Handle truncation of V256 to V128 using shuffles.
11450   if (!VT.is128BitVector() || !InVT.is256BitVector())
11451     return SDValue();
11452
11453   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11454
11455   unsigned NumElems = VT.getVectorNumElements();
11456   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11457
11458   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11459   // Prepare truncation shuffle mask
11460   for (unsigned i = 0; i != NumElems; ++i)
11461     MaskVec[i] = i * 2;
11462   SDValue V = DAG.getVectorShuffle(NVT, DL,
11463                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11464                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11465   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11466                      DAG.getIntPtrConstant(0));
11467 }
11468
11469 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11470                                            SelectionDAG &DAG) const {
11471   assert(!Op.getSimpleValueType().isVector());
11472
11473   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11474     /*IsSigned=*/ true, /*IsReplace=*/ false);
11475   SDValue FIST = Vals.first, StackSlot = Vals.second;
11476   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11477   if (!FIST.getNode()) return Op;
11478
11479   if (StackSlot.getNode())
11480     // Load the result.
11481     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11482                        FIST, StackSlot, MachinePointerInfo(),
11483                        false, false, false, 0);
11484
11485   // The node is the result.
11486   return FIST;
11487 }
11488
11489 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11490                                            SelectionDAG &DAG) const {
11491   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11492     /*IsSigned=*/ false, /*IsReplace=*/ false);
11493   SDValue FIST = Vals.first, StackSlot = Vals.second;
11494   assert(FIST.getNode() && "Unexpected failure");
11495
11496   if (StackSlot.getNode())
11497     // Load the result.
11498     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11499                        FIST, StackSlot, MachinePointerInfo(),
11500                        false, false, false, 0);
11501
11502   // The node is the result.
11503   return FIST;
11504 }
11505
11506 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11507   SDLoc DL(Op);
11508   MVT VT = Op.getSimpleValueType();
11509   SDValue In = Op.getOperand(0);
11510   MVT SVT = In.getSimpleValueType();
11511
11512   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11513
11514   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11515                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11516                                  In, DAG.getUNDEF(SVT)));
11517 }
11518
11519 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11520   LLVMContext *Context = DAG.getContext();
11521   SDLoc dl(Op);
11522   MVT VT = Op.getSimpleValueType();
11523   MVT EltVT = VT;
11524   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11525   if (VT.isVector()) {
11526     EltVT = VT.getVectorElementType();
11527     NumElts = VT.getVectorNumElements();
11528   }
11529   Constant *C;
11530   if (EltVT == MVT::f64)
11531     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11532                                           APInt(64, ~(1ULL << 63))));
11533   else
11534     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11535                                           APInt(32, ~(1U << 31))));
11536   C = ConstantVector::getSplat(NumElts, C);
11537   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11538   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11539   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11540   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11541                              MachinePointerInfo::getConstantPool(),
11542                              false, false, false, Alignment);
11543   if (VT.isVector()) {
11544     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11545     return DAG.getNode(ISD::BITCAST, dl, VT,
11546                        DAG.getNode(ISD::AND, dl, ANDVT,
11547                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11548                                                Op.getOperand(0)),
11549                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11550   }
11551   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11552 }
11553
11554 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11555   LLVMContext *Context = DAG.getContext();
11556   SDLoc dl(Op);
11557   MVT VT = Op.getSimpleValueType();
11558   MVT EltVT = VT;
11559   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11560   if (VT.isVector()) {
11561     EltVT = VT.getVectorElementType();
11562     NumElts = VT.getVectorNumElements();
11563   }
11564   Constant *C;
11565   if (EltVT == MVT::f64)
11566     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11567                                           APInt(64, 1ULL << 63)));
11568   else
11569     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11570                                           APInt(32, 1U << 31)));
11571   C = ConstantVector::getSplat(NumElts, C);
11572   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11573   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11574   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11575   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11576                              MachinePointerInfo::getConstantPool(),
11577                              false, false, false, Alignment);
11578   if (VT.isVector()) {
11579     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11580     return DAG.getNode(ISD::BITCAST, dl, VT,
11581                        DAG.getNode(ISD::XOR, dl, XORVT,
11582                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11583                                                Op.getOperand(0)),
11584                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11585   }
11586
11587   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11588 }
11589
11590 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11591   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11592   LLVMContext *Context = DAG.getContext();
11593   SDValue Op0 = Op.getOperand(0);
11594   SDValue Op1 = Op.getOperand(1);
11595   SDLoc dl(Op);
11596   MVT VT = Op.getSimpleValueType();
11597   MVT SrcVT = Op1.getSimpleValueType();
11598
11599   // If second operand is smaller, extend it first.
11600   if (SrcVT.bitsLT(VT)) {
11601     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11602     SrcVT = VT;
11603   }
11604   // And if it is bigger, shrink it first.
11605   if (SrcVT.bitsGT(VT)) {
11606     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11607     SrcVT = VT;
11608   }
11609
11610   // At this point the operands and the result should have the same
11611   // type, and that won't be f80 since that is not custom lowered.
11612
11613   // First get the sign bit of second operand.
11614   SmallVector<Constant*,4> CV;
11615   if (SrcVT == MVT::f64) {
11616     const fltSemantics &Sem = APFloat::IEEEdouble;
11617     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11618     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11619   } else {
11620     const fltSemantics &Sem = APFloat::IEEEsingle;
11621     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11622     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11623     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11624     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11625   }
11626   Constant *C = ConstantVector::get(CV);
11627   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11628   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11629                               MachinePointerInfo::getConstantPool(),
11630                               false, false, false, 16);
11631   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11632
11633   // Shift sign bit right or left if the two operands have different types.
11634   if (SrcVT.bitsGT(VT)) {
11635     // Op0 is MVT::f32, Op1 is MVT::f64.
11636     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11637     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11638                           DAG.getConstant(32, MVT::i32));
11639     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11640     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11641                           DAG.getIntPtrConstant(0));
11642   }
11643
11644   // Clear first operand sign bit.
11645   CV.clear();
11646   if (VT == MVT::f64) {
11647     const fltSemantics &Sem = APFloat::IEEEdouble;
11648     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11649                                                    APInt(64, ~(1ULL << 63)))));
11650     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11651   } else {
11652     const fltSemantics &Sem = APFloat::IEEEsingle;
11653     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11654                                                    APInt(32, ~(1U << 31)))));
11655     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11656     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11657     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11658   }
11659   C = ConstantVector::get(CV);
11660   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11661   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11662                               MachinePointerInfo::getConstantPool(),
11663                               false, false, false, 16);
11664   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11665
11666   // Or the value with the sign bit.
11667   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11668 }
11669
11670 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11671   SDValue N0 = Op.getOperand(0);
11672   SDLoc dl(Op);
11673   MVT VT = Op.getSimpleValueType();
11674
11675   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11676   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11677                                   DAG.getConstant(1, VT));
11678   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11679 }
11680
11681 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11682 //
11683 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11684                                       SelectionDAG &DAG) {
11685   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11686
11687   if (!Subtarget->hasSSE41())
11688     return SDValue();
11689
11690   if (!Op->hasOneUse())
11691     return SDValue();
11692
11693   SDNode *N = Op.getNode();
11694   SDLoc DL(N);
11695
11696   SmallVector<SDValue, 8> Opnds;
11697   DenseMap<SDValue, unsigned> VecInMap;
11698   SmallVector<SDValue, 8> VecIns;
11699   EVT VT = MVT::Other;
11700
11701   // Recognize a special case where a vector is casted into wide integer to
11702   // test all 0s.
11703   Opnds.push_back(N->getOperand(0));
11704   Opnds.push_back(N->getOperand(1));
11705
11706   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11707     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11708     // BFS traverse all OR'd operands.
11709     if (I->getOpcode() == ISD::OR) {
11710       Opnds.push_back(I->getOperand(0));
11711       Opnds.push_back(I->getOperand(1));
11712       // Re-evaluate the number of nodes to be traversed.
11713       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11714       continue;
11715     }
11716
11717     // Quit if a non-EXTRACT_VECTOR_ELT
11718     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11719       return SDValue();
11720
11721     // Quit if without a constant index.
11722     SDValue Idx = I->getOperand(1);
11723     if (!isa<ConstantSDNode>(Idx))
11724       return SDValue();
11725
11726     SDValue ExtractedFromVec = I->getOperand(0);
11727     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11728     if (M == VecInMap.end()) {
11729       VT = ExtractedFromVec.getValueType();
11730       // Quit if not 128/256-bit vector.
11731       if (!VT.is128BitVector() && !VT.is256BitVector())
11732         return SDValue();
11733       // Quit if not the same type.
11734       if (VecInMap.begin() != VecInMap.end() &&
11735           VT != VecInMap.begin()->first.getValueType())
11736         return SDValue();
11737       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11738       VecIns.push_back(ExtractedFromVec);
11739     }
11740     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11741   }
11742
11743   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11744          "Not extracted from 128-/256-bit vector.");
11745
11746   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11747
11748   for (DenseMap<SDValue, unsigned>::const_iterator
11749         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11750     // Quit if not all elements are used.
11751     if (I->second != FullMask)
11752       return SDValue();
11753   }
11754
11755   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11756
11757   // Cast all vectors into TestVT for PTEST.
11758   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11759     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11760
11761   // If more than one full vectors are evaluated, OR them first before PTEST.
11762   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11763     // Each iteration will OR 2 nodes and append the result until there is only
11764     // 1 node left, i.e. the final OR'd value of all vectors.
11765     SDValue LHS = VecIns[Slot];
11766     SDValue RHS = VecIns[Slot + 1];
11767     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11768   }
11769
11770   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11771                      VecIns.back(), VecIns.back());
11772 }
11773
11774 /// \brief return true if \c Op has a use that doesn't just read flags.
11775 static bool hasNonFlagsUse(SDValue Op) {
11776   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11777        ++UI) {
11778     SDNode *User = *UI;
11779     unsigned UOpNo = UI.getOperandNo();
11780     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11781       // Look pass truncate.
11782       UOpNo = User->use_begin().getOperandNo();
11783       User = *User->use_begin();
11784     }
11785
11786     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11787         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11788       return true;
11789   }
11790   return false;
11791 }
11792
11793 /// Emit nodes that will be selected as "test Op0,Op0", or something
11794 /// equivalent.
11795 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11796                                     SelectionDAG &DAG) const {
11797   if (Op.getValueType() == MVT::i1)
11798     // KORTEST instruction should be selected
11799     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11800                        DAG.getConstant(0, Op.getValueType()));
11801
11802   // CF and OF aren't always set the way we want. Determine which
11803   // of these we need.
11804   bool NeedCF = false;
11805   bool NeedOF = false;
11806   switch (X86CC) {
11807   default: break;
11808   case X86::COND_A: case X86::COND_AE:
11809   case X86::COND_B: case X86::COND_BE:
11810     NeedCF = true;
11811     break;
11812   case X86::COND_G: case X86::COND_GE:
11813   case X86::COND_L: case X86::COND_LE:
11814   case X86::COND_O: case X86::COND_NO: {
11815     // Check if we really need to set the
11816     // Overflow flag. If NoSignedWrap is present
11817     // that is not actually needed.
11818     switch (Op->getOpcode()) {
11819     case ISD::ADD:
11820     case ISD::SUB:
11821     case ISD::MUL:
11822     case ISD::SHL: {
11823       const BinaryWithFlagsSDNode *BinNode =
11824           cast<BinaryWithFlagsSDNode>(Op.getNode());
11825       if (BinNode->hasNoSignedWrap())
11826         break;
11827     }
11828     default:
11829       NeedOF = true;
11830       break;
11831     }
11832     break;
11833   }
11834   }
11835   // See if we can use the EFLAGS value from the operand instead of
11836   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11837   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11838   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11839     // Emit a CMP with 0, which is the TEST pattern.
11840     //if (Op.getValueType() == MVT::i1)
11841     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11842     //                     DAG.getConstant(0, MVT::i1));
11843     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11844                        DAG.getConstant(0, Op.getValueType()));
11845   }
11846   unsigned Opcode = 0;
11847   unsigned NumOperands = 0;
11848
11849   // Truncate operations may prevent the merge of the SETCC instruction
11850   // and the arithmetic instruction before it. Attempt to truncate the operands
11851   // of the arithmetic instruction and use a reduced bit-width instruction.
11852   bool NeedTruncation = false;
11853   SDValue ArithOp = Op;
11854   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11855     SDValue Arith = Op->getOperand(0);
11856     // Both the trunc and the arithmetic op need to have one user each.
11857     if (Arith->hasOneUse())
11858       switch (Arith.getOpcode()) {
11859         default: break;
11860         case ISD::ADD:
11861         case ISD::SUB:
11862         case ISD::AND:
11863         case ISD::OR:
11864         case ISD::XOR: {
11865           NeedTruncation = true;
11866           ArithOp = Arith;
11867         }
11868       }
11869   }
11870
11871   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11872   // which may be the result of a CAST.  We use the variable 'Op', which is the
11873   // non-casted variable when we check for possible users.
11874   switch (ArithOp.getOpcode()) {
11875   case ISD::ADD:
11876     // Due to an isel shortcoming, be conservative if this add is likely to be
11877     // selected as part of a load-modify-store instruction. When the root node
11878     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11879     // uses of other nodes in the match, such as the ADD in this case. This
11880     // leads to the ADD being left around and reselected, with the result being
11881     // two adds in the output.  Alas, even if none our users are stores, that
11882     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11883     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11884     // climbing the DAG back to the root, and it doesn't seem to be worth the
11885     // effort.
11886     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11887          UE = Op.getNode()->use_end(); UI != UE; ++UI)
11888       if (UI->getOpcode() != ISD::CopyToReg &&
11889           UI->getOpcode() != ISD::SETCC &&
11890           UI->getOpcode() != ISD::STORE)
11891         goto default_case;
11892
11893     if (ConstantSDNode *C =
11894         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11895       // An add of one will be selected as an INC.
11896       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11897         Opcode = X86ISD::INC;
11898         NumOperands = 1;
11899         break;
11900       }
11901
11902       // An add of negative one (subtract of one) will be selected as a DEC.
11903       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11904         Opcode = X86ISD::DEC;
11905         NumOperands = 1;
11906         break;
11907       }
11908     }
11909
11910     // Otherwise use a regular EFLAGS-setting add.
11911     Opcode = X86ISD::ADD;
11912     NumOperands = 2;
11913     break;
11914   case ISD::SHL:
11915   case ISD::SRL:
11916     // If we have a constant logical shift that's only used in a comparison
11917     // against zero turn it into an equivalent AND. This allows turning it into
11918     // a TEST instruction later.
11919     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11920         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11921       EVT VT = Op.getValueType();
11922       unsigned BitWidth = VT.getSizeInBits();
11923       unsigned ShAmt = Op->getConstantOperandVal(1);
11924       if (ShAmt >= BitWidth) // Avoid undefined shifts.
11925         break;
11926       APInt Mask = ArithOp.getOpcode() == ISD::SRL
11927                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11928                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11929       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11930         break;
11931       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11932                                 DAG.getConstant(Mask, VT));
11933       DAG.ReplaceAllUsesWith(Op, New);
11934       Op = New;
11935     }
11936     break;
11937
11938   case ISD::AND:
11939     // If the primary and result isn't used, don't bother using X86ISD::AND,
11940     // because a TEST instruction will be better.
11941     if (!hasNonFlagsUse(Op))
11942       break;
11943     // FALL THROUGH
11944   case ISD::SUB:
11945   case ISD::OR:
11946   case ISD::XOR:
11947     // Due to the ISEL shortcoming noted above, be conservative if this op is
11948     // likely to be selected as part of a load-modify-store instruction.
11949     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11950            UE = Op.getNode()->use_end(); UI != UE; ++UI)
11951       if (UI->getOpcode() == ISD::STORE)
11952         goto default_case;
11953
11954     // Otherwise use a regular EFLAGS-setting instruction.
11955     switch (ArithOp.getOpcode()) {
11956     default: llvm_unreachable("unexpected operator!");
11957     case ISD::SUB: Opcode = X86ISD::SUB; break;
11958     case ISD::XOR: Opcode = X86ISD::XOR; break;
11959     case ISD::AND: Opcode = X86ISD::AND; break;
11960     case ISD::OR: {
11961       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11962         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11963         if (EFLAGS.getNode())
11964           return EFLAGS;
11965       }
11966       Opcode = X86ISD::OR;
11967       break;
11968     }
11969     }
11970
11971     NumOperands = 2;
11972     break;
11973   case X86ISD::ADD:
11974   case X86ISD::SUB:
11975   case X86ISD::INC:
11976   case X86ISD::DEC:
11977   case X86ISD::OR:
11978   case X86ISD::XOR:
11979   case X86ISD::AND:
11980     return SDValue(Op.getNode(), 1);
11981   default:
11982   default_case:
11983     break;
11984   }
11985
11986   // If we found that truncation is beneficial, perform the truncation and
11987   // update 'Op'.
11988   if (NeedTruncation) {
11989     EVT VT = Op.getValueType();
11990     SDValue WideVal = Op->getOperand(0);
11991     EVT WideVT = WideVal.getValueType();
11992     unsigned ConvertedOp = 0;
11993     // Use a target machine opcode to prevent further DAGCombine
11994     // optimizations that may separate the arithmetic operations
11995     // from the setcc node.
11996     switch (WideVal.getOpcode()) {
11997       default: break;
11998       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11999       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12000       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12001       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12002       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12003     }
12004
12005     if (ConvertedOp) {
12006       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12007       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12008         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12009         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12010         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12011       }
12012     }
12013   }
12014
12015   if (Opcode == 0)
12016     // Emit a CMP with 0, which is the TEST pattern.
12017     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12018                        DAG.getConstant(0, Op.getValueType()));
12019
12020   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12021   SmallVector<SDValue, 4> Ops;
12022   for (unsigned i = 0; i != NumOperands; ++i)
12023     Ops.push_back(Op.getOperand(i));
12024
12025   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12026   DAG.ReplaceAllUsesWith(Op, New);
12027   return SDValue(New.getNode(), 1);
12028 }
12029
12030 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12031 /// equivalent.
12032 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12033                                    SDLoc dl, SelectionDAG &DAG) const {
12034   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12035     if (C->getAPIntValue() == 0)
12036       return EmitTest(Op0, X86CC, dl, DAG);
12037
12038      if (Op0.getValueType() == MVT::i1)
12039        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12040   }
12041  
12042   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12043        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12044     // Do the comparison at i32 if it's smaller, besides the Atom case. 
12045     // This avoids subregister aliasing issues. Keep the smaller reference 
12046     // if we're optimizing for size, however, as that'll allow better folding 
12047     // of memory operations.
12048     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12049         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12050              AttributeSet::FunctionIndex, Attribute::MinSize) &&
12051         !Subtarget->isAtom()) {
12052       unsigned ExtendOp =
12053           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12054       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12055       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12056     }
12057     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12058     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12059     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12060                               Op0, Op1);
12061     return SDValue(Sub.getNode(), 1);
12062   }
12063   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12064 }
12065
12066 /// Convert a comparison if required by the subtarget.
12067 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12068                                                  SelectionDAG &DAG) const {
12069   // If the subtarget does not support the FUCOMI instruction, floating-point
12070   // comparisons have to be converted.
12071   if (Subtarget->hasCMov() ||
12072       Cmp.getOpcode() != X86ISD::CMP ||
12073       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12074       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12075     return Cmp;
12076
12077   // The instruction selector will select an FUCOM instruction instead of
12078   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12079   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12080   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12081   SDLoc dl(Cmp);
12082   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12083   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12084   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12085                             DAG.getConstant(8, MVT::i8));
12086   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12087   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12088 }
12089
12090 static bool isAllOnes(SDValue V) {
12091   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12092   return C && C->isAllOnesValue();
12093 }
12094
12095 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12096 /// if it's possible.
12097 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12098                                      SDLoc dl, SelectionDAG &DAG) const {
12099   SDValue Op0 = And.getOperand(0);
12100   SDValue Op1 = And.getOperand(1);
12101   if (Op0.getOpcode() == ISD::TRUNCATE)
12102     Op0 = Op0.getOperand(0);
12103   if (Op1.getOpcode() == ISD::TRUNCATE)
12104     Op1 = Op1.getOperand(0);
12105
12106   SDValue LHS, RHS;
12107   if (Op1.getOpcode() == ISD::SHL)
12108     std::swap(Op0, Op1);
12109   if (Op0.getOpcode() == ISD::SHL) {
12110     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12111       if (And00C->getZExtValue() == 1) {
12112         // If we looked past a truncate, check that it's only truncating away
12113         // known zeros.
12114         unsigned BitWidth = Op0.getValueSizeInBits();
12115         unsigned AndBitWidth = And.getValueSizeInBits();
12116         if (BitWidth > AndBitWidth) {
12117           APInt Zeros, Ones;
12118           DAG.computeKnownBits(Op0, Zeros, Ones);
12119           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12120             return SDValue();
12121         }
12122         LHS = Op1;
12123         RHS = Op0.getOperand(1);
12124       }
12125   } else if (Op1.getOpcode() == ISD::Constant) {
12126     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12127     uint64_t AndRHSVal = AndRHS->getZExtValue();
12128     SDValue AndLHS = Op0;
12129
12130     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12131       LHS = AndLHS.getOperand(0);
12132       RHS = AndLHS.getOperand(1);
12133     }
12134
12135     // Use BT if the immediate can't be encoded in a TEST instruction.
12136     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12137       LHS = AndLHS;
12138       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12139     }
12140   }
12141
12142   if (LHS.getNode()) {
12143     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12144     // instruction.  Since the shift amount is in-range-or-undefined, we know
12145     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12146     // the encoding for the i16 version is larger than the i32 version.
12147     // Also promote i16 to i32 for performance / code size reason.
12148     if (LHS.getValueType() == MVT::i8 ||
12149         LHS.getValueType() == MVT::i16)
12150       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12151
12152     // If the operand types disagree, extend the shift amount to match.  Since
12153     // BT ignores high bits (like shifts) we can use anyextend.
12154     if (LHS.getValueType() != RHS.getValueType())
12155       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12156
12157     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12158     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12159     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12160                        DAG.getConstant(Cond, MVT::i8), BT);
12161   }
12162
12163   return SDValue();
12164 }
12165
12166 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12167 /// mask CMPs.
12168 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12169                               SDValue &Op1) {
12170   unsigned SSECC;
12171   bool Swap = false;
12172
12173   // SSE Condition code mapping:
12174   //  0 - EQ
12175   //  1 - LT
12176   //  2 - LE
12177   //  3 - UNORD
12178   //  4 - NEQ
12179   //  5 - NLT
12180   //  6 - NLE
12181   //  7 - ORD
12182   switch (SetCCOpcode) {
12183   default: llvm_unreachable("Unexpected SETCC condition");
12184   case ISD::SETOEQ:
12185   case ISD::SETEQ:  SSECC = 0; break;
12186   case ISD::SETOGT:
12187   case ISD::SETGT:  Swap = true; // Fallthrough
12188   case ISD::SETLT:
12189   case ISD::SETOLT: SSECC = 1; break;
12190   case ISD::SETOGE:
12191   case ISD::SETGE:  Swap = true; // Fallthrough
12192   case ISD::SETLE:
12193   case ISD::SETOLE: SSECC = 2; break;
12194   case ISD::SETUO:  SSECC = 3; break;
12195   case ISD::SETUNE:
12196   case ISD::SETNE:  SSECC = 4; break;
12197   case ISD::SETULE: Swap = true; // Fallthrough
12198   case ISD::SETUGE: SSECC = 5; break;
12199   case ISD::SETULT: Swap = true; // Fallthrough
12200   case ISD::SETUGT: SSECC = 6; break;
12201   case ISD::SETO:   SSECC = 7; break;
12202   case ISD::SETUEQ:
12203   case ISD::SETONE: SSECC = 8; break;
12204   }
12205   if (Swap)
12206     std::swap(Op0, Op1);
12207
12208   return SSECC;
12209 }
12210
12211 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12212 // ones, and then concatenate the result back.
12213 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12214   MVT VT = Op.getSimpleValueType();
12215
12216   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12217          "Unsupported value type for operation");
12218
12219   unsigned NumElems = VT.getVectorNumElements();
12220   SDLoc dl(Op);
12221   SDValue CC = Op.getOperand(2);
12222
12223   // Extract the LHS vectors
12224   SDValue LHS = Op.getOperand(0);
12225   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12226   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12227
12228   // Extract the RHS vectors
12229   SDValue RHS = Op.getOperand(1);
12230   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12231   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12232
12233   // Issue the operation on the smaller types and concatenate the result back
12234   MVT EltVT = VT.getVectorElementType();
12235   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12236   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12237                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12238                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12239 }
12240
12241 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12242                                      const X86Subtarget *Subtarget) {
12243   SDValue Op0 = Op.getOperand(0);
12244   SDValue Op1 = Op.getOperand(1);
12245   SDValue CC = Op.getOperand(2);
12246   MVT VT = Op.getSimpleValueType();
12247   SDLoc dl(Op);
12248
12249   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12250          Op.getValueType().getScalarType() == MVT::i1 &&
12251          "Cannot set masked compare for this operation");
12252
12253   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12254   unsigned  Opc = 0;
12255   bool Unsigned = false;
12256   bool Swap = false;
12257   unsigned SSECC;
12258   switch (SetCCOpcode) {
12259   default: llvm_unreachable("Unexpected SETCC condition");
12260   case ISD::SETNE:  SSECC = 4; break;
12261   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12262   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12263   case ISD::SETLT:  Swap = true; //fall-through
12264   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12265   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12266   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12267   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12268   case ISD::SETULE: Unsigned = true; //fall-through
12269   case ISD::SETLE:  SSECC = 2; break;
12270   }
12271
12272   if (Swap)
12273     std::swap(Op0, Op1);
12274   if (Opc)
12275     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12276   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12277   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12278                      DAG.getConstant(SSECC, MVT::i8));
12279 }
12280
12281 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12282 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12283 /// return an empty value.
12284 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12285 {
12286   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12287   if (!BV)
12288     return SDValue();
12289
12290   MVT VT = Op1.getSimpleValueType();
12291   MVT EVT = VT.getVectorElementType();
12292   unsigned n = VT.getVectorNumElements();
12293   SmallVector<SDValue, 8> ULTOp1;
12294
12295   for (unsigned i = 0; i < n; ++i) {
12296     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12297     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12298       return SDValue();
12299
12300     // Avoid underflow.
12301     APInt Val = Elt->getAPIntValue();
12302     if (Val == 0)
12303       return SDValue();
12304
12305     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12306   }
12307
12308   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12309 }
12310
12311 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12312                            SelectionDAG &DAG) {
12313   SDValue Op0 = Op.getOperand(0);
12314   SDValue Op1 = Op.getOperand(1);
12315   SDValue CC = Op.getOperand(2);
12316   MVT VT = Op.getSimpleValueType();
12317   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12318   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12319   SDLoc dl(Op);
12320
12321   if (isFP) {
12322 #ifndef NDEBUG
12323     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12324     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12325 #endif
12326
12327     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12328     unsigned Opc = X86ISD::CMPP;
12329     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12330       assert(VT.getVectorNumElements() <= 16);
12331       Opc = X86ISD::CMPM;
12332     }
12333     // In the two special cases we can't handle, emit two comparisons.
12334     if (SSECC == 8) {
12335       unsigned CC0, CC1;
12336       unsigned CombineOpc;
12337       if (SetCCOpcode == ISD::SETUEQ) {
12338         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12339       } else {
12340         assert(SetCCOpcode == ISD::SETONE);
12341         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12342       }
12343
12344       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12345                                  DAG.getConstant(CC0, MVT::i8));
12346       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12347                                  DAG.getConstant(CC1, MVT::i8));
12348       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12349     }
12350     // Handle all other FP comparisons here.
12351     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12352                        DAG.getConstant(SSECC, MVT::i8));
12353   }
12354
12355   // Break 256-bit integer vector compare into smaller ones.
12356   if (VT.is256BitVector() && !Subtarget->hasInt256())
12357     return Lower256IntVSETCC(Op, DAG);
12358
12359   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12360   EVT OpVT = Op1.getValueType();
12361   if (Subtarget->hasAVX512()) {
12362     if (Op1.getValueType().is512BitVector() ||
12363         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12364       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12365
12366     // In AVX-512 architecture setcc returns mask with i1 elements,
12367     // But there is no compare instruction for i8 and i16 elements.
12368     // We are not talking about 512-bit operands in this case, these
12369     // types are illegal.
12370     if (MaskResult &&
12371         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12372          OpVT.getVectorElementType().getSizeInBits() >= 8))
12373       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12374                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12375   }
12376
12377   // We are handling one of the integer comparisons here.  Since SSE only has
12378   // GT and EQ comparisons for integer, swapping operands and multiple
12379   // operations may be required for some comparisons.
12380   unsigned Opc;
12381   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12382   bool Subus = false;
12383
12384   switch (SetCCOpcode) {
12385   default: llvm_unreachable("Unexpected SETCC condition");
12386   case ISD::SETNE:  Invert = true;
12387   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12388   case ISD::SETLT:  Swap = true;
12389   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12390   case ISD::SETGE:  Swap = true;
12391   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12392                     Invert = true; break;
12393   case ISD::SETULT: Swap = true;
12394   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12395                     FlipSigns = true; break;
12396   case ISD::SETUGE: Swap = true;
12397   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12398                     FlipSigns = true; Invert = true; break;
12399   }
12400
12401   // Special case: Use min/max operations for SETULE/SETUGE
12402   MVT VET = VT.getVectorElementType();
12403   bool hasMinMax =
12404        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12405     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12406
12407   if (hasMinMax) {
12408     switch (SetCCOpcode) {
12409     default: break;
12410     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12411     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12412     }
12413
12414     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12415   }
12416
12417   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12418   if (!MinMax && hasSubus) {
12419     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12420     // Op0 u<= Op1:
12421     //   t = psubus Op0, Op1
12422     //   pcmpeq t, <0..0>
12423     switch (SetCCOpcode) {
12424     default: break;
12425     case ISD::SETULT: {
12426       // If the comparison is against a constant we can turn this into a
12427       // setule.  With psubus, setule does not require a swap.  This is
12428       // beneficial because the constant in the register is no longer
12429       // destructed as the destination so it can be hoisted out of a loop.
12430       // Only do this pre-AVX since vpcmp* is no longer destructive.
12431       if (Subtarget->hasAVX())
12432         break;
12433       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12434       if (ULEOp1.getNode()) {
12435         Op1 = ULEOp1;
12436         Subus = true; Invert = false; Swap = false;
12437       }
12438       break;
12439     }
12440     // Psubus is better than flip-sign because it requires no inversion.
12441     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12442     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12443     }
12444
12445     if (Subus) {
12446       Opc = X86ISD::SUBUS;
12447       FlipSigns = false;
12448     }
12449   }
12450
12451   if (Swap)
12452     std::swap(Op0, Op1);
12453
12454   // Check that the operation in question is available (most are plain SSE2,
12455   // but PCMPGTQ and PCMPEQQ have different requirements).
12456   if (VT == MVT::v2i64) {
12457     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12458       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12459
12460       // First cast everything to the right type.
12461       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12462       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12463
12464       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12465       // bits of the inputs before performing those operations. The lower
12466       // compare is always unsigned.
12467       SDValue SB;
12468       if (FlipSigns) {
12469         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12470       } else {
12471         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12472         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12473         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12474                          Sign, Zero, Sign, Zero);
12475       }
12476       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12477       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12478
12479       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12480       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12481       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12482
12483       // Create masks for only the low parts/high parts of the 64 bit integers.
12484       static const int MaskHi[] = { 1, 1, 3, 3 };
12485       static const int MaskLo[] = { 0, 0, 2, 2 };
12486       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12487       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12488       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12489
12490       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12491       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12492
12493       if (Invert)
12494         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12495
12496       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12497     }
12498
12499     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12500       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12501       // pcmpeqd + pshufd + pand.
12502       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12503
12504       // First cast everything to the right type.
12505       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12506       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12507
12508       // Do the compare.
12509       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12510
12511       // Make sure the lower and upper halves are both all-ones.
12512       static const int Mask[] = { 1, 0, 3, 2 };
12513       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12514       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12515
12516       if (Invert)
12517         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12518
12519       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12520     }
12521   }
12522
12523   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12524   // bits of the inputs before performing those operations.
12525   if (FlipSigns) {
12526     EVT EltVT = VT.getVectorElementType();
12527     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12528     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12529     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12530   }
12531
12532   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12533
12534   // If the logical-not of the result is required, perform that now.
12535   if (Invert)
12536     Result = DAG.getNOT(dl, Result, VT);
12537
12538   if (MinMax)
12539     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12540
12541   if (Subus)
12542     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12543                          getZeroVector(VT, Subtarget, DAG, dl));
12544
12545   return Result;
12546 }
12547
12548 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12549
12550   MVT VT = Op.getSimpleValueType();
12551
12552   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12553
12554   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12555          && "SetCC type must be 8-bit or 1-bit integer");
12556   SDValue Op0 = Op.getOperand(0);
12557   SDValue Op1 = Op.getOperand(1);
12558   SDLoc dl(Op);
12559   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12560
12561   // Optimize to BT if possible.
12562   // Lower (X & (1 << N)) == 0 to BT(X, N).
12563   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12564   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12565   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12566       Op1.getOpcode() == ISD::Constant &&
12567       cast<ConstantSDNode>(Op1)->isNullValue() &&
12568       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12569     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12570     if (NewSetCC.getNode())
12571       return NewSetCC;
12572   }
12573
12574   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12575   // these.
12576   if (Op1.getOpcode() == ISD::Constant &&
12577       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12578        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12579       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12580
12581     // If the input is a setcc, then reuse the input setcc or use a new one with
12582     // the inverted condition.
12583     if (Op0.getOpcode() == X86ISD::SETCC) {
12584       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12585       bool Invert = (CC == ISD::SETNE) ^
12586         cast<ConstantSDNode>(Op1)->isNullValue();
12587       if (!Invert)
12588         return Op0;
12589
12590       CCode = X86::GetOppositeBranchCondition(CCode);
12591       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12592                                   DAG.getConstant(CCode, MVT::i8),
12593                                   Op0.getOperand(1));
12594       if (VT == MVT::i1)
12595         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12596       return SetCC;
12597     }
12598   }
12599   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12600       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12601       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12602
12603     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12604     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12605   }
12606
12607   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12608   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12609   if (X86CC == X86::COND_INVALID)
12610     return SDValue();
12611
12612   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12613   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12614   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12615                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12616   if (VT == MVT::i1)
12617     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12618   return SetCC;
12619 }
12620
12621 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12622 static bool isX86LogicalCmp(SDValue Op) {
12623   unsigned Opc = Op.getNode()->getOpcode();
12624   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12625       Opc == X86ISD::SAHF)
12626     return true;
12627   if (Op.getResNo() == 1 &&
12628       (Opc == X86ISD::ADD ||
12629        Opc == X86ISD::SUB ||
12630        Opc == X86ISD::ADC ||
12631        Opc == X86ISD::SBB ||
12632        Opc == X86ISD::SMUL ||
12633        Opc == X86ISD::UMUL ||
12634        Opc == X86ISD::INC ||
12635        Opc == X86ISD::DEC ||
12636        Opc == X86ISD::OR ||
12637        Opc == X86ISD::XOR ||
12638        Opc == X86ISD::AND))
12639     return true;
12640
12641   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12642     return true;
12643
12644   return false;
12645 }
12646
12647 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12648   if (V.getOpcode() != ISD::TRUNCATE)
12649     return false;
12650
12651   SDValue VOp0 = V.getOperand(0);
12652   unsigned InBits = VOp0.getValueSizeInBits();
12653   unsigned Bits = V.getValueSizeInBits();
12654   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12655 }
12656
12657 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12658   bool addTest = true;
12659   SDValue Cond  = Op.getOperand(0);
12660   SDValue Op1 = Op.getOperand(1);
12661   SDValue Op2 = Op.getOperand(2);
12662   SDLoc DL(Op);
12663   EVT VT = Op1.getValueType();
12664   SDValue CC;
12665
12666   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12667   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12668   // sequence later on.
12669   if (Cond.getOpcode() == ISD::SETCC &&
12670       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12671        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12672       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12673     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12674     int SSECC = translateX86FSETCC(
12675         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12676
12677     if (SSECC != 8) {
12678       if (Subtarget->hasAVX512()) {
12679         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12680                                   DAG.getConstant(SSECC, MVT::i8));
12681         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12682       }
12683       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12684                                 DAG.getConstant(SSECC, MVT::i8));
12685       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12686       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12687       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12688     }
12689   }
12690
12691   if (Cond.getOpcode() == ISD::SETCC) {
12692     SDValue NewCond = LowerSETCC(Cond, DAG);
12693     if (NewCond.getNode())
12694       Cond = NewCond;
12695   }
12696
12697   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12698   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12699   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12700   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12701   if (Cond.getOpcode() == X86ISD::SETCC &&
12702       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12703       isZero(Cond.getOperand(1).getOperand(1))) {
12704     SDValue Cmp = Cond.getOperand(1);
12705
12706     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12707
12708     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12709         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12710       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12711
12712       SDValue CmpOp0 = Cmp.getOperand(0);
12713       // Apply further optimizations for special cases
12714       // (select (x != 0), -1, 0) -> neg & sbb
12715       // (select (x == 0), 0, -1) -> neg & sbb
12716       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12717         if (YC->isNullValue() &&
12718             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12719           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12720           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12721                                     DAG.getConstant(0, CmpOp0.getValueType()),
12722                                     CmpOp0);
12723           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12724                                     DAG.getConstant(X86::COND_B, MVT::i8),
12725                                     SDValue(Neg.getNode(), 1));
12726           return Res;
12727         }
12728
12729       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12730                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12731       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12732
12733       SDValue Res =   // Res = 0 or -1.
12734         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12735                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12736
12737       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12738         Res = DAG.getNOT(DL, Res, Res.getValueType());
12739
12740       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12741       if (!N2C || !N2C->isNullValue())
12742         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12743       return Res;
12744     }
12745   }
12746
12747   // Look past (and (setcc_carry (cmp ...)), 1).
12748   if (Cond.getOpcode() == ISD::AND &&
12749       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12750     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12751     if (C && C->getAPIntValue() == 1)
12752       Cond = Cond.getOperand(0);
12753   }
12754
12755   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12756   // setting operand in place of the X86ISD::SETCC.
12757   unsigned CondOpcode = Cond.getOpcode();
12758   if (CondOpcode == X86ISD::SETCC ||
12759       CondOpcode == X86ISD::SETCC_CARRY) {
12760     CC = Cond.getOperand(0);
12761
12762     SDValue Cmp = Cond.getOperand(1);
12763     unsigned Opc = Cmp.getOpcode();
12764     MVT VT = Op.getSimpleValueType();
12765
12766     bool IllegalFPCMov = false;
12767     if (VT.isFloatingPoint() && !VT.isVector() &&
12768         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12769       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12770
12771     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12772         Opc == X86ISD::BT) { // FIXME
12773       Cond = Cmp;
12774       addTest = false;
12775     }
12776   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12777              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12778              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12779               Cond.getOperand(0).getValueType() != MVT::i8)) {
12780     SDValue LHS = Cond.getOperand(0);
12781     SDValue RHS = Cond.getOperand(1);
12782     unsigned X86Opcode;
12783     unsigned X86Cond;
12784     SDVTList VTs;
12785     switch (CondOpcode) {
12786     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12787     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12788     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12789     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12790     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12791     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12792     default: llvm_unreachable("unexpected overflowing operator");
12793     }
12794     if (CondOpcode == ISD::UMULO)
12795       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12796                           MVT::i32);
12797     else
12798       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12799
12800     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12801
12802     if (CondOpcode == ISD::UMULO)
12803       Cond = X86Op.getValue(2);
12804     else
12805       Cond = X86Op.getValue(1);
12806
12807     CC = DAG.getConstant(X86Cond, MVT::i8);
12808     addTest = false;
12809   }
12810
12811   if (addTest) {
12812     // Look pass the truncate if the high bits are known zero.
12813     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12814         Cond = Cond.getOperand(0);
12815
12816     // We know the result of AND is compared against zero. Try to match
12817     // it to BT.
12818     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12819       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12820       if (NewSetCC.getNode()) {
12821         CC = NewSetCC.getOperand(0);
12822         Cond = NewSetCC.getOperand(1);
12823         addTest = false;
12824       }
12825     }
12826   }
12827
12828   if (addTest) {
12829     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12830     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12831   }
12832
12833   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12834   // a <  b ?  0 : -1 -> RES = setcc_carry
12835   // a >= b ? -1 :  0 -> RES = setcc_carry
12836   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12837   if (Cond.getOpcode() == X86ISD::SUB) {
12838     Cond = ConvertCmpIfNecessary(Cond, DAG);
12839     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12840
12841     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12842         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12843       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12844                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12845       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12846         return DAG.getNOT(DL, Res, Res.getValueType());
12847       return Res;
12848     }
12849   }
12850
12851   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12852   // widen the cmov and push the truncate through. This avoids introducing a new
12853   // branch during isel and doesn't add any extensions.
12854   if (Op.getValueType() == MVT::i8 &&
12855       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12856     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12857     if (T1.getValueType() == T2.getValueType() &&
12858         // Blacklist CopyFromReg to avoid partial register stalls.
12859         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12860       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12861       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12862       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12863     }
12864   }
12865
12866   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12867   // condition is true.
12868   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12869   SDValue Ops[] = { Op2, Op1, CC, Cond };
12870   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12871 }
12872
12873 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12874   MVT VT = Op->getSimpleValueType(0);
12875   SDValue In = Op->getOperand(0);
12876   MVT InVT = In.getSimpleValueType();
12877   SDLoc dl(Op);
12878
12879   unsigned int NumElts = VT.getVectorNumElements();
12880   if (NumElts != 8 && NumElts != 16)
12881     return SDValue();
12882
12883   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12884     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12885
12886   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12887   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12888
12889   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12890   Constant *C = ConstantInt::get(*DAG.getContext(),
12891     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12892
12893   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12894   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12895   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12896                           MachinePointerInfo::getConstantPool(),
12897                           false, false, false, Alignment);
12898   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12899   if (VT.is512BitVector())
12900     return Brcst;
12901   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12902 }
12903
12904 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12905                                 SelectionDAG &DAG) {
12906   MVT VT = Op->getSimpleValueType(0);
12907   SDValue In = Op->getOperand(0);
12908   MVT InVT = In.getSimpleValueType();
12909   SDLoc dl(Op);
12910
12911   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12912     return LowerSIGN_EXTEND_AVX512(Op, DAG);
12913
12914   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12915       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12916       (VT != MVT::v16i16 || InVT != MVT::v16i8))
12917     return SDValue();
12918
12919   if (Subtarget->hasInt256())
12920     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12921
12922   // Optimize vectors in AVX mode
12923   // Sign extend  v8i16 to v8i32 and
12924   //              v4i32 to v4i64
12925   //
12926   // Divide input vector into two parts
12927   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12928   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12929   // concat the vectors to original VT
12930
12931   unsigned NumElems = InVT.getVectorNumElements();
12932   SDValue Undef = DAG.getUNDEF(InVT);
12933
12934   SmallVector<int,8> ShufMask1(NumElems, -1);
12935   for (unsigned i = 0; i != NumElems/2; ++i)
12936     ShufMask1[i] = i;
12937
12938   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12939
12940   SmallVector<int,8> ShufMask2(NumElems, -1);
12941   for (unsigned i = 0; i != NumElems/2; ++i)
12942     ShufMask2[i] = i + NumElems/2;
12943
12944   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12945
12946   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12947                                 VT.getVectorNumElements()/2);
12948
12949   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12950   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12951
12952   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12953 }
12954
12955 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
12956 // may emit an illegal shuffle but the expansion is still better than scalar
12957 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
12958 // we'll emit a shuffle and a arithmetic shift.
12959 // TODO: It is possible to support ZExt by zeroing the undef values during
12960 // the shuffle phase or after the shuffle.
12961 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
12962                                  SelectionDAG &DAG) {
12963   MVT RegVT = Op.getSimpleValueType();
12964   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
12965   assert(RegVT.isInteger() &&
12966          "We only custom lower integer vector sext loads.");
12967
12968   // Nothing useful we can do without SSE2 shuffles.
12969   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
12970
12971   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
12972   SDLoc dl(Ld);
12973   EVT MemVT = Ld->getMemoryVT();
12974   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12975   unsigned RegSz = RegVT.getSizeInBits();
12976
12977   ISD::LoadExtType Ext = Ld->getExtensionType();
12978
12979   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
12980          && "Only anyext and sext are currently implemented.");
12981   assert(MemVT != RegVT && "Cannot extend to the same type");
12982   assert(MemVT.isVector() && "Must load a vector from memory");
12983
12984   unsigned NumElems = RegVT.getVectorNumElements();
12985   unsigned MemSz = MemVT.getSizeInBits();
12986   assert(RegSz > MemSz && "Register size must be greater than the mem size");
12987
12988   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
12989     // The only way in which we have a legal 256-bit vector result but not the
12990     // integer 256-bit operations needed to directly lower a sextload is if we
12991     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
12992     // a 128-bit vector and a normal sign_extend to 256-bits that should get
12993     // correctly legalized. We do this late to allow the canonical form of
12994     // sextload to persist throughout the rest of the DAG combiner -- it wants
12995     // to fold together any extensions it can, and so will fuse a sign_extend
12996     // of an sextload into an sextload targeting a wider value.
12997     SDValue Load;
12998     if (MemSz == 128) {
12999       // Just switch this to a normal load.
13000       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13001                                        "it must be a legal 128-bit vector "
13002                                        "type!");
13003       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13004                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13005                   Ld->isInvariant(), Ld->getAlignment());
13006     } else {
13007       assert(MemSz < 128 &&
13008              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13009       // Do an sext load to a 128-bit vector type. We want to use the same
13010       // number of elements, but elements half as wide. This will end up being
13011       // recursively lowered by this routine, but will succeed as we definitely
13012       // have all the necessary features if we're using AVX1.
13013       EVT HalfEltVT =
13014           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13015       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13016       Load =
13017           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13018                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13019                          Ld->isNonTemporal(), Ld->isInvariant(),
13020                          Ld->getAlignment());
13021     }
13022
13023     // Replace chain users with the new chain.
13024     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13025     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13026
13027     // Finally, do a normal sign-extend to the desired register.
13028     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13029   }
13030
13031   // All sizes must be a power of two.
13032   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13033          "Non-power-of-two elements are not custom lowered!");
13034
13035   // Attempt to load the original value using scalar loads.
13036   // Find the largest scalar type that divides the total loaded size.
13037   MVT SclrLoadTy = MVT::i8;
13038   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13039        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13040     MVT Tp = (MVT::SimpleValueType)tp;
13041     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13042       SclrLoadTy = Tp;
13043     }
13044   }
13045
13046   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13047   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13048       (64 <= MemSz))
13049     SclrLoadTy = MVT::f64;
13050
13051   // Calculate the number of scalar loads that we need to perform
13052   // in order to load our vector from memory.
13053   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13054
13055   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13056          "Can only lower sext loads with a single scalar load!");
13057
13058   unsigned loadRegZize = RegSz;
13059   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13060     loadRegZize /= 2;
13061
13062   // Represent our vector as a sequence of elements which are the
13063   // largest scalar that we can load.
13064   EVT LoadUnitVecVT = EVT::getVectorVT(
13065       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13066
13067   // Represent the data using the same element type that is stored in
13068   // memory. In practice, we ''widen'' MemVT.
13069   EVT WideVecVT =
13070       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13071                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13072
13073   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13074          "Invalid vector type");
13075
13076   // We can't shuffle using an illegal type.
13077   assert(TLI.isTypeLegal(WideVecVT) &&
13078          "We only lower types that form legal widened vector types");
13079
13080   SmallVector<SDValue, 8> Chains;
13081   SDValue Ptr = Ld->getBasePtr();
13082   SDValue Increment =
13083       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13084   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13085
13086   for (unsigned i = 0; i < NumLoads; ++i) {
13087     // Perform a single load.
13088     SDValue ScalarLoad =
13089         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13090                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13091                     Ld->getAlignment());
13092     Chains.push_back(ScalarLoad.getValue(1));
13093     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13094     // another round of DAGCombining.
13095     if (i == 0)
13096       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13097     else
13098       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13099                         ScalarLoad, DAG.getIntPtrConstant(i));
13100
13101     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13102   }
13103
13104   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13105
13106   // Bitcast the loaded value to a vector of the original element type, in
13107   // the size of the target vector type.
13108   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13109   unsigned SizeRatio = RegSz / MemSz;
13110
13111   if (Ext == ISD::SEXTLOAD) {
13112     // If we have SSE4.1 we can directly emit a VSEXT node.
13113     if (Subtarget->hasSSE41()) {
13114       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13115       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13116       return Sext;
13117     }
13118
13119     // Otherwise we'll shuffle the small elements in the high bits of the
13120     // larger type and perform an arithmetic shift. If the shift is not legal
13121     // it's better to scalarize.
13122     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13123            "We can't implement an sext load without a arithmetic right shift!");
13124
13125     // Redistribute the loaded elements into the different locations.
13126     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13127     for (unsigned i = 0; i != NumElems; ++i)
13128       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13129
13130     SDValue Shuff = DAG.getVectorShuffle(
13131         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13132
13133     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13134
13135     // Build the arithmetic shift.
13136     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13137                    MemVT.getVectorElementType().getSizeInBits();
13138     Shuff =
13139         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13140
13141     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13142     return Shuff;
13143   }
13144
13145   // Redistribute the loaded elements into the different locations.
13146   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13147   for (unsigned i = 0; i != NumElems; ++i)
13148     ShuffleVec[i * SizeRatio] = i;
13149
13150   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13151                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13152
13153   // Bitcast to the requested type.
13154   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13155   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13156   return Shuff;
13157 }
13158
13159 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13160 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13161 // from the AND / OR.
13162 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13163   Opc = Op.getOpcode();
13164   if (Opc != ISD::OR && Opc != ISD::AND)
13165     return false;
13166   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13167           Op.getOperand(0).hasOneUse() &&
13168           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13169           Op.getOperand(1).hasOneUse());
13170 }
13171
13172 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13173 // 1 and that the SETCC node has a single use.
13174 static bool isXor1OfSetCC(SDValue Op) {
13175   if (Op.getOpcode() != ISD::XOR)
13176     return false;
13177   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13178   if (N1C && N1C->getAPIntValue() == 1) {
13179     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13180       Op.getOperand(0).hasOneUse();
13181   }
13182   return false;
13183 }
13184
13185 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13186   bool addTest = true;
13187   SDValue Chain = Op.getOperand(0);
13188   SDValue Cond  = Op.getOperand(1);
13189   SDValue Dest  = Op.getOperand(2);
13190   SDLoc dl(Op);
13191   SDValue CC;
13192   bool Inverted = false;
13193
13194   if (Cond.getOpcode() == ISD::SETCC) {
13195     // Check for setcc([su]{add,sub,mul}o == 0).
13196     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13197         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13198         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13199         Cond.getOperand(0).getResNo() == 1 &&
13200         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13201          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13202          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13203          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13204          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13205          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13206       Inverted = true;
13207       Cond = Cond.getOperand(0);
13208     } else {
13209       SDValue NewCond = LowerSETCC(Cond, DAG);
13210       if (NewCond.getNode())
13211         Cond = NewCond;
13212     }
13213   }
13214 #if 0
13215   // FIXME: LowerXALUO doesn't handle these!!
13216   else if (Cond.getOpcode() == X86ISD::ADD  ||
13217            Cond.getOpcode() == X86ISD::SUB  ||
13218            Cond.getOpcode() == X86ISD::SMUL ||
13219            Cond.getOpcode() == X86ISD::UMUL)
13220     Cond = LowerXALUO(Cond, DAG);
13221 #endif
13222
13223   // Look pass (and (setcc_carry (cmp ...)), 1).
13224   if (Cond.getOpcode() == ISD::AND &&
13225       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13226     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13227     if (C && C->getAPIntValue() == 1)
13228       Cond = Cond.getOperand(0);
13229   }
13230
13231   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13232   // setting operand in place of the X86ISD::SETCC.
13233   unsigned CondOpcode = Cond.getOpcode();
13234   if (CondOpcode == X86ISD::SETCC ||
13235       CondOpcode == X86ISD::SETCC_CARRY) {
13236     CC = Cond.getOperand(0);
13237
13238     SDValue Cmp = Cond.getOperand(1);
13239     unsigned Opc = Cmp.getOpcode();
13240     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13241     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13242       Cond = Cmp;
13243       addTest = false;
13244     } else {
13245       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13246       default: break;
13247       case X86::COND_O:
13248       case X86::COND_B:
13249         // These can only come from an arithmetic instruction with overflow,
13250         // e.g. SADDO, UADDO.
13251         Cond = Cond.getNode()->getOperand(1);
13252         addTest = false;
13253         break;
13254       }
13255     }
13256   }
13257   CondOpcode = Cond.getOpcode();
13258   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13259       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13260       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13261        Cond.getOperand(0).getValueType() != MVT::i8)) {
13262     SDValue LHS = Cond.getOperand(0);
13263     SDValue RHS = Cond.getOperand(1);
13264     unsigned X86Opcode;
13265     unsigned X86Cond;
13266     SDVTList VTs;
13267     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13268     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13269     // X86ISD::INC).
13270     switch (CondOpcode) {
13271     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13272     case ISD::SADDO:
13273       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13274         if (C->isOne()) {
13275           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13276           break;
13277         }
13278       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13279     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13280     case ISD::SSUBO:
13281       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13282         if (C->isOne()) {
13283           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13284           break;
13285         }
13286       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13287     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13288     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13289     default: llvm_unreachable("unexpected overflowing operator");
13290     }
13291     if (Inverted)
13292       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13293     if (CondOpcode == ISD::UMULO)
13294       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13295                           MVT::i32);
13296     else
13297       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13298
13299     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13300
13301     if (CondOpcode == ISD::UMULO)
13302       Cond = X86Op.getValue(2);
13303     else
13304       Cond = X86Op.getValue(1);
13305
13306     CC = DAG.getConstant(X86Cond, MVT::i8);
13307     addTest = false;
13308   } else {
13309     unsigned CondOpc;
13310     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13311       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13312       if (CondOpc == ISD::OR) {
13313         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13314         // two branches instead of an explicit OR instruction with a
13315         // separate test.
13316         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13317             isX86LogicalCmp(Cmp)) {
13318           CC = Cond.getOperand(0).getOperand(0);
13319           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13320                               Chain, Dest, CC, Cmp);
13321           CC = Cond.getOperand(1).getOperand(0);
13322           Cond = Cmp;
13323           addTest = false;
13324         }
13325       } else { // ISD::AND
13326         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13327         // two branches instead of an explicit AND instruction with a
13328         // separate test. However, we only do this if this block doesn't
13329         // have a fall-through edge, because this requires an explicit
13330         // jmp when the condition is false.
13331         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13332             isX86LogicalCmp(Cmp) &&
13333             Op.getNode()->hasOneUse()) {
13334           X86::CondCode CCode =
13335             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13336           CCode = X86::GetOppositeBranchCondition(CCode);
13337           CC = DAG.getConstant(CCode, MVT::i8);
13338           SDNode *User = *Op.getNode()->use_begin();
13339           // Look for an unconditional branch following this conditional branch.
13340           // We need this because we need to reverse the successors in order
13341           // to implement FCMP_OEQ.
13342           if (User->getOpcode() == ISD::BR) {
13343             SDValue FalseBB = User->getOperand(1);
13344             SDNode *NewBR =
13345               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13346             assert(NewBR == User);
13347             (void)NewBR;
13348             Dest = FalseBB;
13349
13350             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13351                                 Chain, Dest, CC, Cmp);
13352             X86::CondCode CCode =
13353               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13354             CCode = X86::GetOppositeBranchCondition(CCode);
13355             CC = DAG.getConstant(CCode, MVT::i8);
13356             Cond = Cmp;
13357             addTest = false;
13358           }
13359         }
13360       }
13361     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13362       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13363       // It should be transformed during dag combiner except when the condition
13364       // is set by a arithmetics with overflow node.
13365       X86::CondCode CCode =
13366         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13367       CCode = X86::GetOppositeBranchCondition(CCode);
13368       CC = DAG.getConstant(CCode, MVT::i8);
13369       Cond = Cond.getOperand(0).getOperand(1);
13370       addTest = false;
13371     } else if (Cond.getOpcode() == ISD::SETCC &&
13372                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13373       // For FCMP_OEQ, we can emit
13374       // two branches instead of an explicit AND instruction with a
13375       // separate test. However, we only do this if this block doesn't
13376       // have a fall-through edge, because this requires an explicit
13377       // jmp when the condition is false.
13378       if (Op.getNode()->hasOneUse()) {
13379         SDNode *User = *Op.getNode()->use_begin();
13380         // Look for an unconditional branch following this conditional branch.
13381         // We need this because we need to reverse the successors in order
13382         // to implement FCMP_OEQ.
13383         if (User->getOpcode() == ISD::BR) {
13384           SDValue FalseBB = User->getOperand(1);
13385           SDNode *NewBR =
13386             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13387           assert(NewBR == User);
13388           (void)NewBR;
13389           Dest = FalseBB;
13390
13391           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13392                                     Cond.getOperand(0), Cond.getOperand(1));
13393           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13394           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13395           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13396                               Chain, Dest, CC, Cmp);
13397           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13398           Cond = Cmp;
13399           addTest = false;
13400         }
13401       }
13402     } else if (Cond.getOpcode() == ISD::SETCC &&
13403                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13404       // For FCMP_UNE, we can emit
13405       // two branches instead of an explicit AND instruction with a
13406       // separate test. However, we only do this if this block doesn't
13407       // have a fall-through edge, because this requires an explicit
13408       // jmp when the condition is false.
13409       if (Op.getNode()->hasOneUse()) {
13410         SDNode *User = *Op.getNode()->use_begin();
13411         // Look for an unconditional branch following this conditional branch.
13412         // We need this because we need to reverse the successors in order
13413         // to implement FCMP_UNE.
13414         if (User->getOpcode() == ISD::BR) {
13415           SDValue FalseBB = User->getOperand(1);
13416           SDNode *NewBR =
13417             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13418           assert(NewBR == User);
13419           (void)NewBR;
13420
13421           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13422                                     Cond.getOperand(0), Cond.getOperand(1));
13423           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13424           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13425           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13426                               Chain, Dest, CC, Cmp);
13427           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13428           Cond = Cmp;
13429           addTest = false;
13430           Dest = FalseBB;
13431         }
13432       }
13433     }
13434   }
13435
13436   if (addTest) {
13437     // Look pass the truncate if the high bits are known zero.
13438     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13439         Cond = Cond.getOperand(0);
13440
13441     // We know the result of AND is compared against zero. Try to match
13442     // it to BT.
13443     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13444       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13445       if (NewSetCC.getNode()) {
13446         CC = NewSetCC.getOperand(0);
13447         Cond = NewSetCC.getOperand(1);
13448         addTest = false;
13449       }
13450     }
13451   }
13452
13453   if (addTest) {
13454     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13455     CC = DAG.getConstant(X86Cond, MVT::i8);
13456     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13457   }
13458   Cond = ConvertCmpIfNecessary(Cond, DAG);
13459   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13460                      Chain, Dest, CC, Cond);
13461 }
13462
13463 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13464 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13465 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13466 // that the guard pages used by the OS virtual memory manager are allocated in
13467 // correct sequence.
13468 SDValue
13469 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13470                                            SelectionDAG &DAG) const {
13471   MachineFunction &MF = DAG.getMachineFunction();
13472   bool SplitStack = MF.shouldSplitStack();
13473   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13474                SplitStack;
13475   SDLoc dl(Op);
13476
13477   if (!Lower) {
13478     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13479     SDNode* Node = Op.getNode();
13480
13481     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13482     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13483         " not tell us which reg is the stack pointer!");
13484     EVT VT = Node->getValueType(0);
13485     SDValue Tmp1 = SDValue(Node, 0);
13486     SDValue Tmp2 = SDValue(Node, 1);
13487     SDValue Tmp3 = Node->getOperand(2);
13488     SDValue Chain = Tmp1.getOperand(0);
13489
13490     // Chain the dynamic stack allocation so that it doesn't modify the stack
13491     // pointer when other instructions are using the stack.
13492     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13493         SDLoc(Node));
13494
13495     SDValue Size = Tmp2.getOperand(1);
13496     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13497     Chain = SP.getValue(1);
13498     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13499     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13500     unsigned StackAlign = TFI.getStackAlignment();
13501     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13502     if (Align > StackAlign)
13503       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13504           DAG.getConstant(-(uint64_t)Align, VT));
13505     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13506
13507     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13508         DAG.getIntPtrConstant(0, true), SDValue(),
13509         SDLoc(Node));
13510
13511     SDValue Ops[2] = { Tmp1, Tmp2 };
13512     return DAG.getMergeValues(Ops, dl);
13513   }
13514
13515   // Get the inputs.
13516   SDValue Chain = Op.getOperand(0);
13517   SDValue Size  = Op.getOperand(1);
13518   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13519   EVT VT = Op.getNode()->getValueType(0);
13520
13521   bool Is64Bit = Subtarget->is64Bit();
13522   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13523
13524   if (SplitStack) {
13525     MachineRegisterInfo &MRI = MF.getRegInfo();
13526
13527     if (Is64Bit) {
13528       // The 64 bit implementation of segmented stacks needs to clobber both r10
13529       // r11. This makes it impossible to use it along with nested parameters.
13530       const Function *F = MF.getFunction();
13531
13532       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13533            I != E; ++I)
13534         if (I->hasNestAttr())
13535           report_fatal_error("Cannot use segmented stacks with functions that "
13536                              "have nested arguments.");
13537     }
13538
13539     const TargetRegisterClass *AddrRegClass =
13540       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13541     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13542     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13543     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13544                                 DAG.getRegister(Vreg, SPTy));
13545     SDValue Ops1[2] = { Value, Chain };
13546     return DAG.getMergeValues(Ops1, dl);
13547   } else {
13548     SDValue Flag;
13549     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13550
13551     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13552     Flag = Chain.getValue(1);
13553     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13554
13555     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13556
13557     const X86RegisterInfo *RegInfo =
13558       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13559     unsigned SPReg = RegInfo->getStackRegister();
13560     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13561     Chain = SP.getValue(1);
13562
13563     if (Align) {
13564       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13565                        DAG.getConstant(-(uint64_t)Align, VT));
13566       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13567     }
13568
13569     SDValue Ops1[2] = { SP, Chain };
13570     return DAG.getMergeValues(Ops1, dl);
13571   }
13572 }
13573
13574 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13575   MachineFunction &MF = DAG.getMachineFunction();
13576   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13577
13578   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13579   SDLoc DL(Op);
13580
13581   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13582     // vastart just stores the address of the VarArgsFrameIndex slot into the
13583     // memory location argument.
13584     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13585                                    getPointerTy());
13586     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13587                         MachinePointerInfo(SV), false, false, 0);
13588   }
13589
13590   // __va_list_tag:
13591   //   gp_offset         (0 - 6 * 8)
13592   //   fp_offset         (48 - 48 + 8 * 16)
13593   //   overflow_arg_area (point to parameters coming in memory).
13594   //   reg_save_area
13595   SmallVector<SDValue, 8> MemOps;
13596   SDValue FIN = Op.getOperand(1);
13597   // Store gp_offset
13598   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13599                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13600                                                MVT::i32),
13601                                FIN, MachinePointerInfo(SV), false, false, 0);
13602   MemOps.push_back(Store);
13603
13604   // Store fp_offset
13605   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13606                     FIN, DAG.getIntPtrConstant(4));
13607   Store = DAG.getStore(Op.getOperand(0), DL,
13608                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13609                                        MVT::i32),
13610                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13611   MemOps.push_back(Store);
13612
13613   // Store ptr to overflow_arg_area
13614   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13615                     FIN, DAG.getIntPtrConstant(4));
13616   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13617                                     getPointerTy());
13618   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13619                        MachinePointerInfo(SV, 8),
13620                        false, false, 0);
13621   MemOps.push_back(Store);
13622
13623   // Store ptr to reg_save_area.
13624   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13625                     FIN, DAG.getIntPtrConstant(8));
13626   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13627                                     getPointerTy());
13628   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13629                        MachinePointerInfo(SV, 16), false, false, 0);
13630   MemOps.push_back(Store);
13631   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13632 }
13633
13634 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13635   assert(Subtarget->is64Bit() &&
13636          "LowerVAARG only handles 64-bit va_arg!");
13637   assert((Subtarget->isTargetLinux() ||
13638           Subtarget->isTargetDarwin()) &&
13639           "Unhandled target in LowerVAARG");
13640   assert(Op.getNode()->getNumOperands() == 4);
13641   SDValue Chain = Op.getOperand(0);
13642   SDValue SrcPtr = Op.getOperand(1);
13643   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13644   unsigned Align = Op.getConstantOperandVal(3);
13645   SDLoc dl(Op);
13646
13647   EVT ArgVT = Op.getNode()->getValueType(0);
13648   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13649   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13650   uint8_t ArgMode;
13651
13652   // Decide which area this value should be read from.
13653   // TODO: Implement the AMD64 ABI in its entirety. This simple
13654   // selection mechanism works only for the basic types.
13655   if (ArgVT == MVT::f80) {
13656     llvm_unreachable("va_arg for f80 not yet implemented");
13657   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13658     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13659   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13660     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13661   } else {
13662     llvm_unreachable("Unhandled argument type in LowerVAARG");
13663   }
13664
13665   if (ArgMode == 2) {
13666     // Sanity Check: Make sure using fp_offset makes sense.
13667     assert(!DAG.getTarget().Options.UseSoftFloat &&
13668            !(DAG.getMachineFunction()
13669                 .getFunction()->getAttributes()
13670                 .hasAttribute(AttributeSet::FunctionIndex,
13671                               Attribute::NoImplicitFloat)) &&
13672            Subtarget->hasSSE1());
13673   }
13674
13675   // Insert VAARG_64 node into the DAG
13676   // VAARG_64 returns two values: Variable Argument Address, Chain
13677   SmallVector<SDValue, 11> InstOps;
13678   InstOps.push_back(Chain);
13679   InstOps.push_back(SrcPtr);
13680   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13681   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13682   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13683   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13684   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13685                                           VTs, InstOps, MVT::i64,
13686                                           MachinePointerInfo(SV),
13687                                           /*Align=*/0,
13688                                           /*Volatile=*/false,
13689                                           /*ReadMem=*/true,
13690                                           /*WriteMem=*/true);
13691   Chain = VAARG.getValue(1);
13692
13693   // Load the next argument and return it
13694   return DAG.getLoad(ArgVT, dl,
13695                      Chain,
13696                      VAARG,
13697                      MachinePointerInfo(),
13698                      false, false, false, 0);
13699 }
13700
13701 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13702                            SelectionDAG &DAG) {
13703   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13704   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13705   SDValue Chain = Op.getOperand(0);
13706   SDValue DstPtr = Op.getOperand(1);
13707   SDValue SrcPtr = Op.getOperand(2);
13708   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13709   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13710   SDLoc DL(Op);
13711
13712   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13713                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13714                        false,
13715                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13716 }
13717
13718 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13719 // amount is a constant. Takes immediate version of shift as input.
13720 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13721                                           SDValue SrcOp, uint64_t ShiftAmt,
13722                                           SelectionDAG &DAG) {
13723   MVT ElementType = VT.getVectorElementType();
13724
13725   // Fold this packed shift into its first operand if ShiftAmt is 0.
13726   if (ShiftAmt == 0)
13727     return SrcOp;
13728
13729   // Check for ShiftAmt >= element width
13730   if (ShiftAmt >= ElementType.getSizeInBits()) {
13731     if (Opc == X86ISD::VSRAI)
13732       ShiftAmt = ElementType.getSizeInBits() - 1;
13733     else
13734       return DAG.getConstant(0, VT);
13735   }
13736
13737   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13738          && "Unknown target vector shift-by-constant node");
13739
13740   // Fold this packed vector shift into a build vector if SrcOp is a
13741   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13742   if (VT == SrcOp.getSimpleValueType() &&
13743       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13744     SmallVector<SDValue, 8> Elts;
13745     unsigned NumElts = SrcOp->getNumOperands();
13746     ConstantSDNode *ND;
13747
13748     switch(Opc) {
13749     default: llvm_unreachable(nullptr);
13750     case X86ISD::VSHLI:
13751       for (unsigned i=0; i!=NumElts; ++i) {
13752         SDValue CurrentOp = SrcOp->getOperand(i);
13753         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13754           Elts.push_back(CurrentOp);
13755           continue;
13756         }
13757         ND = cast<ConstantSDNode>(CurrentOp);
13758         const APInt &C = ND->getAPIntValue();
13759         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13760       }
13761       break;
13762     case X86ISD::VSRLI:
13763       for (unsigned i=0; i!=NumElts; ++i) {
13764         SDValue CurrentOp = SrcOp->getOperand(i);
13765         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13766           Elts.push_back(CurrentOp);
13767           continue;
13768         }
13769         ND = cast<ConstantSDNode>(CurrentOp);
13770         const APInt &C = ND->getAPIntValue();
13771         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13772       }
13773       break;
13774     case X86ISD::VSRAI:
13775       for (unsigned i=0; i!=NumElts; ++i) {
13776         SDValue CurrentOp = SrcOp->getOperand(i);
13777         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13778           Elts.push_back(CurrentOp);
13779           continue;
13780         }
13781         ND = cast<ConstantSDNode>(CurrentOp);
13782         const APInt &C = ND->getAPIntValue();
13783         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13784       }
13785       break;
13786     }
13787
13788     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13789   }
13790
13791   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13792 }
13793
13794 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13795 // may or may not be a constant. Takes immediate version of shift as input.
13796 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13797                                    SDValue SrcOp, SDValue ShAmt,
13798                                    SelectionDAG &DAG) {
13799   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13800
13801   // Catch shift-by-constant.
13802   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13803     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13804                                       CShAmt->getZExtValue(), DAG);
13805
13806   // Change opcode to non-immediate version
13807   switch (Opc) {
13808     default: llvm_unreachable("Unknown target vector shift node");
13809     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13810     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13811     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13812   }
13813
13814   // Need to build a vector containing shift amount
13815   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13816   SDValue ShOps[4];
13817   ShOps[0] = ShAmt;
13818   ShOps[1] = DAG.getConstant(0, MVT::i32);
13819   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13820   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13821
13822   // The return type has to be a 128-bit type with the same element
13823   // type as the input type.
13824   MVT EltVT = VT.getVectorElementType();
13825   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13826
13827   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13828   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13829 }
13830
13831 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13832   SDLoc dl(Op);
13833   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13834   switch (IntNo) {
13835   default: return SDValue();    // Don't custom lower most intrinsics.
13836   // Comparison intrinsics.
13837   case Intrinsic::x86_sse_comieq_ss:
13838   case Intrinsic::x86_sse_comilt_ss:
13839   case Intrinsic::x86_sse_comile_ss:
13840   case Intrinsic::x86_sse_comigt_ss:
13841   case Intrinsic::x86_sse_comige_ss:
13842   case Intrinsic::x86_sse_comineq_ss:
13843   case Intrinsic::x86_sse_ucomieq_ss:
13844   case Intrinsic::x86_sse_ucomilt_ss:
13845   case Intrinsic::x86_sse_ucomile_ss:
13846   case Intrinsic::x86_sse_ucomigt_ss:
13847   case Intrinsic::x86_sse_ucomige_ss:
13848   case Intrinsic::x86_sse_ucomineq_ss:
13849   case Intrinsic::x86_sse2_comieq_sd:
13850   case Intrinsic::x86_sse2_comilt_sd:
13851   case Intrinsic::x86_sse2_comile_sd:
13852   case Intrinsic::x86_sse2_comigt_sd:
13853   case Intrinsic::x86_sse2_comige_sd:
13854   case Intrinsic::x86_sse2_comineq_sd:
13855   case Intrinsic::x86_sse2_ucomieq_sd:
13856   case Intrinsic::x86_sse2_ucomilt_sd:
13857   case Intrinsic::x86_sse2_ucomile_sd:
13858   case Intrinsic::x86_sse2_ucomigt_sd:
13859   case Intrinsic::x86_sse2_ucomige_sd:
13860   case Intrinsic::x86_sse2_ucomineq_sd: {
13861     unsigned Opc;
13862     ISD::CondCode CC;
13863     switch (IntNo) {
13864     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13865     case Intrinsic::x86_sse_comieq_ss:
13866     case Intrinsic::x86_sse2_comieq_sd:
13867       Opc = X86ISD::COMI;
13868       CC = ISD::SETEQ;
13869       break;
13870     case Intrinsic::x86_sse_comilt_ss:
13871     case Intrinsic::x86_sse2_comilt_sd:
13872       Opc = X86ISD::COMI;
13873       CC = ISD::SETLT;
13874       break;
13875     case Intrinsic::x86_sse_comile_ss:
13876     case Intrinsic::x86_sse2_comile_sd:
13877       Opc = X86ISD::COMI;
13878       CC = ISD::SETLE;
13879       break;
13880     case Intrinsic::x86_sse_comigt_ss:
13881     case Intrinsic::x86_sse2_comigt_sd:
13882       Opc = X86ISD::COMI;
13883       CC = ISD::SETGT;
13884       break;
13885     case Intrinsic::x86_sse_comige_ss:
13886     case Intrinsic::x86_sse2_comige_sd:
13887       Opc = X86ISD::COMI;
13888       CC = ISD::SETGE;
13889       break;
13890     case Intrinsic::x86_sse_comineq_ss:
13891     case Intrinsic::x86_sse2_comineq_sd:
13892       Opc = X86ISD::COMI;
13893       CC = ISD::SETNE;
13894       break;
13895     case Intrinsic::x86_sse_ucomieq_ss:
13896     case Intrinsic::x86_sse2_ucomieq_sd:
13897       Opc = X86ISD::UCOMI;
13898       CC = ISD::SETEQ;
13899       break;
13900     case Intrinsic::x86_sse_ucomilt_ss:
13901     case Intrinsic::x86_sse2_ucomilt_sd:
13902       Opc = X86ISD::UCOMI;
13903       CC = ISD::SETLT;
13904       break;
13905     case Intrinsic::x86_sse_ucomile_ss:
13906     case Intrinsic::x86_sse2_ucomile_sd:
13907       Opc = X86ISD::UCOMI;
13908       CC = ISD::SETLE;
13909       break;
13910     case Intrinsic::x86_sse_ucomigt_ss:
13911     case Intrinsic::x86_sse2_ucomigt_sd:
13912       Opc = X86ISD::UCOMI;
13913       CC = ISD::SETGT;
13914       break;
13915     case Intrinsic::x86_sse_ucomige_ss:
13916     case Intrinsic::x86_sse2_ucomige_sd:
13917       Opc = X86ISD::UCOMI;
13918       CC = ISD::SETGE;
13919       break;
13920     case Intrinsic::x86_sse_ucomineq_ss:
13921     case Intrinsic::x86_sse2_ucomineq_sd:
13922       Opc = X86ISD::UCOMI;
13923       CC = ISD::SETNE;
13924       break;
13925     }
13926
13927     SDValue LHS = Op.getOperand(1);
13928     SDValue RHS = Op.getOperand(2);
13929     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13930     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13931     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13932     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13933                                 DAG.getConstant(X86CC, MVT::i8), Cond);
13934     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13935   }
13936
13937   // Arithmetic intrinsics.
13938   case Intrinsic::x86_sse2_pmulu_dq:
13939   case Intrinsic::x86_avx2_pmulu_dq:
13940     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13941                        Op.getOperand(1), Op.getOperand(2));
13942
13943   case Intrinsic::x86_sse41_pmuldq:
13944   case Intrinsic::x86_avx2_pmul_dq:
13945     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13946                        Op.getOperand(1), Op.getOperand(2));
13947
13948   case Intrinsic::x86_sse2_pmulhu_w:
13949   case Intrinsic::x86_avx2_pmulhu_w:
13950     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13951                        Op.getOperand(1), Op.getOperand(2));
13952
13953   case Intrinsic::x86_sse2_pmulh_w:
13954   case Intrinsic::x86_avx2_pmulh_w:
13955     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13956                        Op.getOperand(1), Op.getOperand(2));
13957
13958   // SSE2/AVX2 sub with unsigned saturation intrinsics
13959   case Intrinsic::x86_sse2_psubus_b:
13960   case Intrinsic::x86_sse2_psubus_w:
13961   case Intrinsic::x86_avx2_psubus_b:
13962   case Intrinsic::x86_avx2_psubus_w:
13963     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13964                        Op.getOperand(1), Op.getOperand(2));
13965
13966   // SSE3/AVX horizontal add/sub intrinsics
13967   case Intrinsic::x86_sse3_hadd_ps:
13968   case Intrinsic::x86_sse3_hadd_pd:
13969   case Intrinsic::x86_avx_hadd_ps_256:
13970   case Intrinsic::x86_avx_hadd_pd_256:
13971   case Intrinsic::x86_sse3_hsub_ps:
13972   case Intrinsic::x86_sse3_hsub_pd:
13973   case Intrinsic::x86_avx_hsub_ps_256:
13974   case Intrinsic::x86_avx_hsub_pd_256:
13975   case Intrinsic::x86_ssse3_phadd_w_128:
13976   case Intrinsic::x86_ssse3_phadd_d_128:
13977   case Intrinsic::x86_avx2_phadd_w:
13978   case Intrinsic::x86_avx2_phadd_d:
13979   case Intrinsic::x86_ssse3_phsub_w_128:
13980   case Intrinsic::x86_ssse3_phsub_d_128:
13981   case Intrinsic::x86_avx2_phsub_w:
13982   case Intrinsic::x86_avx2_phsub_d: {
13983     unsigned Opcode;
13984     switch (IntNo) {
13985     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13986     case Intrinsic::x86_sse3_hadd_ps:
13987     case Intrinsic::x86_sse3_hadd_pd:
13988     case Intrinsic::x86_avx_hadd_ps_256:
13989     case Intrinsic::x86_avx_hadd_pd_256:
13990       Opcode = X86ISD::FHADD;
13991       break;
13992     case Intrinsic::x86_sse3_hsub_ps:
13993     case Intrinsic::x86_sse3_hsub_pd:
13994     case Intrinsic::x86_avx_hsub_ps_256:
13995     case Intrinsic::x86_avx_hsub_pd_256:
13996       Opcode = X86ISD::FHSUB;
13997       break;
13998     case Intrinsic::x86_ssse3_phadd_w_128:
13999     case Intrinsic::x86_ssse3_phadd_d_128:
14000     case Intrinsic::x86_avx2_phadd_w:
14001     case Intrinsic::x86_avx2_phadd_d:
14002       Opcode = X86ISD::HADD;
14003       break;
14004     case Intrinsic::x86_ssse3_phsub_w_128:
14005     case Intrinsic::x86_ssse3_phsub_d_128:
14006     case Intrinsic::x86_avx2_phsub_w:
14007     case Intrinsic::x86_avx2_phsub_d:
14008       Opcode = X86ISD::HSUB;
14009       break;
14010     }
14011     return DAG.getNode(Opcode, dl, Op.getValueType(),
14012                        Op.getOperand(1), Op.getOperand(2));
14013   }
14014
14015   // SSE2/SSE41/AVX2 integer max/min intrinsics.
14016   case Intrinsic::x86_sse2_pmaxu_b:
14017   case Intrinsic::x86_sse41_pmaxuw:
14018   case Intrinsic::x86_sse41_pmaxud:
14019   case Intrinsic::x86_avx2_pmaxu_b:
14020   case Intrinsic::x86_avx2_pmaxu_w:
14021   case Intrinsic::x86_avx2_pmaxu_d:
14022   case Intrinsic::x86_sse2_pminu_b:
14023   case Intrinsic::x86_sse41_pminuw:
14024   case Intrinsic::x86_sse41_pminud:
14025   case Intrinsic::x86_avx2_pminu_b:
14026   case Intrinsic::x86_avx2_pminu_w:
14027   case Intrinsic::x86_avx2_pminu_d:
14028   case Intrinsic::x86_sse41_pmaxsb:
14029   case Intrinsic::x86_sse2_pmaxs_w:
14030   case Intrinsic::x86_sse41_pmaxsd:
14031   case Intrinsic::x86_avx2_pmaxs_b:
14032   case Intrinsic::x86_avx2_pmaxs_w:
14033   case Intrinsic::x86_avx2_pmaxs_d:
14034   case Intrinsic::x86_sse41_pminsb:
14035   case Intrinsic::x86_sse2_pmins_w:
14036   case Intrinsic::x86_sse41_pminsd:
14037   case Intrinsic::x86_avx2_pmins_b:
14038   case Intrinsic::x86_avx2_pmins_w:
14039   case Intrinsic::x86_avx2_pmins_d: {
14040     unsigned Opcode;
14041     switch (IntNo) {
14042     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14043     case Intrinsic::x86_sse2_pmaxu_b:
14044     case Intrinsic::x86_sse41_pmaxuw:
14045     case Intrinsic::x86_sse41_pmaxud:
14046     case Intrinsic::x86_avx2_pmaxu_b:
14047     case Intrinsic::x86_avx2_pmaxu_w:
14048     case Intrinsic::x86_avx2_pmaxu_d:
14049       Opcode = X86ISD::UMAX;
14050       break;
14051     case Intrinsic::x86_sse2_pminu_b:
14052     case Intrinsic::x86_sse41_pminuw:
14053     case Intrinsic::x86_sse41_pminud:
14054     case Intrinsic::x86_avx2_pminu_b:
14055     case Intrinsic::x86_avx2_pminu_w:
14056     case Intrinsic::x86_avx2_pminu_d:
14057       Opcode = X86ISD::UMIN;
14058       break;
14059     case Intrinsic::x86_sse41_pmaxsb:
14060     case Intrinsic::x86_sse2_pmaxs_w:
14061     case Intrinsic::x86_sse41_pmaxsd:
14062     case Intrinsic::x86_avx2_pmaxs_b:
14063     case Intrinsic::x86_avx2_pmaxs_w:
14064     case Intrinsic::x86_avx2_pmaxs_d:
14065       Opcode = X86ISD::SMAX;
14066       break;
14067     case Intrinsic::x86_sse41_pminsb:
14068     case Intrinsic::x86_sse2_pmins_w:
14069     case Intrinsic::x86_sse41_pminsd:
14070     case Intrinsic::x86_avx2_pmins_b:
14071     case Intrinsic::x86_avx2_pmins_w:
14072     case Intrinsic::x86_avx2_pmins_d:
14073       Opcode = X86ISD::SMIN;
14074       break;
14075     }
14076     return DAG.getNode(Opcode, dl, Op.getValueType(),
14077                        Op.getOperand(1), Op.getOperand(2));
14078   }
14079
14080   // SSE/SSE2/AVX floating point max/min intrinsics.
14081   case Intrinsic::x86_sse_max_ps:
14082   case Intrinsic::x86_sse2_max_pd:
14083   case Intrinsic::x86_avx_max_ps_256:
14084   case Intrinsic::x86_avx_max_pd_256:
14085   case Intrinsic::x86_sse_min_ps:
14086   case Intrinsic::x86_sse2_min_pd:
14087   case Intrinsic::x86_avx_min_ps_256:
14088   case Intrinsic::x86_avx_min_pd_256: {
14089     unsigned Opcode;
14090     switch (IntNo) {
14091     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14092     case Intrinsic::x86_sse_max_ps:
14093     case Intrinsic::x86_sse2_max_pd:
14094     case Intrinsic::x86_avx_max_ps_256:
14095     case Intrinsic::x86_avx_max_pd_256:
14096       Opcode = X86ISD::FMAX;
14097       break;
14098     case Intrinsic::x86_sse_min_ps:
14099     case Intrinsic::x86_sse2_min_pd:
14100     case Intrinsic::x86_avx_min_ps_256:
14101     case Intrinsic::x86_avx_min_pd_256:
14102       Opcode = X86ISD::FMIN;
14103       break;
14104     }
14105     return DAG.getNode(Opcode, dl, Op.getValueType(),
14106                        Op.getOperand(1), Op.getOperand(2));
14107   }
14108
14109   // AVX2 variable shift intrinsics
14110   case Intrinsic::x86_avx2_psllv_d:
14111   case Intrinsic::x86_avx2_psllv_q:
14112   case Intrinsic::x86_avx2_psllv_d_256:
14113   case Intrinsic::x86_avx2_psllv_q_256:
14114   case Intrinsic::x86_avx2_psrlv_d:
14115   case Intrinsic::x86_avx2_psrlv_q:
14116   case Intrinsic::x86_avx2_psrlv_d_256:
14117   case Intrinsic::x86_avx2_psrlv_q_256:
14118   case Intrinsic::x86_avx2_psrav_d:
14119   case Intrinsic::x86_avx2_psrav_d_256: {
14120     unsigned Opcode;
14121     switch (IntNo) {
14122     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14123     case Intrinsic::x86_avx2_psllv_d:
14124     case Intrinsic::x86_avx2_psllv_q:
14125     case Intrinsic::x86_avx2_psllv_d_256:
14126     case Intrinsic::x86_avx2_psllv_q_256:
14127       Opcode = ISD::SHL;
14128       break;
14129     case Intrinsic::x86_avx2_psrlv_d:
14130     case Intrinsic::x86_avx2_psrlv_q:
14131     case Intrinsic::x86_avx2_psrlv_d_256:
14132     case Intrinsic::x86_avx2_psrlv_q_256:
14133       Opcode = ISD::SRL;
14134       break;
14135     case Intrinsic::x86_avx2_psrav_d:
14136     case Intrinsic::x86_avx2_psrav_d_256:
14137       Opcode = ISD::SRA;
14138       break;
14139     }
14140     return DAG.getNode(Opcode, dl, Op.getValueType(),
14141                        Op.getOperand(1), Op.getOperand(2));
14142   }
14143
14144   case Intrinsic::x86_sse2_packssdw_128:
14145   case Intrinsic::x86_sse2_packsswb_128:
14146   case Intrinsic::x86_avx2_packssdw:
14147   case Intrinsic::x86_avx2_packsswb:
14148     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14149                        Op.getOperand(1), Op.getOperand(2));
14150
14151   case Intrinsic::x86_sse2_packuswb_128:
14152   case Intrinsic::x86_sse41_packusdw:
14153   case Intrinsic::x86_avx2_packuswb:
14154   case Intrinsic::x86_avx2_packusdw:
14155     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14156                        Op.getOperand(1), Op.getOperand(2));
14157
14158   case Intrinsic::x86_ssse3_pshuf_b_128:
14159   case Intrinsic::x86_avx2_pshuf_b:
14160     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14161                        Op.getOperand(1), Op.getOperand(2));
14162
14163   case Intrinsic::x86_sse2_pshuf_d:
14164     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14165                        Op.getOperand(1), Op.getOperand(2));
14166
14167   case Intrinsic::x86_sse2_pshufl_w:
14168     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14169                        Op.getOperand(1), Op.getOperand(2));
14170
14171   case Intrinsic::x86_sse2_pshufh_w:
14172     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14173                        Op.getOperand(1), Op.getOperand(2));
14174
14175   case Intrinsic::x86_ssse3_psign_b_128:
14176   case Intrinsic::x86_ssse3_psign_w_128:
14177   case Intrinsic::x86_ssse3_psign_d_128:
14178   case Intrinsic::x86_avx2_psign_b:
14179   case Intrinsic::x86_avx2_psign_w:
14180   case Intrinsic::x86_avx2_psign_d:
14181     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14182                        Op.getOperand(1), Op.getOperand(2));
14183
14184   case Intrinsic::x86_sse41_insertps:
14185     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14186                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14187
14188   case Intrinsic::x86_avx_vperm2f128_ps_256:
14189   case Intrinsic::x86_avx_vperm2f128_pd_256:
14190   case Intrinsic::x86_avx_vperm2f128_si_256:
14191   case Intrinsic::x86_avx2_vperm2i128:
14192     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14193                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14194
14195   case Intrinsic::x86_avx2_permd:
14196   case Intrinsic::x86_avx2_permps:
14197     // Operands intentionally swapped. Mask is last operand to intrinsic,
14198     // but second operand for node/instruction.
14199     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14200                        Op.getOperand(2), Op.getOperand(1));
14201
14202   case Intrinsic::x86_sse_sqrt_ps:
14203   case Intrinsic::x86_sse2_sqrt_pd:
14204   case Intrinsic::x86_avx_sqrt_ps_256:
14205   case Intrinsic::x86_avx_sqrt_pd_256:
14206     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14207
14208   // ptest and testp intrinsics. The intrinsic these come from are designed to
14209   // return an integer value, not just an instruction so lower it to the ptest
14210   // or testp pattern and a setcc for the result.
14211   case Intrinsic::x86_sse41_ptestz:
14212   case Intrinsic::x86_sse41_ptestc:
14213   case Intrinsic::x86_sse41_ptestnzc:
14214   case Intrinsic::x86_avx_ptestz_256:
14215   case Intrinsic::x86_avx_ptestc_256:
14216   case Intrinsic::x86_avx_ptestnzc_256:
14217   case Intrinsic::x86_avx_vtestz_ps:
14218   case Intrinsic::x86_avx_vtestc_ps:
14219   case Intrinsic::x86_avx_vtestnzc_ps:
14220   case Intrinsic::x86_avx_vtestz_pd:
14221   case Intrinsic::x86_avx_vtestc_pd:
14222   case Intrinsic::x86_avx_vtestnzc_pd:
14223   case Intrinsic::x86_avx_vtestz_ps_256:
14224   case Intrinsic::x86_avx_vtestc_ps_256:
14225   case Intrinsic::x86_avx_vtestnzc_ps_256:
14226   case Intrinsic::x86_avx_vtestz_pd_256:
14227   case Intrinsic::x86_avx_vtestc_pd_256:
14228   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14229     bool IsTestPacked = false;
14230     unsigned X86CC;
14231     switch (IntNo) {
14232     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14233     case Intrinsic::x86_avx_vtestz_ps:
14234     case Intrinsic::x86_avx_vtestz_pd:
14235     case Intrinsic::x86_avx_vtestz_ps_256:
14236     case Intrinsic::x86_avx_vtestz_pd_256:
14237       IsTestPacked = true; // Fallthrough
14238     case Intrinsic::x86_sse41_ptestz:
14239     case Intrinsic::x86_avx_ptestz_256:
14240       // ZF = 1
14241       X86CC = X86::COND_E;
14242       break;
14243     case Intrinsic::x86_avx_vtestc_ps:
14244     case Intrinsic::x86_avx_vtestc_pd:
14245     case Intrinsic::x86_avx_vtestc_ps_256:
14246     case Intrinsic::x86_avx_vtestc_pd_256:
14247       IsTestPacked = true; // Fallthrough
14248     case Intrinsic::x86_sse41_ptestc:
14249     case Intrinsic::x86_avx_ptestc_256:
14250       // CF = 1
14251       X86CC = X86::COND_B;
14252       break;
14253     case Intrinsic::x86_avx_vtestnzc_ps:
14254     case Intrinsic::x86_avx_vtestnzc_pd:
14255     case Intrinsic::x86_avx_vtestnzc_ps_256:
14256     case Intrinsic::x86_avx_vtestnzc_pd_256:
14257       IsTestPacked = true; // Fallthrough
14258     case Intrinsic::x86_sse41_ptestnzc:
14259     case Intrinsic::x86_avx_ptestnzc_256:
14260       // ZF and CF = 0
14261       X86CC = X86::COND_A;
14262       break;
14263     }
14264
14265     SDValue LHS = Op.getOperand(1);
14266     SDValue RHS = Op.getOperand(2);
14267     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14268     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14269     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14270     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14271     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14272   }
14273   case Intrinsic::x86_avx512_kortestz_w:
14274   case Intrinsic::x86_avx512_kortestc_w: {
14275     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14276     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14277     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14278     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14279     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14280     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14281     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14282   }
14283
14284   // SSE/AVX shift intrinsics
14285   case Intrinsic::x86_sse2_psll_w:
14286   case Intrinsic::x86_sse2_psll_d:
14287   case Intrinsic::x86_sse2_psll_q:
14288   case Intrinsic::x86_avx2_psll_w:
14289   case Intrinsic::x86_avx2_psll_d:
14290   case Intrinsic::x86_avx2_psll_q:
14291   case Intrinsic::x86_sse2_psrl_w:
14292   case Intrinsic::x86_sse2_psrl_d:
14293   case Intrinsic::x86_sse2_psrl_q:
14294   case Intrinsic::x86_avx2_psrl_w:
14295   case Intrinsic::x86_avx2_psrl_d:
14296   case Intrinsic::x86_avx2_psrl_q:
14297   case Intrinsic::x86_sse2_psra_w:
14298   case Intrinsic::x86_sse2_psra_d:
14299   case Intrinsic::x86_avx2_psra_w:
14300   case Intrinsic::x86_avx2_psra_d: {
14301     unsigned Opcode;
14302     switch (IntNo) {
14303     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14304     case Intrinsic::x86_sse2_psll_w:
14305     case Intrinsic::x86_sse2_psll_d:
14306     case Intrinsic::x86_sse2_psll_q:
14307     case Intrinsic::x86_avx2_psll_w:
14308     case Intrinsic::x86_avx2_psll_d:
14309     case Intrinsic::x86_avx2_psll_q:
14310       Opcode = X86ISD::VSHL;
14311       break;
14312     case Intrinsic::x86_sse2_psrl_w:
14313     case Intrinsic::x86_sse2_psrl_d:
14314     case Intrinsic::x86_sse2_psrl_q:
14315     case Intrinsic::x86_avx2_psrl_w:
14316     case Intrinsic::x86_avx2_psrl_d:
14317     case Intrinsic::x86_avx2_psrl_q:
14318       Opcode = X86ISD::VSRL;
14319       break;
14320     case Intrinsic::x86_sse2_psra_w:
14321     case Intrinsic::x86_sse2_psra_d:
14322     case Intrinsic::x86_avx2_psra_w:
14323     case Intrinsic::x86_avx2_psra_d:
14324       Opcode = X86ISD::VSRA;
14325       break;
14326     }
14327     return DAG.getNode(Opcode, dl, Op.getValueType(),
14328                        Op.getOperand(1), Op.getOperand(2));
14329   }
14330
14331   // SSE/AVX immediate shift intrinsics
14332   case Intrinsic::x86_sse2_pslli_w:
14333   case Intrinsic::x86_sse2_pslli_d:
14334   case Intrinsic::x86_sse2_pslli_q:
14335   case Intrinsic::x86_avx2_pslli_w:
14336   case Intrinsic::x86_avx2_pslli_d:
14337   case Intrinsic::x86_avx2_pslli_q:
14338   case Intrinsic::x86_sse2_psrli_w:
14339   case Intrinsic::x86_sse2_psrli_d:
14340   case Intrinsic::x86_sse2_psrli_q:
14341   case Intrinsic::x86_avx2_psrli_w:
14342   case Intrinsic::x86_avx2_psrli_d:
14343   case Intrinsic::x86_avx2_psrli_q:
14344   case Intrinsic::x86_sse2_psrai_w:
14345   case Intrinsic::x86_sse2_psrai_d:
14346   case Intrinsic::x86_avx2_psrai_w:
14347   case Intrinsic::x86_avx2_psrai_d: {
14348     unsigned Opcode;
14349     switch (IntNo) {
14350     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14351     case Intrinsic::x86_sse2_pslli_w:
14352     case Intrinsic::x86_sse2_pslli_d:
14353     case Intrinsic::x86_sse2_pslli_q:
14354     case Intrinsic::x86_avx2_pslli_w:
14355     case Intrinsic::x86_avx2_pslli_d:
14356     case Intrinsic::x86_avx2_pslli_q:
14357       Opcode = X86ISD::VSHLI;
14358       break;
14359     case Intrinsic::x86_sse2_psrli_w:
14360     case Intrinsic::x86_sse2_psrli_d:
14361     case Intrinsic::x86_sse2_psrli_q:
14362     case Intrinsic::x86_avx2_psrli_w:
14363     case Intrinsic::x86_avx2_psrli_d:
14364     case Intrinsic::x86_avx2_psrli_q:
14365       Opcode = X86ISD::VSRLI;
14366       break;
14367     case Intrinsic::x86_sse2_psrai_w:
14368     case Intrinsic::x86_sse2_psrai_d:
14369     case Intrinsic::x86_avx2_psrai_w:
14370     case Intrinsic::x86_avx2_psrai_d:
14371       Opcode = X86ISD::VSRAI;
14372       break;
14373     }
14374     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14375                                Op.getOperand(1), Op.getOperand(2), DAG);
14376   }
14377
14378   case Intrinsic::x86_sse42_pcmpistria128:
14379   case Intrinsic::x86_sse42_pcmpestria128:
14380   case Intrinsic::x86_sse42_pcmpistric128:
14381   case Intrinsic::x86_sse42_pcmpestric128:
14382   case Intrinsic::x86_sse42_pcmpistrio128:
14383   case Intrinsic::x86_sse42_pcmpestrio128:
14384   case Intrinsic::x86_sse42_pcmpistris128:
14385   case Intrinsic::x86_sse42_pcmpestris128:
14386   case Intrinsic::x86_sse42_pcmpistriz128:
14387   case Intrinsic::x86_sse42_pcmpestriz128: {
14388     unsigned Opcode;
14389     unsigned X86CC;
14390     switch (IntNo) {
14391     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14392     case Intrinsic::x86_sse42_pcmpistria128:
14393       Opcode = X86ISD::PCMPISTRI;
14394       X86CC = X86::COND_A;
14395       break;
14396     case Intrinsic::x86_sse42_pcmpestria128:
14397       Opcode = X86ISD::PCMPESTRI;
14398       X86CC = X86::COND_A;
14399       break;
14400     case Intrinsic::x86_sse42_pcmpistric128:
14401       Opcode = X86ISD::PCMPISTRI;
14402       X86CC = X86::COND_B;
14403       break;
14404     case Intrinsic::x86_sse42_pcmpestric128:
14405       Opcode = X86ISD::PCMPESTRI;
14406       X86CC = X86::COND_B;
14407       break;
14408     case Intrinsic::x86_sse42_pcmpistrio128:
14409       Opcode = X86ISD::PCMPISTRI;
14410       X86CC = X86::COND_O;
14411       break;
14412     case Intrinsic::x86_sse42_pcmpestrio128:
14413       Opcode = X86ISD::PCMPESTRI;
14414       X86CC = X86::COND_O;
14415       break;
14416     case Intrinsic::x86_sse42_pcmpistris128:
14417       Opcode = X86ISD::PCMPISTRI;
14418       X86CC = X86::COND_S;
14419       break;
14420     case Intrinsic::x86_sse42_pcmpestris128:
14421       Opcode = X86ISD::PCMPESTRI;
14422       X86CC = X86::COND_S;
14423       break;
14424     case Intrinsic::x86_sse42_pcmpistriz128:
14425       Opcode = X86ISD::PCMPISTRI;
14426       X86CC = X86::COND_E;
14427       break;
14428     case Intrinsic::x86_sse42_pcmpestriz128:
14429       Opcode = X86ISD::PCMPESTRI;
14430       X86CC = X86::COND_E;
14431       break;
14432     }
14433     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14434     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14435     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14436     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14437                                 DAG.getConstant(X86CC, MVT::i8),
14438                                 SDValue(PCMP.getNode(), 1));
14439     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14440   }
14441
14442   case Intrinsic::x86_sse42_pcmpistri128:
14443   case Intrinsic::x86_sse42_pcmpestri128: {
14444     unsigned Opcode;
14445     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14446       Opcode = X86ISD::PCMPISTRI;
14447     else
14448       Opcode = X86ISD::PCMPESTRI;
14449
14450     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14451     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14452     return DAG.getNode(Opcode, dl, VTs, NewOps);
14453   }
14454   case Intrinsic::x86_fma_vfmadd_ps:
14455   case Intrinsic::x86_fma_vfmadd_pd:
14456   case Intrinsic::x86_fma_vfmsub_ps:
14457   case Intrinsic::x86_fma_vfmsub_pd:
14458   case Intrinsic::x86_fma_vfnmadd_ps:
14459   case Intrinsic::x86_fma_vfnmadd_pd:
14460   case Intrinsic::x86_fma_vfnmsub_ps:
14461   case Intrinsic::x86_fma_vfnmsub_pd:
14462   case Intrinsic::x86_fma_vfmaddsub_ps:
14463   case Intrinsic::x86_fma_vfmaddsub_pd:
14464   case Intrinsic::x86_fma_vfmsubadd_ps:
14465   case Intrinsic::x86_fma_vfmsubadd_pd:
14466   case Intrinsic::x86_fma_vfmadd_ps_256:
14467   case Intrinsic::x86_fma_vfmadd_pd_256:
14468   case Intrinsic::x86_fma_vfmsub_ps_256:
14469   case Intrinsic::x86_fma_vfmsub_pd_256:
14470   case Intrinsic::x86_fma_vfnmadd_ps_256:
14471   case Intrinsic::x86_fma_vfnmadd_pd_256:
14472   case Intrinsic::x86_fma_vfnmsub_ps_256:
14473   case Intrinsic::x86_fma_vfnmsub_pd_256:
14474   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14475   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14476   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14477   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14478   case Intrinsic::x86_fma_vfmadd_ps_512:
14479   case Intrinsic::x86_fma_vfmadd_pd_512:
14480   case Intrinsic::x86_fma_vfmsub_ps_512:
14481   case Intrinsic::x86_fma_vfmsub_pd_512:
14482   case Intrinsic::x86_fma_vfnmadd_ps_512:
14483   case Intrinsic::x86_fma_vfnmadd_pd_512:
14484   case Intrinsic::x86_fma_vfnmsub_ps_512:
14485   case Intrinsic::x86_fma_vfnmsub_pd_512:
14486   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14487   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14488   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14489   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14490     unsigned Opc;
14491     switch (IntNo) {
14492     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14493     case Intrinsic::x86_fma_vfmadd_ps:
14494     case Intrinsic::x86_fma_vfmadd_pd:
14495     case Intrinsic::x86_fma_vfmadd_ps_256:
14496     case Intrinsic::x86_fma_vfmadd_pd_256:
14497     case Intrinsic::x86_fma_vfmadd_ps_512:
14498     case Intrinsic::x86_fma_vfmadd_pd_512:
14499       Opc = X86ISD::FMADD;
14500       break;
14501     case Intrinsic::x86_fma_vfmsub_ps:
14502     case Intrinsic::x86_fma_vfmsub_pd:
14503     case Intrinsic::x86_fma_vfmsub_ps_256:
14504     case Intrinsic::x86_fma_vfmsub_pd_256:
14505     case Intrinsic::x86_fma_vfmsub_ps_512:
14506     case Intrinsic::x86_fma_vfmsub_pd_512:
14507       Opc = X86ISD::FMSUB;
14508       break;
14509     case Intrinsic::x86_fma_vfnmadd_ps:
14510     case Intrinsic::x86_fma_vfnmadd_pd:
14511     case Intrinsic::x86_fma_vfnmadd_ps_256:
14512     case Intrinsic::x86_fma_vfnmadd_pd_256:
14513     case Intrinsic::x86_fma_vfnmadd_ps_512:
14514     case Intrinsic::x86_fma_vfnmadd_pd_512:
14515       Opc = X86ISD::FNMADD;
14516       break;
14517     case Intrinsic::x86_fma_vfnmsub_ps:
14518     case Intrinsic::x86_fma_vfnmsub_pd:
14519     case Intrinsic::x86_fma_vfnmsub_ps_256:
14520     case Intrinsic::x86_fma_vfnmsub_pd_256:
14521     case Intrinsic::x86_fma_vfnmsub_ps_512:
14522     case Intrinsic::x86_fma_vfnmsub_pd_512:
14523       Opc = X86ISD::FNMSUB;
14524       break;
14525     case Intrinsic::x86_fma_vfmaddsub_ps:
14526     case Intrinsic::x86_fma_vfmaddsub_pd:
14527     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14528     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14529     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14530     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14531       Opc = X86ISD::FMADDSUB;
14532       break;
14533     case Intrinsic::x86_fma_vfmsubadd_ps:
14534     case Intrinsic::x86_fma_vfmsubadd_pd:
14535     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14536     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14537     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14538     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14539       Opc = X86ISD::FMSUBADD;
14540       break;
14541     }
14542
14543     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14544                        Op.getOperand(2), Op.getOperand(3));
14545   }
14546   }
14547 }
14548
14549 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14550                               SDValue Src, SDValue Mask, SDValue Base,
14551                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14552                               const X86Subtarget * Subtarget) {
14553   SDLoc dl(Op);
14554   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14555   assert(C && "Invalid scale type");
14556   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14557   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14558                              Index.getSimpleValueType().getVectorNumElements());
14559   SDValue MaskInReg;
14560   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14561   if (MaskC)
14562     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14563   else
14564     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14565   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14566   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14567   SDValue Segment = DAG.getRegister(0, MVT::i32);
14568   if (Src.getOpcode() == ISD::UNDEF)
14569     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14570   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14571   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14572   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14573   return DAG.getMergeValues(RetOps, dl);
14574 }
14575
14576 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14577                                SDValue Src, SDValue Mask, SDValue Base,
14578                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14579   SDLoc dl(Op);
14580   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14581   assert(C && "Invalid scale type");
14582   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14583   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14584   SDValue Segment = DAG.getRegister(0, MVT::i32);
14585   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14586                              Index.getSimpleValueType().getVectorNumElements());
14587   SDValue MaskInReg;
14588   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14589   if (MaskC)
14590     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14591   else
14592     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14593   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14594   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14595   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14596   return SDValue(Res, 1);
14597 }
14598
14599 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14600                                SDValue Mask, SDValue Base, SDValue Index,
14601                                SDValue ScaleOp, SDValue Chain) {
14602   SDLoc dl(Op);
14603   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14604   assert(C && "Invalid scale type");
14605   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14606   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14607   SDValue Segment = DAG.getRegister(0, MVT::i32);
14608   EVT MaskVT =
14609     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14610   SDValue MaskInReg;
14611   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14612   if (MaskC)
14613     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14614   else
14615     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14616   //SDVTList VTs = DAG.getVTList(MVT::Other);
14617   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14618   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14619   return SDValue(Res, 0);
14620 }
14621
14622 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14623 // read performance monitor counters (x86_rdpmc).
14624 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14625                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14626                               SmallVectorImpl<SDValue> &Results) {
14627   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14628   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14629   SDValue LO, HI;
14630
14631   // The ECX register is used to select the index of the performance counter
14632   // to read.
14633   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14634                                    N->getOperand(2));
14635   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14636
14637   // Reads the content of a 64-bit performance counter and returns it in the
14638   // registers EDX:EAX.
14639   if (Subtarget->is64Bit()) {
14640     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14641     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14642                             LO.getValue(2));
14643   } else {
14644     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14645     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14646                             LO.getValue(2));
14647   }
14648   Chain = HI.getValue(1);
14649
14650   if (Subtarget->is64Bit()) {
14651     // The EAX register is loaded with the low-order 32 bits. The EDX register
14652     // is loaded with the supported high-order bits of the counter.
14653     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14654                               DAG.getConstant(32, MVT::i8));
14655     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14656     Results.push_back(Chain);
14657     return;
14658   }
14659
14660   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14661   SDValue Ops[] = { LO, HI };
14662   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14663   Results.push_back(Pair);
14664   Results.push_back(Chain);
14665 }
14666
14667 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14668 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14669 // also used to custom lower READCYCLECOUNTER nodes.
14670 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14671                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14672                               SmallVectorImpl<SDValue> &Results) {
14673   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14674   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14675   SDValue LO, HI;
14676
14677   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14678   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14679   // and the EAX register is loaded with the low-order 32 bits.
14680   if (Subtarget->is64Bit()) {
14681     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14682     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14683                             LO.getValue(2));
14684   } else {
14685     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14686     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14687                             LO.getValue(2));
14688   }
14689   SDValue Chain = HI.getValue(1);
14690
14691   if (Opcode == X86ISD::RDTSCP_DAG) {
14692     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14693
14694     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14695     // the ECX register. Add 'ecx' explicitly to the chain.
14696     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14697                                      HI.getValue(2));
14698     // Explicitly store the content of ECX at the location passed in input
14699     // to the 'rdtscp' intrinsic.
14700     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14701                          MachinePointerInfo(), false, false, 0);
14702   }
14703
14704   if (Subtarget->is64Bit()) {
14705     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14706     // the EAX register is loaded with the low-order 32 bits.
14707     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14708                               DAG.getConstant(32, MVT::i8));
14709     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14710     Results.push_back(Chain);
14711     return;
14712   }
14713
14714   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14715   SDValue Ops[] = { LO, HI };
14716   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14717   Results.push_back(Pair);
14718   Results.push_back(Chain);
14719 }
14720
14721 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14722                                      SelectionDAG &DAG) {
14723   SmallVector<SDValue, 2> Results;
14724   SDLoc DL(Op);
14725   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14726                           Results);
14727   return DAG.getMergeValues(Results, DL);
14728 }
14729
14730 enum IntrinsicType {
14731   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14732 };
14733
14734 struct IntrinsicData {
14735   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14736     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14737   IntrinsicType Type;
14738   unsigned      Opc0;
14739   unsigned      Opc1;
14740 };
14741
14742 std::map < unsigned, IntrinsicData> IntrMap;
14743 static void InitIntinsicsMap() {
14744   static bool Initialized = false;
14745   if (Initialized) 
14746     return;
14747   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14748                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14749   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14750                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14751   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14752                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14753   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14754                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14755   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14756                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14757   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14758                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14759   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14760                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14761   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14762                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14763   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14764                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14765
14766   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14767                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14768   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14769                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14770   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14771                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14772   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14773                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14774   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14775                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14776   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14777                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14778   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14779                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14780   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14781                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14782    
14783   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14784                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14785                                                         X86::VGATHERPF1QPSm)));
14786   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14787                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14788                                                         X86::VGATHERPF1QPDm)));
14789   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14790                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14791                                                         X86::VGATHERPF1DPDm)));
14792   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14793                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14794                                                         X86::VGATHERPF1DPSm)));
14795   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14796                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14797                                                         X86::VSCATTERPF1QPSm)));
14798   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14799                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14800                                                         X86::VSCATTERPF1QPDm)));
14801   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14802                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14803                                                         X86::VSCATTERPF1DPDm)));
14804   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14805                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14806                                                         X86::VSCATTERPF1DPSm)));
14807   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14808                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14809   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14810                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14811   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14812                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14813   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14814                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14815   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14816                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14817   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14818                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14819   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14820                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14821   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14822                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14823   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14824                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14825   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14826                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
14827   Initialized = true;
14828 }
14829
14830 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14831                                       SelectionDAG &DAG) {
14832   InitIntinsicsMap();
14833   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14834   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14835   if (itr == IntrMap.end())
14836     return SDValue();
14837
14838   SDLoc dl(Op);
14839   IntrinsicData Intr = itr->second;
14840   switch(Intr.Type) {
14841   case RDSEED:
14842   case RDRAND: {
14843     // Emit the node with the right value type.
14844     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14845     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14846
14847     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14848     // Otherwise return the value from Rand, which is always 0, casted to i32.
14849     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14850                       DAG.getConstant(1, Op->getValueType(1)),
14851                       DAG.getConstant(X86::COND_B, MVT::i32),
14852                       SDValue(Result.getNode(), 1) };
14853     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14854                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14855                                   Ops);
14856
14857     // Return { result, isValid, chain }.
14858     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14859                        SDValue(Result.getNode(), 2));
14860   }
14861   case GATHER: {
14862   //gather(v1, mask, index, base, scale);
14863     SDValue Chain = Op.getOperand(0);
14864     SDValue Src   = Op.getOperand(2);
14865     SDValue Base  = Op.getOperand(3);
14866     SDValue Index = Op.getOperand(4);
14867     SDValue Mask  = Op.getOperand(5);
14868     SDValue Scale = Op.getOperand(6);
14869     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14870                           Subtarget);
14871   }
14872   case SCATTER: {
14873   //scatter(base, mask, index, v1, scale);
14874     SDValue Chain = Op.getOperand(0);
14875     SDValue Base  = Op.getOperand(2);
14876     SDValue Mask  = Op.getOperand(3);
14877     SDValue Index = Op.getOperand(4);
14878     SDValue Src   = Op.getOperand(5);
14879     SDValue Scale = Op.getOperand(6);
14880     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14881   }
14882   case PREFETCH: {
14883     SDValue Hint = Op.getOperand(6);
14884     unsigned HintVal;
14885     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14886         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14887       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14888     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14889     SDValue Chain = Op.getOperand(0);
14890     SDValue Mask  = Op.getOperand(2);
14891     SDValue Index = Op.getOperand(3);
14892     SDValue Base  = Op.getOperand(4);
14893     SDValue Scale = Op.getOperand(5);
14894     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14895   }
14896   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14897   case RDTSC: {
14898     SmallVector<SDValue, 2> Results;
14899     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14900     return DAG.getMergeValues(Results, dl);
14901   }
14902   // Read Performance Monitoring Counters.
14903   case RDPMC: {
14904     SmallVector<SDValue, 2> Results;
14905     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14906     return DAG.getMergeValues(Results, dl);
14907   }
14908   // XTEST intrinsics.
14909   case XTEST: {
14910     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14911     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14912     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14913                                 DAG.getConstant(X86::COND_NE, MVT::i8),
14914                                 InTrans);
14915     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14916     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14917                        Ret, SDValue(InTrans.getNode(), 1));
14918   }
14919   }
14920   llvm_unreachable("Unknown Intrinsic Type");
14921 }
14922
14923 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14924                                            SelectionDAG &DAG) const {
14925   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14926   MFI->setReturnAddressIsTaken(true);
14927
14928   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14929     return SDValue();
14930
14931   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14932   SDLoc dl(Op);
14933   EVT PtrVT = getPointerTy();
14934
14935   if (Depth > 0) {
14936     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14937     const X86RegisterInfo *RegInfo =
14938       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14939     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14940     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14941                        DAG.getNode(ISD::ADD, dl, PtrVT,
14942                                    FrameAddr, Offset),
14943                        MachinePointerInfo(), false, false, false, 0);
14944   }
14945
14946   // Just load the return address.
14947   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14948   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14949                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14950 }
14951
14952 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14953   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14954   MFI->setFrameAddressIsTaken(true);
14955
14956   EVT VT = Op.getValueType();
14957   SDLoc dl(Op);  // FIXME probably not meaningful
14958   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14959   const X86RegisterInfo *RegInfo =
14960     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14961   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14962   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14963           (FrameReg == X86::EBP && VT == MVT::i32)) &&
14964          "Invalid Frame Register!");
14965   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14966   while (Depth--)
14967     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14968                             MachinePointerInfo(),
14969                             false, false, false, 0);
14970   return FrameAddr;
14971 }
14972
14973 // FIXME? Maybe this could be a TableGen attribute on some registers and
14974 // this table could be generated automatically from RegInfo.
14975 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14976                                               EVT VT) const {
14977   unsigned Reg = StringSwitch<unsigned>(RegName)
14978                        .Case("esp", X86::ESP)
14979                        .Case("rsp", X86::RSP)
14980                        .Default(0);
14981   if (Reg)
14982     return Reg;
14983   report_fatal_error("Invalid register name global variable");
14984 }
14985
14986 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14987                                                      SelectionDAG &DAG) const {
14988   const X86RegisterInfo *RegInfo =
14989     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14990   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14991 }
14992
14993 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14994   SDValue Chain     = Op.getOperand(0);
14995   SDValue Offset    = Op.getOperand(1);
14996   SDValue Handler   = Op.getOperand(2);
14997   SDLoc dl      (Op);
14998
14999   EVT PtrVT = getPointerTy();
15000   const X86RegisterInfo *RegInfo =
15001     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
15002   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15003   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15004           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15005          "Invalid Frame Register!");
15006   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15007   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15008
15009   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15010                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15011   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15012   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15013                        false, false, 0);
15014   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15015
15016   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15017                      DAG.getRegister(StoreAddrReg, PtrVT));
15018 }
15019
15020 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15021                                                SelectionDAG &DAG) const {
15022   SDLoc DL(Op);
15023   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15024                      DAG.getVTList(MVT::i32, MVT::Other),
15025                      Op.getOperand(0), Op.getOperand(1));
15026 }
15027
15028 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15029                                                 SelectionDAG &DAG) const {
15030   SDLoc DL(Op);
15031   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15032                      Op.getOperand(0), Op.getOperand(1));
15033 }
15034
15035 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15036   return Op.getOperand(0);
15037 }
15038
15039 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15040                                                 SelectionDAG &DAG) const {
15041   SDValue Root = Op.getOperand(0);
15042   SDValue Trmp = Op.getOperand(1); // trampoline
15043   SDValue FPtr = Op.getOperand(2); // nested function
15044   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15045   SDLoc dl (Op);
15046
15047   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15048   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
15049
15050   if (Subtarget->is64Bit()) {
15051     SDValue OutChains[6];
15052
15053     // Large code-model.
15054     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15055     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15056
15057     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15058     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15059
15060     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15061
15062     // Load the pointer to the nested function into R11.
15063     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15064     SDValue Addr = Trmp;
15065     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15066                                 Addr, MachinePointerInfo(TrmpAddr),
15067                                 false, false, 0);
15068
15069     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15070                        DAG.getConstant(2, MVT::i64));
15071     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15072                                 MachinePointerInfo(TrmpAddr, 2),
15073                                 false, false, 2);
15074
15075     // Load the 'nest' parameter value into R10.
15076     // R10 is specified in X86CallingConv.td
15077     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15078     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15079                        DAG.getConstant(10, MVT::i64));
15080     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15081                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15082                                 false, false, 0);
15083
15084     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15085                        DAG.getConstant(12, MVT::i64));
15086     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15087                                 MachinePointerInfo(TrmpAddr, 12),
15088                                 false, false, 2);
15089
15090     // Jump to the nested function.
15091     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15092     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15093                        DAG.getConstant(20, MVT::i64));
15094     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15095                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15096                                 false, false, 0);
15097
15098     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15099     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15100                        DAG.getConstant(22, MVT::i64));
15101     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15102                                 MachinePointerInfo(TrmpAddr, 22),
15103                                 false, false, 0);
15104
15105     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15106   } else {
15107     const Function *Func =
15108       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15109     CallingConv::ID CC = Func->getCallingConv();
15110     unsigned NestReg;
15111
15112     switch (CC) {
15113     default:
15114       llvm_unreachable("Unsupported calling convention");
15115     case CallingConv::C:
15116     case CallingConv::X86_StdCall: {
15117       // Pass 'nest' parameter in ECX.
15118       // Must be kept in sync with X86CallingConv.td
15119       NestReg = X86::ECX;
15120
15121       // Check that ECX wasn't needed by an 'inreg' parameter.
15122       FunctionType *FTy = Func->getFunctionType();
15123       const AttributeSet &Attrs = Func->getAttributes();
15124
15125       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15126         unsigned InRegCount = 0;
15127         unsigned Idx = 1;
15128
15129         for (FunctionType::param_iterator I = FTy->param_begin(),
15130              E = FTy->param_end(); I != E; ++I, ++Idx)
15131           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15132             // FIXME: should only count parameters that are lowered to integers.
15133             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15134
15135         if (InRegCount > 2) {
15136           report_fatal_error("Nest register in use - reduce number of inreg"
15137                              " parameters!");
15138         }
15139       }
15140       break;
15141     }
15142     case CallingConv::X86_FastCall:
15143     case CallingConv::X86_ThisCall:
15144     case CallingConv::Fast:
15145       // Pass 'nest' parameter in EAX.
15146       // Must be kept in sync with X86CallingConv.td
15147       NestReg = X86::EAX;
15148       break;
15149     }
15150
15151     SDValue OutChains[4];
15152     SDValue Addr, Disp;
15153
15154     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15155                        DAG.getConstant(10, MVT::i32));
15156     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15157
15158     // This is storing the opcode for MOV32ri.
15159     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15160     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15161     OutChains[0] = DAG.getStore(Root, dl,
15162                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15163                                 Trmp, MachinePointerInfo(TrmpAddr),
15164                                 false, false, 0);
15165
15166     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15167                        DAG.getConstant(1, MVT::i32));
15168     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15169                                 MachinePointerInfo(TrmpAddr, 1),
15170                                 false, false, 1);
15171
15172     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15173     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15174                        DAG.getConstant(5, MVT::i32));
15175     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15176                                 MachinePointerInfo(TrmpAddr, 5),
15177                                 false, false, 1);
15178
15179     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15180                        DAG.getConstant(6, MVT::i32));
15181     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15182                                 MachinePointerInfo(TrmpAddr, 6),
15183                                 false, false, 1);
15184
15185     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15186   }
15187 }
15188
15189 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15190                                             SelectionDAG &DAG) const {
15191   /*
15192    The rounding mode is in bits 11:10 of FPSR, and has the following
15193    settings:
15194      00 Round to nearest
15195      01 Round to -inf
15196      10 Round to +inf
15197      11 Round to 0
15198
15199   FLT_ROUNDS, on the other hand, expects the following:
15200     -1 Undefined
15201      0 Round to 0
15202      1 Round to nearest
15203      2 Round to +inf
15204      3 Round to -inf
15205
15206   To perform the conversion, we do:
15207     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15208   */
15209
15210   MachineFunction &MF = DAG.getMachineFunction();
15211   const TargetMachine &TM = MF.getTarget();
15212   const TargetFrameLowering &TFI = *TM.getFrameLowering();
15213   unsigned StackAlignment = TFI.getStackAlignment();
15214   MVT VT = Op.getSimpleValueType();
15215   SDLoc DL(Op);
15216
15217   // Save FP Control Word to stack slot
15218   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15219   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15220
15221   MachineMemOperand *MMO =
15222    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15223                            MachineMemOperand::MOStore, 2, 2);
15224
15225   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15226   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15227                                           DAG.getVTList(MVT::Other),
15228                                           Ops, MVT::i16, MMO);
15229
15230   // Load FP Control Word from stack slot
15231   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15232                             MachinePointerInfo(), false, false, false, 0);
15233
15234   // Transform as necessary
15235   SDValue CWD1 =
15236     DAG.getNode(ISD::SRL, DL, MVT::i16,
15237                 DAG.getNode(ISD::AND, DL, MVT::i16,
15238                             CWD, DAG.getConstant(0x800, MVT::i16)),
15239                 DAG.getConstant(11, MVT::i8));
15240   SDValue CWD2 =
15241     DAG.getNode(ISD::SRL, DL, MVT::i16,
15242                 DAG.getNode(ISD::AND, DL, MVT::i16,
15243                             CWD, DAG.getConstant(0x400, MVT::i16)),
15244                 DAG.getConstant(9, MVT::i8));
15245
15246   SDValue RetVal =
15247     DAG.getNode(ISD::AND, DL, MVT::i16,
15248                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15249                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15250                             DAG.getConstant(1, MVT::i16)),
15251                 DAG.getConstant(3, MVT::i16));
15252
15253   return DAG.getNode((VT.getSizeInBits() < 16 ?
15254                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15255 }
15256
15257 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15258   MVT VT = Op.getSimpleValueType();
15259   EVT OpVT = VT;
15260   unsigned NumBits = VT.getSizeInBits();
15261   SDLoc dl(Op);
15262
15263   Op = Op.getOperand(0);
15264   if (VT == MVT::i8) {
15265     // Zero extend to i32 since there is not an i8 bsr.
15266     OpVT = MVT::i32;
15267     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15268   }
15269
15270   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15271   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15272   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15273
15274   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15275   SDValue Ops[] = {
15276     Op,
15277     DAG.getConstant(NumBits+NumBits-1, OpVT),
15278     DAG.getConstant(X86::COND_E, MVT::i8),
15279     Op.getValue(1)
15280   };
15281   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15282
15283   // Finally xor with NumBits-1.
15284   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15285
15286   if (VT == MVT::i8)
15287     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15288   return Op;
15289 }
15290
15291 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15292   MVT VT = Op.getSimpleValueType();
15293   EVT OpVT = VT;
15294   unsigned NumBits = VT.getSizeInBits();
15295   SDLoc dl(Op);
15296
15297   Op = Op.getOperand(0);
15298   if (VT == MVT::i8) {
15299     // Zero extend to i32 since there is not an i8 bsr.
15300     OpVT = MVT::i32;
15301     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15302   }
15303
15304   // Issue a bsr (scan bits in reverse).
15305   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15306   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15307
15308   // And xor with NumBits-1.
15309   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15310
15311   if (VT == MVT::i8)
15312     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15313   return Op;
15314 }
15315
15316 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15317   MVT VT = Op.getSimpleValueType();
15318   unsigned NumBits = VT.getSizeInBits();
15319   SDLoc dl(Op);
15320   Op = Op.getOperand(0);
15321
15322   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15323   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15324   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15325
15326   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15327   SDValue Ops[] = {
15328     Op,
15329     DAG.getConstant(NumBits, VT),
15330     DAG.getConstant(X86::COND_E, MVT::i8),
15331     Op.getValue(1)
15332   };
15333   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15334 }
15335
15336 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15337 // ones, and then concatenate the result back.
15338 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15339   MVT VT = Op.getSimpleValueType();
15340
15341   assert(VT.is256BitVector() && VT.isInteger() &&
15342          "Unsupported value type for operation");
15343
15344   unsigned NumElems = VT.getVectorNumElements();
15345   SDLoc dl(Op);
15346
15347   // Extract the LHS vectors
15348   SDValue LHS = Op.getOperand(0);
15349   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15350   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15351
15352   // Extract the RHS vectors
15353   SDValue RHS = Op.getOperand(1);
15354   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15355   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15356
15357   MVT EltVT = VT.getVectorElementType();
15358   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15359
15360   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15361                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15362                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15363 }
15364
15365 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15366   assert(Op.getSimpleValueType().is256BitVector() &&
15367          Op.getSimpleValueType().isInteger() &&
15368          "Only handle AVX 256-bit vector integer operation");
15369   return Lower256IntArith(Op, DAG);
15370 }
15371
15372 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15373   assert(Op.getSimpleValueType().is256BitVector() &&
15374          Op.getSimpleValueType().isInteger() &&
15375          "Only handle AVX 256-bit vector integer operation");
15376   return Lower256IntArith(Op, DAG);
15377 }
15378
15379 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15380                         SelectionDAG &DAG) {
15381   SDLoc dl(Op);
15382   MVT VT = Op.getSimpleValueType();
15383
15384   // Decompose 256-bit ops into smaller 128-bit ops.
15385   if (VT.is256BitVector() && !Subtarget->hasInt256())
15386     return Lower256IntArith(Op, DAG);
15387
15388   SDValue A = Op.getOperand(0);
15389   SDValue B = Op.getOperand(1);
15390
15391   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15392   if (VT == MVT::v4i32) {
15393     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15394            "Should not custom lower when pmuldq is available!");
15395
15396     // Extract the odd parts.
15397     static const int UnpackMask[] = { 1, -1, 3, -1 };
15398     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15399     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15400
15401     // Multiply the even parts.
15402     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15403     // Now multiply odd parts.
15404     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15405
15406     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15407     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15408
15409     // Merge the two vectors back together with a shuffle. This expands into 2
15410     // shuffles.
15411     static const int ShufMask[] = { 0, 4, 2, 6 };
15412     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15413   }
15414
15415   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15416          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15417
15418   //  Ahi = psrlqi(a, 32);
15419   //  Bhi = psrlqi(b, 32);
15420   //
15421   //  AloBlo = pmuludq(a, b);
15422   //  AloBhi = pmuludq(a, Bhi);
15423   //  AhiBlo = pmuludq(Ahi, b);
15424
15425   //  AloBhi = psllqi(AloBhi, 32);
15426   //  AhiBlo = psllqi(AhiBlo, 32);
15427   //  return AloBlo + AloBhi + AhiBlo;
15428
15429   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15430   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15431
15432   // Bit cast to 32-bit vectors for MULUDQ
15433   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15434                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15435   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15436   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15437   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15438   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15439
15440   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15441   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15442   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15443
15444   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15445   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15446
15447   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15448   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15449 }
15450
15451 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15452   assert(Subtarget->isTargetWin64() && "Unexpected target");
15453   EVT VT = Op.getValueType();
15454   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15455          "Unexpected return type for lowering");
15456
15457   RTLIB::Libcall LC;
15458   bool isSigned;
15459   switch (Op->getOpcode()) {
15460   default: llvm_unreachable("Unexpected request for libcall!");
15461   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15462   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15463   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15464   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15465   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15466   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15467   }
15468
15469   SDLoc dl(Op);
15470   SDValue InChain = DAG.getEntryNode();
15471
15472   TargetLowering::ArgListTy Args;
15473   TargetLowering::ArgListEntry Entry;
15474   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15475     EVT ArgVT = Op->getOperand(i).getValueType();
15476     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15477            "Unexpected argument type for lowering");
15478     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15479     Entry.Node = StackPtr;
15480     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15481                            false, false, 16);
15482     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15483     Entry.Ty = PointerType::get(ArgTy,0);
15484     Entry.isSExt = false;
15485     Entry.isZExt = false;
15486     Args.push_back(Entry);
15487   }
15488
15489   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15490                                          getPointerTy());
15491
15492   TargetLowering::CallLoweringInfo CLI(DAG);
15493   CLI.setDebugLoc(dl).setChain(InChain)
15494     .setCallee(getLibcallCallingConv(LC),
15495                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15496                Callee, std::move(Args), 0)
15497     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15498
15499   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15500   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15501 }
15502
15503 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15504                              SelectionDAG &DAG) {
15505   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15506   EVT VT = Op0.getValueType();
15507   SDLoc dl(Op);
15508
15509   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15510          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15511
15512   // PMULxD operations multiply each even value (starting at 0) of LHS with
15513   // the related value of RHS and produce a widen result.
15514   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15515   // => <2 x i64> <ae|cg>
15516   //
15517   // In other word, to have all the results, we need to perform two PMULxD:
15518   // 1. one with the even values.
15519   // 2. one with the odd values.
15520   // To achieve #2, with need to place the odd values at an even position.
15521   //
15522   // Place the odd value at an even position (basically, shift all values 1
15523   // step to the left):
15524   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15525   // <a|b|c|d> => <b|undef|d|undef>
15526   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15527   // <e|f|g|h> => <f|undef|h|undef>
15528   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15529
15530   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15531   // ints.
15532   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15533   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15534   unsigned Opcode =
15535       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15536   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15537   // => <2 x i64> <ae|cg>
15538   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15539                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15540   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15541   // => <2 x i64> <bf|dh>
15542   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15543                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15544
15545   // Shuffle it back into the right order.
15546   SDValue Highs, Lows;
15547   if (VT == MVT::v8i32) {
15548     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15549     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15550     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15551     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15552   } else {
15553     const int HighMask[] = {1, 5, 3, 7};
15554     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15555     const int LowMask[] = {1, 4, 2, 6};
15556     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15557   }
15558
15559   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15560   // unsigned multiply.
15561   if (IsSigned && !Subtarget->hasSSE41()) {
15562     SDValue ShAmt =
15563         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15564     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15565                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15566     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15567                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15568
15569     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15570     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15571   }
15572
15573   // The first result of MUL_LOHI is actually the low value, followed by the
15574   // high value.
15575   SDValue Ops[] = {Lows, Highs};
15576   return DAG.getMergeValues(Ops, dl);
15577 }
15578
15579 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15580                                          const X86Subtarget *Subtarget) {
15581   MVT VT = Op.getSimpleValueType();
15582   SDLoc dl(Op);
15583   SDValue R = Op.getOperand(0);
15584   SDValue Amt = Op.getOperand(1);
15585
15586   // Optimize shl/srl/sra with constant shift amount.
15587   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15588     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15589       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15590
15591       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15592           (Subtarget->hasInt256() &&
15593            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15594           (Subtarget->hasAVX512() &&
15595            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15596         if (Op.getOpcode() == ISD::SHL)
15597           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15598                                             DAG);
15599         if (Op.getOpcode() == ISD::SRL)
15600           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15601                                             DAG);
15602         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15603           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15604                                             DAG);
15605       }
15606
15607       if (VT == MVT::v16i8) {
15608         if (Op.getOpcode() == ISD::SHL) {
15609           // Make a large shift.
15610           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15611                                                    MVT::v8i16, R, ShiftAmt,
15612                                                    DAG);
15613           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15614           // Zero out the rightmost bits.
15615           SmallVector<SDValue, 16> V(16,
15616                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15617                                                      MVT::i8));
15618           return DAG.getNode(ISD::AND, dl, VT, SHL,
15619                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15620         }
15621         if (Op.getOpcode() == ISD::SRL) {
15622           // Make a large shift.
15623           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15624                                                    MVT::v8i16, R, ShiftAmt,
15625                                                    DAG);
15626           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15627           // Zero out the leftmost bits.
15628           SmallVector<SDValue, 16> V(16,
15629                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15630                                                      MVT::i8));
15631           return DAG.getNode(ISD::AND, dl, VT, SRL,
15632                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15633         }
15634         if (Op.getOpcode() == ISD::SRA) {
15635           if (ShiftAmt == 7) {
15636             // R s>> 7  ===  R s< 0
15637             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15638             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15639           }
15640
15641           // R s>> a === ((R u>> a) ^ m) - m
15642           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15643           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15644                                                          MVT::i8));
15645           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15646           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15647           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15648           return Res;
15649         }
15650         llvm_unreachable("Unknown shift opcode.");
15651       }
15652
15653       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15654         if (Op.getOpcode() == ISD::SHL) {
15655           // Make a large shift.
15656           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15657                                                    MVT::v16i16, R, ShiftAmt,
15658                                                    DAG);
15659           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15660           // Zero out the rightmost bits.
15661           SmallVector<SDValue, 32> V(32,
15662                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15663                                                      MVT::i8));
15664           return DAG.getNode(ISD::AND, dl, VT, SHL,
15665                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15666         }
15667         if (Op.getOpcode() == ISD::SRL) {
15668           // Make a large shift.
15669           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15670                                                    MVT::v16i16, R, ShiftAmt,
15671                                                    DAG);
15672           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15673           // Zero out the leftmost bits.
15674           SmallVector<SDValue, 32> V(32,
15675                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15676                                                      MVT::i8));
15677           return DAG.getNode(ISD::AND, dl, VT, SRL,
15678                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15679         }
15680         if (Op.getOpcode() == ISD::SRA) {
15681           if (ShiftAmt == 7) {
15682             // R s>> 7  ===  R s< 0
15683             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15684             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15685           }
15686
15687           // R s>> a === ((R u>> a) ^ m) - m
15688           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15689           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15690                                                          MVT::i8));
15691           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15692           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15693           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15694           return Res;
15695         }
15696         llvm_unreachable("Unknown shift opcode.");
15697       }
15698     }
15699   }
15700
15701   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15702   if (!Subtarget->is64Bit() &&
15703       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15704       Amt.getOpcode() == ISD::BITCAST &&
15705       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15706     Amt = Amt.getOperand(0);
15707     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15708                      VT.getVectorNumElements();
15709     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15710     uint64_t ShiftAmt = 0;
15711     for (unsigned i = 0; i != Ratio; ++i) {
15712       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15713       if (!C)
15714         return SDValue();
15715       // 6 == Log2(64)
15716       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15717     }
15718     // Check remaining shift amounts.
15719     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15720       uint64_t ShAmt = 0;
15721       for (unsigned j = 0; j != Ratio; ++j) {
15722         ConstantSDNode *C =
15723           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15724         if (!C)
15725           return SDValue();
15726         // 6 == Log2(64)
15727         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15728       }
15729       if (ShAmt != ShiftAmt)
15730         return SDValue();
15731     }
15732     switch (Op.getOpcode()) {
15733     default:
15734       llvm_unreachable("Unknown shift opcode!");
15735     case ISD::SHL:
15736       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15737                                         DAG);
15738     case ISD::SRL:
15739       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15740                                         DAG);
15741     case ISD::SRA:
15742       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15743                                         DAG);
15744     }
15745   }
15746
15747   return SDValue();
15748 }
15749
15750 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15751                                         const X86Subtarget* Subtarget) {
15752   MVT VT = Op.getSimpleValueType();
15753   SDLoc dl(Op);
15754   SDValue R = Op.getOperand(0);
15755   SDValue Amt = Op.getOperand(1);
15756
15757   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15758       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15759       (Subtarget->hasInt256() &&
15760        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15761         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15762        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15763     SDValue BaseShAmt;
15764     EVT EltVT = VT.getVectorElementType();
15765
15766     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15767       unsigned NumElts = VT.getVectorNumElements();
15768       unsigned i, j;
15769       for (i = 0; i != NumElts; ++i) {
15770         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15771           continue;
15772         break;
15773       }
15774       for (j = i; j != NumElts; ++j) {
15775         SDValue Arg = Amt.getOperand(j);
15776         if (Arg.getOpcode() == ISD::UNDEF) continue;
15777         if (Arg != Amt.getOperand(i))
15778           break;
15779       }
15780       if (i != NumElts && j == NumElts)
15781         BaseShAmt = Amt.getOperand(i);
15782     } else {
15783       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15784         Amt = Amt.getOperand(0);
15785       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15786                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15787         SDValue InVec = Amt.getOperand(0);
15788         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15789           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15790           unsigned i = 0;
15791           for (; i != NumElts; ++i) {
15792             SDValue Arg = InVec.getOperand(i);
15793             if (Arg.getOpcode() == ISD::UNDEF) continue;
15794             BaseShAmt = Arg;
15795             break;
15796           }
15797         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15798            if (ConstantSDNode *C =
15799                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15800              unsigned SplatIdx =
15801                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15802              if (C->getZExtValue() == SplatIdx)
15803                BaseShAmt = InVec.getOperand(1);
15804            }
15805         }
15806         if (!BaseShAmt.getNode())
15807           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15808                                   DAG.getIntPtrConstant(0));
15809       }
15810     }
15811
15812     if (BaseShAmt.getNode()) {
15813       if (EltVT.bitsGT(MVT::i32))
15814         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15815       else if (EltVT.bitsLT(MVT::i32))
15816         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15817
15818       switch (Op.getOpcode()) {
15819       default:
15820         llvm_unreachable("Unknown shift opcode!");
15821       case ISD::SHL:
15822         switch (VT.SimpleTy) {
15823         default: return SDValue();
15824         case MVT::v2i64:
15825         case MVT::v4i32:
15826         case MVT::v8i16:
15827         case MVT::v4i64:
15828         case MVT::v8i32:
15829         case MVT::v16i16:
15830         case MVT::v16i32:
15831         case MVT::v8i64:
15832           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15833         }
15834       case ISD::SRA:
15835         switch (VT.SimpleTy) {
15836         default: return SDValue();
15837         case MVT::v4i32:
15838         case MVT::v8i16:
15839         case MVT::v8i32:
15840         case MVT::v16i16:
15841         case MVT::v16i32:
15842         case MVT::v8i64:
15843           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15844         }
15845       case ISD::SRL:
15846         switch (VT.SimpleTy) {
15847         default: return SDValue();
15848         case MVT::v2i64:
15849         case MVT::v4i32:
15850         case MVT::v8i16:
15851         case MVT::v4i64:
15852         case MVT::v8i32:
15853         case MVT::v16i16:
15854         case MVT::v16i32:
15855         case MVT::v8i64:
15856           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15857         }
15858       }
15859     }
15860   }
15861
15862   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15863   if (!Subtarget->is64Bit() &&
15864       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15865       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15866       Amt.getOpcode() == ISD::BITCAST &&
15867       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15868     Amt = Amt.getOperand(0);
15869     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15870                      VT.getVectorNumElements();
15871     std::vector<SDValue> Vals(Ratio);
15872     for (unsigned i = 0; i != Ratio; ++i)
15873       Vals[i] = Amt.getOperand(i);
15874     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15875       for (unsigned j = 0; j != Ratio; ++j)
15876         if (Vals[j] != Amt.getOperand(i + j))
15877           return SDValue();
15878     }
15879     switch (Op.getOpcode()) {
15880     default:
15881       llvm_unreachable("Unknown shift opcode!");
15882     case ISD::SHL:
15883       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15884     case ISD::SRL:
15885       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15886     case ISD::SRA:
15887       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15888     }
15889   }
15890
15891   return SDValue();
15892 }
15893
15894 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15895                           SelectionDAG &DAG) {
15896   MVT VT = Op.getSimpleValueType();
15897   SDLoc dl(Op);
15898   SDValue R = Op.getOperand(0);
15899   SDValue Amt = Op.getOperand(1);
15900   SDValue V;
15901
15902   assert(VT.isVector() && "Custom lowering only for vector shifts!");
15903   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15904
15905   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15906   if (V.getNode())
15907     return V;
15908
15909   V = LowerScalarVariableShift(Op, DAG, Subtarget);
15910   if (V.getNode())
15911       return V;
15912
15913   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15914     return Op;
15915   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15916   if (Subtarget->hasInt256()) {
15917     if (Op.getOpcode() == ISD::SRL &&
15918         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15919          VT == MVT::v4i64 || VT == MVT::v8i32))
15920       return Op;
15921     if (Op.getOpcode() == ISD::SHL &&
15922         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15923          VT == MVT::v4i64 || VT == MVT::v8i32))
15924       return Op;
15925     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15926       return Op;
15927   }
15928
15929   // If possible, lower this packed shift into a vector multiply instead of
15930   // expanding it into a sequence of scalar shifts.
15931   // Do this only if the vector shift count is a constant build_vector.
15932   if (Op.getOpcode() == ISD::SHL && 
15933       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15934        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15935       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15936     SmallVector<SDValue, 8> Elts;
15937     EVT SVT = VT.getScalarType();
15938     unsigned SVTBits = SVT.getSizeInBits();
15939     const APInt &One = APInt(SVTBits, 1);
15940     unsigned NumElems = VT.getVectorNumElements();
15941
15942     for (unsigned i=0; i !=NumElems; ++i) {
15943       SDValue Op = Amt->getOperand(i);
15944       if (Op->getOpcode() == ISD::UNDEF) {
15945         Elts.push_back(Op);
15946         continue;
15947       }
15948
15949       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15950       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15951       uint64_t ShAmt = C.getZExtValue();
15952       if (ShAmt >= SVTBits) {
15953         Elts.push_back(DAG.getUNDEF(SVT));
15954         continue;
15955       }
15956       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15957     }
15958     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15959     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15960   }
15961
15962   // Lower SHL with variable shift amount.
15963   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15964     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15965
15966     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15967     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15968     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15969     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15970   }
15971
15972   // If possible, lower this shift as a sequence of two shifts by
15973   // constant plus a MOVSS/MOVSD instead of scalarizing it.
15974   // Example:
15975   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15976   //
15977   // Could be rewritten as:
15978   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15979   //
15980   // The advantage is that the two shifts from the example would be
15981   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15982   // the vector shift into four scalar shifts plus four pairs of vector
15983   // insert/extract.
15984   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15985       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15986     unsigned TargetOpcode = X86ISD::MOVSS;
15987     bool CanBeSimplified;
15988     // The splat value for the first packed shift (the 'X' from the example).
15989     SDValue Amt1 = Amt->getOperand(0);
15990     // The splat value for the second packed shift (the 'Y' from the example).
15991     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15992                                         Amt->getOperand(2);
15993
15994     // See if it is possible to replace this node with a sequence of
15995     // two shifts followed by a MOVSS/MOVSD
15996     if (VT == MVT::v4i32) {
15997       // Check if it is legal to use a MOVSS.
15998       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15999                         Amt2 == Amt->getOperand(3);
16000       if (!CanBeSimplified) {
16001         // Otherwise, check if we can still simplify this node using a MOVSD.
16002         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16003                           Amt->getOperand(2) == Amt->getOperand(3);
16004         TargetOpcode = X86ISD::MOVSD;
16005         Amt2 = Amt->getOperand(2);
16006       }
16007     } else {
16008       // Do similar checks for the case where the machine value type
16009       // is MVT::v8i16.
16010       CanBeSimplified = Amt1 == Amt->getOperand(1);
16011       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16012         CanBeSimplified = Amt2 == Amt->getOperand(i);
16013
16014       if (!CanBeSimplified) {
16015         TargetOpcode = X86ISD::MOVSD;
16016         CanBeSimplified = true;
16017         Amt2 = Amt->getOperand(4);
16018         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16019           CanBeSimplified = Amt1 == Amt->getOperand(i);
16020         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16021           CanBeSimplified = Amt2 == Amt->getOperand(j);
16022       }
16023     }
16024     
16025     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16026         isa<ConstantSDNode>(Amt2)) {
16027       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16028       EVT CastVT = MVT::v4i32;
16029       SDValue Splat1 = 
16030         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16031       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16032       SDValue Splat2 = 
16033         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16034       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16035       if (TargetOpcode == X86ISD::MOVSD)
16036         CastVT = MVT::v2i64;
16037       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16038       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16039       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16040                                             BitCast1, DAG);
16041       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16042     }
16043   }
16044
16045   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16046     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16047
16048     // a = a << 5;
16049     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16050     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16051
16052     // Turn 'a' into a mask suitable for VSELECT
16053     SDValue VSelM = DAG.getConstant(0x80, VT);
16054     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16055     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16056
16057     SDValue CM1 = DAG.getConstant(0x0f, VT);
16058     SDValue CM2 = DAG.getConstant(0x3f, VT);
16059
16060     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16061     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16062     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16063     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16064     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16065
16066     // a += a
16067     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16068     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16069     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16070
16071     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16072     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16073     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16074     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16075     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16076
16077     // a += a
16078     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16079     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16080     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16081
16082     // return VSELECT(r, r+r, a);
16083     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16084                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16085     return R;
16086   }
16087
16088   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16089   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16090   // solution better.
16091   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16092     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16093     unsigned ExtOpc =
16094         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16095     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16096     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16097     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16098                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16099     }
16100
16101   // Decompose 256-bit shifts into smaller 128-bit shifts.
16102   if (VT.is256BitVector()) {
16103     unsigned NumElems = VT.getVectorNumElements();
16104     MVT EltVT = VT.getVectorElementType();
16105     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16106
16107     // Extract the two vectors
16108     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16109     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16110
16111     // Recreate the shift amount vectors
16112     SDValue Amt1, Amt2;
16113     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16114       // Constant shift amount
16115       SmallVector<SDValue, 4> Amt1Csts;
16116       SmallVector<SDValue, 4> Amt2Csts;
16117       for (unsigned i = 0; i != NumElems/2; ++i)
16118         Amt1Csts.push_back(Amt->getOperand(i));
16119       for (unsigned i = NumElems/2; i != NumElems; ++i)
16120         Amt2Csts.push_back(Amt->getOperand(i));
16121
16122       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16123       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16124     } else {
16125       // Variable shift amount
16126       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16127       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16128     }
16129
16130     // Issue new vector shifts for the smaller types
16131     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16132     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16133
16134     // Concatenate the result back
16135     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16136   }
16137
16138   return SDValue();
16139 }
16140
16141 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16142   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16143   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16144   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16145   // has only one use.
16146   SDNode *N = Op.getNode();
16147   SDValue LHS = N->getOperand(0);
16148   SDValue RHS = N->getOperand(1);
16149   unsigned BaseOp = 0;
16150   unsigned Cond = 0;
16151   SDLoc DL(Op);
16152   switch (Op.getOpcode()) {
16153   default: llvm_unreachable("Unknown ovf instruction!");
16154   case ISD::SADDO:
16155     // A subtract of one will be selected as a INC. Note that INC doesn't
16156     // set CF, so we can't do this for UADDO.
16157     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16158       if (C->isOne()) {
16159         BaseOp = X86ISD::INC;
16160         Cond = X86::COND_O;
16161         break;
16162       }
16163     BaseOp = X86ISD::ADD;
16164     Cond = X86::COND_O;
16165     break;
16166   case ISD::UADDO:
16167     BaseOp = X86ISD::ADD;
16168     Cond = X86::COND_B;
16169     break;
16170   case ISD::SSUBO:
16171     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16172     // set CF, so we can't do this for USUBO.
16173     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16174       if (C->isOne()) {
16175         BaseOp = X86ISD::DEC;
16176         Cond = X86::COND_O;
16177         break;
16178       }
16179     BaseOp = X86ISD::SUB;
16180     Cond = X86::COND_O;
16181     break;
16182   case ISD::USUBO:
16183     BaseOp = X86ISD::SUB;
16184     Cond = X86::COND_B;
16185     break;
16186   case ISD::SMULO:
16187     BaseOp = X86ISD::SMUL;
16188     Cond = X86::COND_O;
16189     break;
16190   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16191     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16192                                  MVT::i32);
16193     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16194
16195     SDValue SetCC =
16196       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16197                   DAG.getConstant(X86::COND_O, MVT::i32),
16198                   SDValue(Sum.getNode(), 2));
16199
16200     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16201   }
16202   }
16203
16204   // Also sets EFLAGS.
16205   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16206   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16207
16208   SDValue SetCC =
16209     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16210                 DAG.getConstant(Cond, MVT::i32),
16211                 SDValue(Sum.getNode(), 1));
16212
16213   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16214 }
16215
16216 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16217                                                   SelectionDAG &DAG) const {
16218   SDLoc dl(Op);
16219   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16220   MVT VT = Op.getSimpleValueType();
16221
16222   if (!Subtarget->hasSSE2() || !VT.isVector())
16223     return SDValue();
16224
16225   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16226                       ExtraVT.getScalarType().getSizeInBits();
16227
16228   switch (VT.SimpleTy) {
16229     default: return SDValue();
16230     case MVT::v8i32:
16231     case MVT::v16i16:
16232       if (!Subtarget->hasFp256())
16233         return SDValue();
16234       if (!Subtarget->hasInt256()) {
16235         // needs to be split
16236         unsigned NumElems = VT.getVectorNumElements();
16237
16238         // Extract the LHS vectors
16239         SDValue LHS = Op.getOperand(0);
16240         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16241         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16242
16243         MVT EltVT = VT.getVectorElementType();
16244         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16245
16246         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16247         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16248         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16249                                    ExtraNumElems/2);
16250         SDValue Extra = DAG.getValueType(ExtraVT);
16251
16252         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16253         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16254
16255         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16256       }
16257       // fall through
16258     case MVT::v4i32:
16259     case MVT::v8i16: {
16260       SDValue Op0 = Op.getOperand(0);
16261       SDValue Op00 = Op0.getOperand(0);
16262       SDValue Tmp1;
16263       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16264       if (Op0.getOpcode() == ISD::BITCAST &&
16265           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16266         // (sext (vzext x)) -> (vsext x)
16267         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16268         if (Tmp1.getNode()) {
16269           EVT ExtraEltVT = ExtraVT.getVectorElementType();
16270           // This folding is only valid when the in-reg type is a vector of i8,
16271           // i16, or i32.
16272           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16273               ExtraEltVT == MVT::i32) {
16274             SDValue Tmp1Op0 = Tmp1.getOperand(0);
16275             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16276                    "This optimization is invalid without a VZEXT.");
16277             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16278           }
16279           Op0 = Tmp1;
16280         }
16281       }
16282
16283       // If the above didn't work, then just use Shift-Left + Shift-Right.
16284       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16285                                         DAG);
16286       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16287                                         DAG);
16288     }
16289   }
16290 }
16291
16292 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16293                                  SelectionDAG &DAG) {
16294   SDLoc dl(Op);
16295   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16296     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16297   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16298     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16299
16300   // The only fence that needs an instruction is a sequentially-consistent
16301   // cross-thread fence.
16302   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16303     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16304     // no-sse2). There isn't any reason to disable it if the target processor
16305     // supports it.
16306     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16307       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16308
16309     SDValue Chain = Op.getOperand(0);
16310     SDValue Zero = DAG.getConstant(0, MVT::i32);
16311     SDValue Ops[] = {
16312       DAG.getRegister(X86::ESP, MVT::i32), // Base
16313       DAG.getTargetConstant(1, MVT::i8),   // Scale
16314       DAG.getRegister(0, MVT::i32),        // Index
16315       DAG.getTargetConstant(0, MVT::i32),  // Disp
16316       DAG.getRegister(0, MVT::i32),        // Segment.
16317       Zero,
16318       Chain
16319     };
16320     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16321     return SDValue(Res, 0);
16322   }
16323
16324   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16325   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16326 }
16327
16328 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16329                              SelectionDAG &DAG) {
16330   MVT T = Op.getSimpleValueType();
16331   SDLoc DL(Op);
16332   unsigned Reg = 0;
16333   unsigned size = 0;
16334   switch(T.SimpleTy) {
16335   default: llvm_unreachable("Invalid value type!");
16336   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16337   case MVT::i16: Reg = X86::AX;  size = 2; break;
16338   case MVT::i32: Reg = X86::EAX; size = 4; break;
16339   case MVT::i64:
16340     assert(Subtarget->is64Bit() && "Node not type legal!");
16341     Reg = X86::RAX; size = 8;
16342     break;
16343   }
16344   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16345                                   Op.getOperand(2), SDValue());
16346   SDValue Ops[] = { cpIn.getValue(0),
16347                     Op.getOperand(1),
16348                     Op.getOperand(3),
16349                     DAG.getTargetConstant(size, MVT::i8),
16350                     cpIn.getValue(1) };
16351   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16352   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16353   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16354                                            Ops, T, MMO);
16355
16356   SDValue cpOut =
16357     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16358   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16359                                       MVT::i32, cpOut.getValue(2));
16360   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16361                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16362
16363   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16364   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16365   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16366   return SDValue();
16367 }
16368
16369 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16370                             SelectionDAG &DAG) {
16371   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16372   MVT DstVT = Op.getSimpleValueType();
16373
16374   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16375     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16376     if (DstVT != MVT::f64)
16377       // This conversion needs to be expanded.
16378       return SDValue();
16379
16380     SDValue InVec = Op->getOperand(0);
16381     SDLoc dl(Op);
16382     unsigned NumElts = SrcVT.getVectorNumElements();
16383     EVT SVT = SrcVT.getVectorElementType();
16384
16385     // Widen the vector in input in the case of MVT::v2i32.
16386     // Example: from MVT::v2i32 to MVT::v4i32.
16387     SmallVector<SDValue, 16> Elts;
16388     for (unsigned i = 0, e = NumElts; i != e; ++i)
16389       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16390                                  DAG.getIntPtrConstant(i)));
16391
16392     // Explicitly mark the extra elements as Undef.
16393     SDValue Undef = DAG.getUNDEF(SVT);
16394     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16395       Elts.push_back(Undef);
16396
16397     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16398     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16399     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16400     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16401                        DAG.getIntPtrConstant(0));
16402   }
16403
16404   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16405          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16406   assert((DstVT == MVT::i64 ||
16407           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16408          "Unexpected custom BITCAST");
16409   // i64 <=> MMX conversions are Legal.
16410   if (SrcVT==MVT::i64 && DstVT.isVector())
16411     return Op;
16412   if (DstVT==MVT::i64 && SrcVT.isVector())
16413     return Op;
16414   // MMX <=> MMX conversions are Legal.
16415   if (SrcVT.isVector() && DstVT.isVector())
16416     return Op;
16417   // All other conversions need to be expanded.
16418   return SDValue();
16419 }
16420
16421 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16422   SDNode *Node = Op.getNode();
16423   SDLoc dl(Node);
16424   EVT T = Node->getValueType(0);
16425   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16426                               DAG.getConstant(0, T), Node->getOperand(2));
16427   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16428                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16429                        Node->getOperand(0),
16430                        Node->getOperand(1), negOp,
16431                        cast<AtomicSDNode>(Node)->getMemOperand(),
16432                        cast<AtomicSDNode>(Node)->getOrdering(),
16433                        cast<AtomicSDNode>(Node)->getSynchScope());
16434 }
16435
16436 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16437   SDNode *Node = Op.getNode();
16438   SDLoc dl(Node);
16439   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16440
16441   // Convert seq_cst store -> xchg
16442   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16443   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16444   //        (The only way to get a 16-byte store is cmpxchg16b)
16445   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16446   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16447       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16448     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16449                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16450                                  Node->getOperand(0),
16451                                  Node->getOperand(1), Node->getOperand(2),
16452                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16453                                  cast<AtomicSDNode>(Node)->getOrdering(),
16454                                  cast<AtomicSDNode>(Node)->getSynchScope());
16455     return Swap.getValue(1);
16456   }
16457   // Other atomic stores have a simple pattern.
16458   return Op;
16459 }
16460
16461 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16462   EVT VT = Op.getNode()->getSimpleValueType(0);
16463
16464   // Let legalize expand this if it isn't a legal type yet.
16465   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16466     return SDValue();
16467
16468   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16469
16470   unsigned Opc;
16471   bool ExtraOp = false;
16472   switch (Op.getOpcode()) {
16473   default: llvm_unreachable("Invalid code");
16474   case ISD::ADDC: Opc = X86ISD::ADD; break;
16475   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16476   case ISD::SUBC: Opc = X86ISD::SUB; break;
16477   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16478   }
16479
16480   if (!ExtraOp)
16481     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16482                        Op.getOperand(1));
16483   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16484                      Op.getOperand(1), Op.getOperand(2));
16485 }
16486
16487 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16488                             SelectionDAG &DAG) {
16489   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16490
16491   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16492   // which returns the values as { float, float } (in XMM0) or
16493   // { double, double } (which is returned in XMM0, XMM1).
16494   SDLoc dl(Op);
16495   SDValue Arg = Op.getOperand(0);
16496   EVT ArgVT = Arg.getValueType();
16497   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16498
16499   TargetLowering::ArgListTy Args;
16500   TargetLowering::ArgListEntry Entry;
16501
16502   Entry.Node = Arg;
16503   Entry.Ty = ArgTy;
16504   Entry.isSExt = false;
16505   Entry.isZExt = false;
16506   Args.push_back(Entry);
16507
16508   bool isF64 = ArgVT == MVT::f64;
16509   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16510   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16511   // the results are returned via SRet in memory.
16512   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16513   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16514   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16515
16516   Type *RetTy = isF64
16517     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16518     : (Type*)VectorType::get(ArgTy, 4);
16519
16520   TargetLowering::CallLoweringInfo CLI(DAG);
16521   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16522     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16523
16524   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16525
16526   if (isF64)
16527     // Returned in xmm0 and xmm1.
16528     return CallResult.first;
16529
16530   // Returned in bits 0:31 and 32:64 xmm0.
16531   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16532                                CallResult.first, DAG.getIntPtrConstant(0));
16533   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16534                                CallResult.first, DAG.getIntPtrConstant(1));
16535   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16536   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16537 }
16538
16539 /// LowerOperation - Provide custom lowering hooks for some operations.
16540 ///
16541 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16542   switch (Op.getOpcode()) {
16543   default: llvm_unreachable("Should not custom lower this!");
16544   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16545   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16546   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16547     return LowerCMP_SWAP(Op, Subtarget, DAG);
16548   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16549   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16550   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16551   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16552   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16553   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16554   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16555   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16556   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16557   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16558   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16559   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16560   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16561   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16562   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16563   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16564   case ISD::SHL_PARTS:
16565   case ISD::SRA_PARTS:
16566   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16567   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16568   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16569   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16570   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16571   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16572   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16573   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16574   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16575   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16576   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16577   case ISD::FABS:               return LowerFABS(Op, DAG);
16578   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16579   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16580   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16581   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16582   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16583   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16584   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16585   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16586   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16587   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16588   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16589   case ISD::INTRINSIC_VOID:
16590   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16591   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16592   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16593   case ISD::FRAME_TO_ARGS_OFFSET:
16594                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16595   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16596   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16597   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16598   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16599   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16600   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16601   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16602   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16603   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16604   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16605   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16606   case ISD::UMUL_LOHI:
16607   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16608   case ISD::SRA:
16609   case ISD::SRL:
16610   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16611   case ISD::SADDO:
16612   case ISD::UADDO:
16613   case ISD::SSUBO:
16614   case ISD::USUBO:
16615   case ISD::SMULO:
16616   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16617   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16618   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16619   case ISD::ADDC:
16620   case ISD::ADDE:
16621   case ISD::SUBC:
16622   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16623   case ISD::ADD:                return LowerADD(Op, DAG);
16624   case ISD::SUB:                return LowerSUB(Op, DAG);
16625   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16626   }
16627 }
16628
16629 static void ReplaceATOMIC_LOAD(SDNode *Node,
16630                                SmallVectorImpl<SDValue> &Results,
16631                                SelectionDAG &DAG) {
16632   SDLoc dl(Node);
16633   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16634
16635   // Convert wide load -> cmpxchg8b/cmpxchg16b
16636   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16637   //        (The only way to get a 16-byte load is cmpxchg16b)
16638   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16639   SDValue Zero = DAG.getConstant(0, VT);
16640   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16641   SDValue Swap =
16642       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16643                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16644                            cast<AtomicSDNode>(Node)->getMemOperand(),
16645                            cast<AtomicSDNode>(Node)->getOrdering(),
16646                            cast<AtomicSDNode>(Node)->getOrdering(),
16647                            cast<AtomicSDNode>(Node)->getSynchScope());
16648   Results.push_back(Swap.getValue(0));
16649   Results.push_back(Swap.getValue(2));
16650 }
16651
16652 /// ReplaceNodeResults - Replace a node with an illegal result type
16653 /// with a new node built out of custom code.
16654 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16655                                            SmallVectorImpl<SDValue>&Results,
16656                                            SelectionDAG &DAG) const {
16657   SDLoc dl(N);
16658   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16659   switch (N->getOpcode()) {
16660   default:
16661     llvm_unreachable("Do not know how to custom type legalize this operation!");
16662   case ISD::SIGN_EXTEND_INREG:
16663   case ISD::ADDC:
16664   case ISD::ADDE:
16665   case ISD::SUBC:
16666   case ISD::SUBE:
16667     // We don't want to expand or promote these.
16668     return;
16669   case ISD::SDIV:
16670   case ISD::UDIV:
16671   case ISD::SREM:
16672   case ISD::UREM:
16673   case ISD::SDIVREM:
16674   case ISD::UDIVREM: {
16675     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16676     Results.push_back(V);
16677     return;
16678   }
16679   case ISD::FP_TO_SINT:
16680   case ISD::FP_TO_UINT: {
16681     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16682
16683     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16684       return;
16685
16686     std::pair<SDValue,SDValue> Vals =
16687         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16688     SDValue FIST = Vals.first, StackSlot = Vals.second;
16689     if (FIST.getNode()) {
16690       EVT VT = N->getValueType(0);
16691       // Return a load from the stack slot.
16692       if (StackSlot.getNode())
16693         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16694                                       MachinePointerInfo(),
16695                                       false, false, false, 0));
16696       else
16697         Results.push_back(FIST);
16698     }
16699     return;
16700   }
16701   case ISD::UINT_TO_FP: {
16702     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16703     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16704         N->getValueType(0) != MVT::v2f32)
16705       return;
16706     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16707                                  N->getOperand(0));
16708     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16709                                      MVT::f64);
16710     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16711     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16712                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16713     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16714     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16715     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16716     return;
16717   }
16718   case ISD::FP_ROUND: {
16719     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16720         return;
16721     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16722     Results.push_back(V);
16723     return;
16724   }
16725   case ISD::INTRINSIC_W_CHAIN: {
16726     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16727     switch (IntNo) {
16728     default : llvm_unreachable("Do not know how to custom type "
16729                                "legalize this intrinsic operation!");
16730     case Intrinsic::x86_rdtsc:
16731       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16732                                      Results);
16733     case Intrinsic::x86_rdtscp:
16734       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16735                                      Results);
16736     case Intrinsic::x86_rdpmc:
16737       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16738     }
16739   }
16740   case ISD::READCYCLECOUNTER: {
16741     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16742                                    Results);
16743   }
16744   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16745     EVT T = N->getValueType(0);
16746     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16747     bool Regs64bit = T == MVT::i128;
16748     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16749     SDValue cpInL, cpInH;
16750     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16751                         DAG.getConstant(0, HalfT));
16752     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16753                         DAG.getConstant(1, HalfT));
16754     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16755                              Regs64bit ? X86::RAX : X86::EAX,
16756                              cpInL, SDValue());
16757     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16758                              Regs64bit ? X86::RDX : X86::EDX,
16759                              cpInH, cpInL.getValue(1));
16760     SDValue swapInL, swapInH;
16761     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16762                           DAG.getConstant(0, HalfT));
16763     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16764                           DAG.getConstant(1, HalfT));
16765     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16766                                Regs64bit ? X86::RBX : X86::EBX,
16767                                swapInL, cpInH.getValue(1));
16768     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16769                                Regs64bit ? X86::RCX : X86::ECX,
16770                                swapInH, swapInL.getValue(1));
16771     SDValue Ops[] = { swapInH.getValue(0),
16772                       N->getOperand(1),
16773                       swapInH.getValue(1) };
16774     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16775     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16776     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16777                                   X86ISD::LCMPXCHG8_DAG;
16778     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16779     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16780                                         Regs64bit ? X86::RAX : X86::EAX,
16781                                         HalfT, Result.getValue(1));
16782     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16783                                         Regs64bit ? X86::RDX : X86::EDX,
16784                                         HalfT, cpOutL.getValue(2));
16785     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16786
16787     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16788                                         MVT::i32, cpOutH.getValue(2));
16789     SDValue Success =
16790         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16791                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16792     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16793
16794     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16795     Results.push_back(Success);
16796     Results.push_back(EFLAGS.getValue(1));
16797     return;
16798   }
16799   case ISD::ATOMIC_SWAP:
16800   case ISD::ATOMIC_LOAD_ADD:
16801   case ISD::ATOMIC_LOAD_SUB:
16802   case ISD::ATOMIC_LOAD_AND:
16803   case ISD::ATOMIC_LOAD_OR:
16804   case ISD::ATOMIC_LOAD_XOR:
16805   case ISD::ATOMIC_LOAD_NAND:
16806   case ISD::ATOMIC_LOAD_MIN:
16807   case ISD::ATOMIC_LOAD_MAX:
16808   case ISD::ATOMIC_LOAD_UMIN:
16809   case ISD::ATOMIC_LOAD_UMAX:
16810     // Delegate to generic TypeLegalization. Situations we can really handle
16811     // should have already been dealt with by X86AtomicExpand.cpp.
16812     break;
16813   case ISD::ATOMIC_LOAD: {
16814     ReplaceATOMIC_LOAD(N, Results, DAG);
16815     return;
16816   }
16817   case ISD::BITCAST: {
16818     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16819     EVT DstVT = N->getValueType(0);
16820     EVT SrcVT = N->getOperand(0)->getValueType(0);
16821
16822     if (SrcVT != MVT::f64 ||
16823         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16824       return;
16825
16826     unsigned NumElts = DstVT.getVectorNumElements();
16827     EVT SVT = DstVT.getVectorElementType();
16828     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16829     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16830                                    MVT::v2f64, N->getOperand(0));
16831     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16832
16833     if (ExperimentalVectorWideningLegalization) {
16834       // If we are legalizing vectors by widening, we already have the desired
16835       // legal vector type, just return it.
16836       Results.push_back(ToVecInt);
16837       return;
16838     }
16839
16840     SmallVector<SDValue, 8> Elts;
16841     for (unsigned i = 0, e = NumElts; i != e; ++i)
16842       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16843                                    ToVecInt, DAG.getIntPtrConstant(i)));
16844
16845     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16846   }
16847   }
16848 }
16849
16850 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16851   switch (Opcode) {
16852   default: return nullptr;
16853   case X86ISD::BSF:                return "X86ISD::BSF";
16854   case X86ISD::BSR:                return "X86ISD::BSR";
16855   case X86ISD::SHLD:               return "X86ISD::SHLD";
16856   case X86ISD::SHRD:               return "X86ISD::SHRD";
16857   case X86ISD::FAND:               return "X86ISD::FAND";
16858   case X86ISD::FANDN:              return "X86ISD::FANDN";
16859   case X86ISD::FOR:                return "X86ISD::FOR";
16860   case X86ISD::FXOR:               return "X86ISD::FXOR";
16861   case X86ISD::FSRL:               return "X86ISD::FSRL";
16862   case X86ISD::FILD:               return "X86ISD::FILD";
16863   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16864   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16865   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16866   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16867   case X86ISD::FLD:                return "X86ISD::FLD";
16868   case X86ISD::FST:                return "X86ISD::FST";
16869   case X86ISD::CALL:               return "X86ISD::CALL";
16870   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16871   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16872   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
16873   case X86ISD::BT:                 return "X86ISD::BT";
16874   case X86ISD::CMP:                return "X86ISD::CMP";
16875   case X86ISD::COMI:               return "X86ISD::COMI";
16876   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16877   case X86ISD::CMPM:               return "X86ISD::CMPM";
16878   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16879   case X86ISD::SETCC:              return "X86ISD::SETCC";
16880   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16881   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16882   case X86ISD::CMOV:               return "X86ISD::CMOV";
16883   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16884   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16885   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
16886   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
16887   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
16888   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
16889   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
16890   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
16891   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
16892   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
16893   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
16894   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
16895   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
16896   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
16897   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
16898   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
16899   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
16900   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
16901   case X86ISD::HADD:               return "X86ISD::HADD";
16902   case X86ISD::HSUB:               return "X86ISD::HSUB";
16903   case X86ISD::FHADD:              return "X86ISD::FHADD";
16904   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
16905   case X86ISD::UMAX:               return "X86ISD::UMAX";
16906   case X86ISD::UMIN:               return "X86ISD::UMIN";
16907   case X86ISD::SMAX:               return "X86ISD::SMAX";
16908   case X86ISD::SMIN:               return "X86ISD::SMIN";
16909   case X86ISD::FMAX:               return "X86ISD::FMAX";
16910   case X86ISD::FMIN:               return "X86ISD::FMIN";
16911   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
16912   case X86ISD::FMINC:              return "X86ISD::FMINC";
16913   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
16914   case X86ISD::FRCP:               return "X86ISD::FRCP";
16915   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
16916   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
16917   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
16918   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
16919   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
16920   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
16921   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
16922   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
16923   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
16924   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
16925   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
16926   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
16927   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
16928   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
16929   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
16930   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
16931   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
16932   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
16933   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
16934   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
16935   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
16936   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
16937   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
16938   case X86ISD::VSHL:               return "X86ISD::VSHL";
16939   case X86ISD::VSRL:               return "X86ISD::VSRL";
16940   case X86ISD::VSRA:               return "X86ISD::VSRA";
16941   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
16942   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
16943   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
16944   case X86ISD::CMPP:               return "X86ISD::CMPP";
16945   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
16946   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
16947   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
16948   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
16949   case X86ISD::ADD:                return "X86ISD::ADD";
16950   case X86ISD::SUB:                return "X86ISD::SUB";
16951   case X86ISD::ADC:                return "X86ISD::ADC";
16952   case X86ISD::SBB:                return "X86ISD::SBB";
16953   case X86ISD::SMUL:               return "X86ISD::SMUL";
16954   case X86ISD::UMUL:               return "X86ISD::UMUL";
16955   case X86ISD::INC:                return "X86ISD::INC";
16956   case X86ISD::DEC:                return "X86ISD::DEC";
16957   case X86ISD::OR:                 return "X86ISD::OR";
16958   case X86ISD::XOR:                return "X86ISD::XOR";
16959   case X86ISD::AND:                return "X86ISD::AND";
16960   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
16961   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
16962   case X86ISD::PTEST:              return "X86ISD::PTEST";
16963   case X86ISD::TESTP:              return "X86ISD::TESTP";
16964   case X86ISD::TESTM:              return "X86ISD::TESTM";
16965   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
16966   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
16967   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
16968   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
16969   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
16970   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
16971   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
16972   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
16973   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
16974   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
16975   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
16976   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
16977   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
16978   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
16979   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
16980   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
16981   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
16982   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
16983   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
16984   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
16985   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
16986   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
16987   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
16988   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
16989   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
16990   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
16991   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
16992   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
16993   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
16994   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
16995   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
16996   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
16997   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16998   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
16999   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17000   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17001   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17002   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17003   case X86ISD::SAHF:               return "X86ISD::SAHF";
17004   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17005   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17006   case X86ISD::FMADD:              return "X86ISD::FMADD";
17007   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17008   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17009   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17010   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17011   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17012   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17013   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17014   case X86ISD::XTEST:              return "X86ISD::XTEST";
17015   }
17016 }
17017
17018 // isLegalAddressingMode - Return true if the addressing mode represented
17019 // by AM is legal for this target, for a load/store of the specified type.
17020 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17021                                               Type *Ty) const {
17022   // X86 supports extremely general addressing modes.
17023   CodeModel::Model M = getTargetMachine().getCodeModel();
17024   Reloc::Model R = getTargetMachine().getRelocationModel();
17025
17026   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17027   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17028     return false;
17029
17030   if (AM.BaseGV) {
17031     unsigned GVFlags =
17032       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17033
17034     // If a reference to this global requires an extra load, we can't fold it.
17035     if (isGlobalStubReference(GVFlags))
17036       return false;
17037
17038     // If BaseGV requires a register for the PIC base, we cannot also have a
17039     // BaseReg specified.
17040     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17041       return false;
17042
17043     // If lower 4G is not available, then we must use rip-relative addressing.
17044     if ((M != CodeModel::Small || R != Reloc::Static) &&
17045         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17046       return false;
17047   }
17048
17049   switch (AM.Scale) {
17050   case 0:
17051   case 1:
17052   case 2:
17053   case 4:
17054   case 8:
17055     // These scales always work.
17056     break;
17057   case 3:
17058   case 5:
17059   case 9:
17060     // These scales are formed with basereg+scalereg.  Only accept if there is
17061     // no basereg yet.
17062     if (AM.HasBaseReg)
17063       return false;
17064     break;
17065   default:  // Other stuff never works.
17066     return false;
17067   }
17068
17069   return true;
17070 }
17071
17072 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17073   unsigned Bits = Ty->getScalarSizeInBits();
17074
17075   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17076   // particularly cheaper than those without.
17077   if (Bits == 8)
17078     return false;
17079
17080   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17081   // variable shifts just as cheap as scalar ones.
17082   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17083     return false;
17084
17085   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17086   // fully general vector.
17087   return true;
17088 }
17089
17090 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17091   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17092     return false;
17093   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17094   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17095   return NumBits1 > NumBits2;
17096 }
17097
17098 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17099   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17100     return false;
17101
17102   if (!isTypeLegal(EVT::getEVT(Ty1)))
17103     return false;
17104
17105   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17106
17107   // Assuming the caller doesn't have a zeroext or signext return parameter,
17108   // truncation all the way down to i1 is valid.
17109   return true;
17110 }
17111
17112 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17113   return isInt<32>(Imm);
17114 }
17115
17116 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17117   // Can also use sub to handle negated immediates.
17118   return isInt<32>(Imm);
17119 }
17120
17121 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17122   if (!VT1.isInteger() || !VT2.isInteger())
17123     return false;
17124   unsigned NumBits1 = VT1.getSizeInBits();
17125   unsigned NumBits2 = VT2.getSizeInBits();
17126   return NumBits1 > NumBits2;
17127 }
17128
17129 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17130   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17131   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17132 }
17133
17134 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17135   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17136   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17137 }
17138
17139 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17140   EVT VT1 = Val.getValueType();
17141   if (isZExtFree(VT1, VT2))
17142     return true;
17143
17144   if (Val.getOpcode() != ISD::LOAD)
17145     return false;
17146
17147   if (!VT1.isSimple() || !VT1.isInteger() ||
17148       !VT2.isSimple() || !VT2.isInteger())
17149     return false;
17150
17151   switch (VT1.getSimpleVT().SimpleTy) {
17152   default: break;
17153   case MVT::i8:
17154   case MVT::i16:
17155   case MVT::i32:
17156     // X86 has 8, 16, and 32-bit zero-extending loads.
17157     return true;
17158   }
17159
17160   return false;
17161 }
17162
17163 bool
17164 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17165   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17166     return false;
17167
17168   VT = VT.getScalarType();
17169
17170   if (!VT.isSimple())
17171     return false;
17172
17173   switch (VT.getSimpleVT().SimpleTy) {
17174   case MVT::f32:
17175   case MVT::f64:
17176     return true;
17177   default:
17178     break;
17179   }
17180
17181   return false;
17182 }
17183
17184 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17185   // i16 instructions are longer (0x66 prefix) and potentially slower.
17186   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17187 }
17188
17189 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17190 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17191 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17192 /// are assumed to be legal.
17193 bool
17194 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17195                                       EVT VT) const {
17196   if (!VT.isSimple())
17197     return false;
17198
17199   MVT SVT = VT.getSimpleVT();
17200
17201   // Very little shuffling can be done for 64-bit vectors right now.
17202   if (VT.getSizeInBits() == 64)
17203     return false;
17204
17205   // If this is a single-input shuffle with no 128 bit lane crossings we can
17206   // lower it into pshufb.
17207   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17208       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17209     bool isLegal = true;
17210     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17211       if (M[I] >= (int)SVT.getVectorNumElements() ||
17212           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17213         isLegal = false;
17214         break;
17215       }
17216     }
17217     if (isLegal)
17218       return true;
17219   }
17220
17221   // FIXME: blends, shifts.
17222   return (SVT.getVectorNumElements() == 2 ||
17223           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17224           isMOVLMask(M, SVT) ||
17225           isMOVHLPSMask(M, SVT) ||
17226           isSHUFPMask(M, SVT) ||
17227           isPSHUFDMask(M, SVT) ||
17228           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17229           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17230           isPALIGNRMask(M, SVT, Subtarget) ||
17231           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17232           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17233           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17234           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17235           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17236 }
17237
17238 bool
17239 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17240                                           EVT VT) const {
17241   if (!VT.isSimple())
17242     return false;
17243
17244   MVT SVT = VT.getSimpleVT();
17245   unsigned NumElts = SVT.getVectorNumElements();
17246   // FIXME: This collection of masks seems suspect.
17247   if (NumElts == 2)
17248     return true;
17249   if (NumElts == 4 && SVT.is128BitVector()) {
17250     return (isMOVLMask(Mask, SVT)  ||
17251             isCommutedMOVLMask(Mask, SVT, true) ||
17252             isSHUFPMask(Mask, SVT) ||
17253             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17254   }
17255   return false;
17256 }
17257
17258 //===----------------------------------------------------------------------===//
17259 //                           X86 Scheduler Hooks
17260 //===----------------------------------------------------------------------===//
17261
17262 /// Utility function to emit xbegin specifying the start of an RTM region.
17263 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17264                                      const TargetInstrInfo *TII) {
17265   DebugLoc DL = MI->getDebugLoc();
17266
17267   const BasicBlock *BB = MBB->getBasicBlock();
17268   MachineFunction::iterator I = MBB;
17269   ++I;
17270
17271   // For the v = xbegin(), we generate
17272   //
17273   // thisMBB:
17274   //  xbegin sinkMBB
17275   //
17276   // mainMBB:
17277   //  eax = -1
17278   //
17279   // sinkMBB:
17280   //  v = eax
17281
17282   MachineBasicBlock *thisMBB = MBB;
17283   MachineFunction *MF = MBB->getParent();
17284   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17285   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17286   MF->insert(I, mainMBB);
17287   MF->insert(I, sinkMBB);
17288
17289   // Transfer the remainder of BB and its successor edges to sinkMBB.
17290   sinkMBB->splice(sinkMBB->begin(), MBB,
17291                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17292   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17293
17294   // thisMBB:
17295   //  xbegin sinkMBB
17296   //  # fallthrough to mainMBB
17297   //  # abortion to sinkMBB
17298   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17299   thisMBB->addSuccessor(mainMBB);
17300   thisMBB->addSuccessor(sinkMBB);
17301
17302   // mainMBB:
17303   //  EAX = -1
17304   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17305   mainMBB->addSuccessor(sinkMBB);
17306
17307   // sinkMBB:
17308   // EAX is live into the sinkMBB
17309   sinkMBB->addLiveIn(X86::EAX);
17310   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17311           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17312     .addReg(X86::EAX);
17313
17314   MI->eraseFromParent();
17315   return sinkMBB;
17316 }
17317
17318 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17319 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17320 // in the .td file.
17321 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17322                                        const TargetInstrInfo *TII) {
17323   unsigned Opc;
17324   switch (MI->getOpcode()) {
17325   default: llvm_unreachable("illegal opcode!");
17326   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17327   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17328   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17329   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17330   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17331   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17332   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17333   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17334   }
17335
17336   DebugLoc dl = MI->getDebugLoc();
17337   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17338
17339   unsigned NumArgs = MI->getNumOperands();
17340   for (unsigned i = 1; i < NumArgs; ++i) {
17341     MachineOperand &Op = MI->getOperand(i);
17342     if (!(Op.isReg() && Op.isImplicit()))
17343       MIB.addOperand(Op);
17344   }
17345   if (MI->hasOneMemOperand())
17346     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17347
17348   BuildMI(*BB, MI, dl,
17349     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17350     .addReg(X86::XMM0);
17351
17352   MI->eraseFromParent();
17353   return BB;
17354 }
17355
17356 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17357 // defs in an instruction pattern
17358 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17359                                        const TargetInstrInfo *TII) {
17360   unsigned Opc;
17361   switch (MI->getOpcode()) {
17362   default: llvm_unreachable("illegal opcode!");
17363   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17364   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17365   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17366   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17367   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17368   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17369   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17370   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17371   }
17372
17373   DebugLoc dl = MI->getDebugLoc();
17374   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17375
17376   unsigned NumArgs = MI->getNumOperands(); // remove the results
17377   for (unsigned i = 1; i < NumArgs; ++i) {
17378     MachineOperand &Op = MI->getOperand(i);
17379     if (!(Op.isReg() && Op.isImplicit()))
17380       MIB.addOperand(Op);
17381   }
17382   if (MI->hasOneMemOperand())
17383     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17384
17385   BuildMI(*BB, MI, dl,
17386     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17387     .addReg(X86::ECX);
17388
17389   MI->eraseFromParent();
17390   return BB;
17391 }
17392
17393 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17394                                        const TargetInstrInfo *TII,
17395                                        const X86Subtarget* Subtarget) {
17396   DebugLoc dl = MI->getDebugLoc();
17397
17398   // Address into RAX/EAX, other two args into ECX, EDX.
17399   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17400   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17401   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17402   for (int i = 0; i < X86::AddrNumOperands; ++i)
17403     MIB.addOperand(MI->getOperand(i));
17404
17405   unsigned ValOps = X86::AddrNumOperands;
17406   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17407     .addReg(MI->getOperand(ValOps).getReg());
17408   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17409     .addReg(MI->getOperand(ValOps+1).getReg());
17410
17411   // The instruction doesn't actually take any operands though.
17412   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17413
17414   MI->eraseFromParent(); // The pseudo is gone now.
17415   return BB;
17416 }
17417
17418 MachineBasicBlock *
17419 X86TargetLowering::EmitVAARG64WithCustomInserter(
17420                    MachineInstr *MI,
17421                    MachineBasicBlock *MBB) const {
17422   // Emit va_arg instruction on X86-64.
17423
17424   // Operands to this pseudo-instruction:
17425   // 0  ) Output        : destination address (reg)
17426   // 1-5) Input         : va_list address (addr, i64mem)
17427   // 6  ) ArgSize       : Size (in bytes) of vararg type
17428   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17429   // 8  ) Align         : Alignment of type
17430   // 9  ) EFLAGS (implicit-def)
17431
17432   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17433   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17434
17435   unsigned DestReg = MI->getOperand(0).getReg();
17436   MachineOperand &Base = MI->getOperand(1);
17437   MachineOperand &Scale = MI->getOperand(2);
17438   MachineOperand &Index = MI->getOperand(3);
17439   MachineOperand &Disp = MI->getOperand(4);
17440   MachineOperand &Segment = MI->getOperand(5);
17441   unsigned ArgSize = MI->getOperand(6).getImm();
17442   unsigned ArgMode = MI->getOperand(7).getImm();
17443   unsigned Align = MI->getOperand(8).getImm();
17444
17445   // Memory Reference
17446   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17447   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17448   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17449
17450   // Machine Information
17451   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17452   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17453   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17454   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17455   DebugLoc DL = MI->getDebugLoc();
17456
17457   // struct va_list {
17458   //   i32   gp_offset
17459   //   i32   fp_offset
17460   //   i64   overflow_area (address)
17461   //   i64   reg_save_area (address)
17462   // }
17463   // sizeof(va_list) = 24
17464   // alignment(va_list) = 8
17465
17466   unsigned TotalNumIntRegs = 6;
17467   unsigned TotalNumXMMRegs = 8;
17468   bool UseGPOffset = (ArgMode == 1);
17469   bool UseFPOffset = (ArgMode == 2);
17470   unsigned MaxOffset = TotalNumIntRegs * 8 +
17471                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17472
17473   /* Align ArgSize to a multiple of 8 */
17474   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17475   bool NeedsAlign = (Align > 8);
17476
17477   MachineBasicBlock *thisMBB = MBB;
17478   MachineBasicBlock *overflowMBB;
17479   MachineBasicBlock *offsetMBB;
17480   MachineBasicBlock *endMBB;
17481
17482   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17483   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17484   unsigned OffsetReg = 0;
17485
17486   if (!UseGPOffset && !UseFPOffset) {
17487     // If we only pull from the overflow region, we don't create a branch.
17488     // We don't need to alter control flow.
17489     OffsetDestReg = 0; // unused
17490     OverflowDestReg = DestReg;
17491
17492     offsetMBB = nullptr;
17493     overflowMBB = thisMBB;
17494     endMBB = thisMBB;
17495   } else {
17496     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17497     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17498     // If not, pull from overflow_area. (branch to overflowMBB)
17499     //
17500     //       thisMBB
17501     //         |     .
17502     //         |        .
17503     //     offsetMBB   overflowMBB
17504     //         |        .
17505     //         |     .
17506     //        endMBB
17507
17508     // Registers for the PHI in endMBB
17509     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17510     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17511
17512     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17513     MachineFunction *MF = MBB->getParent();
17514     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17515     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17516     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17517
17518     MachineFunction::iterator MBBIter = MBB;
17519     ++MBBIter;
17520
17521     // Insert the new basic blocks
17522     MF->insert(MBBIter, offsetMBB);
17523     MF->insert(MBBIter, overflowMBB);
17524     MF->insert(MBBIter, endMBB);
17525
17526     // Transfer the remainder of MBB and its successor edges to endMBB.
17527     endMBB->splice(endMBB->begin(), thisMBB,
17528                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17529     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17530
17531     // Make offsetMBB and overflowMBB successors of thisMBB
17532     thisMBB->addSuccessor(offsetMBB);
17533     thisMBB->addSuccessor(overflowMBB);
17534
17535     // endMBB is a successor of both offsetMBB and overflowMBB
17536     offsetMBB->addSuccessor(endMBB);
17537     overflowMBB->addSuccessor(endMBB);
17538
17539     // Load the offset value into a register
17540     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17541     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17542       .addOperand(Base)
17543       .addOperand(Scale)
17544       .addOperand(Index)
17545       .addDisp(Disp, UseFPOffset ? 4 : 0)
17546       .addOperand(Segment)
17547       .setMemRefs(MMOBegin, MMOEnd);
17548
17549     // Check if there is enough room left to pull this argument.
17550     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17551       .addReg(OffsetReg)
17552       .addImm(MaxOffset + 8 - ArgSizeA8);
17553
17554     // Branch to "overflowMBB" if offset >= max
17555     // Fall through to "offsetMBB" otherwise
17556     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17557       .addMBB(overflowMBB);
17558   }
17559
17560   // In offsetMBB, emit code to use the reg_save_area.
17561   if (offsetMBB) {
17562     assert(OffsetReg != 0);
17563
17564     // Read the reg_save_area address.
17565     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17566     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17567       .addOperand(Base)
17568       .addOperand(Scale)
17569       .addOperand(Index)
17570       .addDisp(Disp, 16)
17571       .addOperand(Segment)
17572       .setMemRefs(MMOBegin, MMOEnd);
17573
17574     // Zero-extend the offset
17575     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17576       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17577         .addImm(0)
17578         .addReg(OffsetReg)
17579         .addImm(X86::sub_32bit);
17580
17581     // Add the offset to the reg_save_area to get the final address.
17582     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17583       .addReg(OffsetReg64)
17584       .addReg(RegSaveReg);
17585
17586     // Compute the offset for the next argument
17587     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17588     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17589       .addReg(OffsetReg)
17590       .addImm(UseFPOffset ? 16 : 8);
17591
17592     // Store it back into the va_list.
17593     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17594       .addOperand(Base)
17595       .addOperand(Scale)
17596       .addOperand(Index)
17597       .addDisp(Disp, UseFPOffset ? 4 : 0)
17598       .addOperand(Segment)
17599       .addReg(NextOffsetReg)
17600       .setMemRefs(MMOBegin, MMOEnd);
17601
17602     // Jump to endMBB
17603     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17604       .addMBB(endMBB);
17605   }
17606
17607   //
17608   // Emit code to use overflow area
17609   //
17610
17611   // Load the overflow_area address into a register.
17612   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17613   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17614     .addOperand(Base)
17615     .addOperand(Scale)
17616     .addOperand(Index)
17617     .addDisp(Disp, 8)
17618     .addOperand(Segment)
17619     .setMemRefs(MMOBegin, MMOEnd);
17620
17621   // If we need to align it, do so. Otherwise, just copy the address
17622   // to OverflowDestReg.
17623   if (NeedsAlign) {
17624     // Align the overflow address
17625     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17626     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17627
17628     // aligned_addr = (addr + (align-1)) & ~(align-1)
17629     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17630       .addReg(OverflowAddrReg)
17631       .addImm(Align-1);
17632
17633     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17634       .addReg(TmpReg)
17635       .addImm(~(uint64_t)(Align-1));
17636   } else {
17637     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17638       .addReg(OverflowAddrReg);
17639   }
17640
17641   // Compute the next overflow address after this argument.
17642   // (the overflow address should be kept 8-byte aligned)
17643   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17644   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17645     .addReg(OverflowDestReg)
17646     .addImm(ArgSizeA8);
17647
17648   // Store the new overflow address.
17649   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17650     .addOperand(Base)
17651     .addOperand(Scale)
17652     .addOperand(Index)
17653     .addDisp(Disp, 8)
17654     .addOperand(Segment)
17655     .addReg(NextAddrReg)
17656     .setMemRefs(MMOBegin, MMOEnd);
17657
17658   // If we branched, emit the PHI to the front of endMBB.
17659   if (offsetMBB) {
17660     BuildMI(*endMBB, endMBB->begin(), DL,
17661             TII->get(X86::PHI), DestReg)
17662       .addReg(OffsetDestReg).addMBB(offsetMBB)
17663       .addReg(OverflowDestReg).addMBB(overflowMBB);
17664   }
17665
17666   // Erase the pseudo instruction
17667   MI->eraseFromParent();
17668
17669   return endMBB;
17670 }
17671
17672 MachineBasicBlock *
17673 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17674                                                  MachineInstr *MI,
17675                                                  MachineBasicBlock *MBB) const {
17676   // Emit code to save XMM registers to the stack. The ABI says that the
17677   // number of registers to save is given in %al, so it's theoretically
17678   // possible to do an indirect jump trick to avoid saving all of them,
17679   // however this code takes a simpler approach and just executes all
17680   // of the stores if %al is non-zero. It's less code, and it's probably
17681   // easier on the hardware branch predictor, and stores aren't all that
17682   // expensive anyway.
17683
17684   // Create the new basic blocks. One block contains all the XMM stores,
17685   // and one block is the final destination regardless of whether any
17686   // stores were performed.
17687   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17688   MachineFunction *F = MBB->getParent();
17689   MachineFunction::iterator MBBIter = MBB;
17690   ++MBBIter;
17691   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17692   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17693   F->insert(MBBIter, XMMSaveMBB);
17694   F->insert(MBBIter, EndMBB);
17695
17696   // Transfer the remainder of MBB and its successor edges to EndMBB.
17697   EndMBB->splice(EndMBB->begin(), MBB,
17698                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17699   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17700
17701   // The original block will now fall through to the XMM save block.
17702   MBB->addSuccessor(XMMSaveMBB);
17703   // The XMMSaveMBB will fall through to the end block.
17704   XMMSaveMBB->addSuccessor(EndMBB);
17705
17706   // Now add the instructions.
17707   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17708   DebugLoc DL = MI->getDebugLoc();
17709
17710   unsigned CountReg = MI->getOperand(0).getReg();
17711   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17712   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17713
17714   if (!Subtarget->isTargetWin64()) {
17715     // If %al is 0, branch around the XMM save block.
17716     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17717     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17718     MBB->addSuccessor(EndMBB);
17719   }
17720
17721   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17722   // that was just emitted, but clearly shouldn't be "saved".
17723   assert((MI->getNumOperands() <= 3 ||
17724           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17725           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17726          && "Expected last argument to be EFLAGS");
17727   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17728   // In the XMM save block, save all the XMM argument registers.
17729   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17730     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17731     MachineMemOperand *MMO =
17732       F->getMachineMemOperand(
17733           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17734         MachineMemOperand::MOStore,
17735         /*Size=*/16, /*Align=*/16);
17736     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17737       .addFrameIndex(RegSaveFrameIndex)
17738       .addImm(/*Scale=*/1)
17739       .addReg(/*IndexReg=*/0)
17740       .addImm(/*Disp=*/Offset)
17741       .addReg(/*Segment=*/0)
17742       .addReg(MI->getOperand(i).getReg())
17743       .addMemOperand(MMO);
17744   }
17745
17746   MI->eraseFromParent();   // The pseudo instruction is gone now.
17747
17748   return EndMBB;
17749 }
17750
17751 // The EFLAGS operand of SelectItr might be missing a kill marker
17752 // because there were multiple uses of EFLAGS, and ISel didn't know
17753 // which to mark. Figure out whether SelectItr should have had a
17754 // kill marker, and set it if it should. Returns the correct kill
17755 // marker value.
17756 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17757                                      MachineBasicBlock* BB,
17758                                      const TargetRegisterInfo* TRI) {
17759   // Scan forward through BB for a use/def of EFLAGS.
17760   MachineBasicBlock::iterator miI(std::next(SelectItr));
17761   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17762     const MachineInstr& mi = *miI;
17763     if (mi.readsRegister(X86::EFLAGS))
17764       return false;
17765     if (mi.definesRegister(X86::EFLAGS))
17766       break; // Should have kill-flag - update below.
17767   }
17768
17769   // If we hit the end of the block, check whether EFLAGS is live into a
17770   // successor.
17771   if (miI == BB->end()) {
17772     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17773                                           sEnd = BB->succ_end();
17774          sItr != sEnd; ++sItr) {
17775       MachineBasicBlock* succ = *sItr;
17776       if (succ->isLiveIn(X86::EFLAGS))
17777         return false;
17778     }
17779   }
17780
17781   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17782   // out. SelectMI should have a kill flag on EFLAGS.
17783   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17784   return true;
17785 }
17786
17787 MachineBasicBlock *
17788 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17789                                      MachineBasicBlock *BB) const {
17790   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17791   DebugLoc DL = MI->getDebugLoc();
17792
17793   // To "insert" a SELECT_CC instruction, we actually have to insert the
17794   // diamond control-flow pattern.  The incoming instruction knows the
17795   // destination vreg to set, the condition code register to branch on, the
17796   // true/false values to select between, and a branch opcode to use.
17797   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17798   MachineFunction::iterator It = BB;
17799   ++It;
17800
17801   //  thisMBB:
17802   //  ...
17803   //   TrueVal = ...
17804   //   cmpTY ccX, r1, r2
17805   //   bCC copy1MBB
17806   //   fallthrough --> copy0MBB
17807   MachineBasicBlock *thisMBB = BB;
17808   MachineFunction *F = BB->getParent();
17809   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17810   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17811   F->insert(It, copy0MBB);
17812   F->insert(It, sinkMBB);
17813
17814   // If the EFLAGS register isn't dead in the terminator, then claim that it's
17815   // live into the sink and copy blocks.
17816   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17817   if (!MI->killsRegister(X86::EFLAGS) &&
17818       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17819     copy0MBB->addLiveIn(X86::EFLAGS);
17820     sinkMBB->addLiveIn(X86::EFLAGS);
17821   }
17822
17823   // Transfer the remainder of BB and its successor edges to sinkMBB.
17824   sinkMBB->splice(sinkMBB->begin(), BB,
17825                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
17826   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17827
17828   // Add the true and fallthrough blocks as its successors.
17829   BB->addSuccessor(copy0MBB);
17830   BB->addSuccessor(sinkMBB);
17831
17832   // Create the conditional branch instruction.
17833   unsigned Opc =
17834     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17835   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17836
17837   //  copy0MBB:
17838   //   %FalseValue = ...
17839   //   # fallthrough to sinkMBB
17840   copy0MBB->addSuccessor(sinkMBB);
17841
17842   //  sinkMBB:
17843   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17844   //  ...
17845   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17846           TII->get(X86::PHI), MI->getOperand(0).getReg())
17847     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17848     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17849
17850   MI->eraseFromParent();   // The pseudo instruction is gone now.
17851   return sinkMBB;
17852 }
17853
17854 MachineBasicBlock *
17855 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17856                                         bool Is64Bit) const {
17857   MachineFunction *MF = BB->getParent();
17858   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17859   DebugLoc DL = MI->getDebugLoc();
17860   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17861
17862   assert(MF->shouldSplitStack());
17863
17864   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17865   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17866
17867   // BB:
17868   //  ... [Till the alloca]
17869   // If stacklet is not large enough, jump to mallocMBB
17870   //
17871   // bumpMBB:
17872   //  Allocate by subtracting from RSP
17873   //  Jump to continueMBB
17874   //
17875   // mallocMBB:
17876   //  Allocate by call to runtime
17877   //
17878   // continueMBB:
17879   //  ...
17880   //  [rest of original BB]
17881   //
17882
17883   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17884   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17885   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17886
17887   MachineRegisterInfo &MRI = MF->getRegInfo();
17888   const TargetRegisterClass *AddrRegClass =
17889     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17890
17891   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17892     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17893     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17894     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17895     sizeVReg = MI->getOperand(1).getReg(),
17896     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17897
17898   MachineFunction::iterator MBBIter = BB;
17899   ++MBBIter;
17900
17901   MF->insert(MBBIter, bumpMBB);
17902   MF->insert(MBBIter, mallocMBB);
17903   MF->insert(MBBIter, continueMBB);
17904
17905   continueMBB->splice(continueMBB->begin(), BB,
17906                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
17907   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17908
17909   // Add code to the main basic block to check if the stack limit has been hit,
17910   // and if so, jump to mallocMBB otherwise to bumpMBB.
17911   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17912   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17913     .addReg(tmpSPVReg).addReg(sizeVReg);
17914   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17915     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17916     .addReg(SPLimitVReg);
17917   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17918
17919   // bumpMBB simply decreases the stack pointer, since we know the current
17920   // stacklet has enough space.
17921   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17922     .addReg(SPLimitVReg);
17923   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17924     .addReg(SPLimitVReg);
17925   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17926
17927   // Calls into a routine in libgcc to allocate more space from the heap.
17928   const uint32_t *RegMask =
17929     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17930   if (Is64Bit) {
17931     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17932       .addReg(sizeVReg);
17933     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17934       .addExternalSymbol("__morestack_allocate_stack_space")
17935       .addRegMask(RegMask)
17936       .addReg(X86::RDI, RegState::Implicit)
17937       .addReg(X86::RAX, RegState::ImplicitDefine);
17938   } else {
17939     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17940       .addImm(12);
17941     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17942     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17943       .addExternalSymbol("__morestack_allocate_stack_space")
17944       .addRegMask(RegMask)
17945       .addReg(X86::EAX, RegState::ImplicitDefine);
17946   }
17947
17948   if (!Is64Bit)
17949     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17950       .addImm(16);
17951
17952   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17953     .addReg(Is64Bit ? X86::RAX : X86::EAX);
17954   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17955
17956   // Set up the CFG correctly.
17957   BB->addSuccessor(bumpMBB);
17958   BB->addSuccessor(mallocMBB);
17959   mallocMBB->addSuccessor(continueMBB);
17960   bumpMBB->addSuccessor(continueMBB);
17961
17962   // Take care of the PHI nodes.
17963   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17964           MI->getOperand(0).getReg())
17965     .addReg(mallocPtrVReg).addMBB(mallocMBB)
17966     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17967
17968   // Delete the original pseudo instruction.
17969   MI->eraseFromParent();
17970
17971   // And we're done.
17972   return continueMBB;
17973 }
17974
17975 MachineBasicBlock *
17976 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17977                                         MachineBasicBlock *BB) const {
17978   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17979   DebugLoc DL = MI->getDebugLoc();
17980
17981   assert(!Subtarget->isTargetMacho());
17982
17983   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
17984   // non-trivial part is impdef of ESP.
17985
17986   if (Subtarget->isTargetWin64()) {
17987     if (Subtarget->isTargetCygMing()) {
17988       // ___chkstk(Mingw64):
17989       // Clobbers R10, R11, RAX and EFLAGS.
17990       // Updates RSP.
17991       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17992         .addExternalSymbol("___chkstk")
17993         .addReg(X86::RAX, RegState::Implicit)
17994         .addReg(X86::RSP, RegState::Implicit)
17995         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17996         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17997         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17998     } else {
17999       // __chkstk(MSVCRT): does not update stack pointer.
18000       // Clobbers R10, R11 and EFLAGS.
18001       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18002         .addExternalSymbol("__chkstk")
18003         .addReg(X86::RAX, RegState::Implicit)
18004         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18005       // RAX has the offset to be subtracted from RSP.
18006       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18007         .addReg(X86::RSP)
18008         .addReg(X86::RAX);
18009     }
18010   } else {
18011     const char *StackProbeSymbol =
18012       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18013
18014     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18015       .addExternalSymbol(StackProbeSymbol)
18016       .addReg(X86::EAX, RegState::Implicit)
18017       .addReg(X86::ESP, RegState::Implicit)
18018       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18019       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18020       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18021   }
18022
18023   MI->eraseFromParent();   // The pseudo instruction is gone now.
18024   return BB;
18025 }
18026
18027 MachineBasicBlock *
18028 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18029                                       MachineBasicBlock *BB) const {
18030   // This is pretty easy.  We're taking the value that we received from
18031   // our load from the relocation, sticking it in either RDI (x86-64)
18032   // or EAX and doing an indirect call.  The return value will then
18033   // be in the normal return register.
18034   MachineFunction *F = BB->getParent();
18035   const X86InstrInfo *TII
18036     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
18037   DebugLoc DL = MI->getDebugLoc();
18038
18039   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18040   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18041
18042   // Get a register mask for the lowered call.
18043   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18044   // proper register mask.
18045   const uint32_t *RegMask =
18046     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18047   if (Subtarget->is64Bit()) {
18048     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18049                                       TII->get(X86::MOV64rm), X86::RDI)
18050     .addReg(X86::RIP)
18051     .addImm(0).addReg(0)
18052     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18053                       MI->getOperand(3).getTargetFlags())
18054     .addReg(0);
18055     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18056     addDirectMem(MIB, X86::RDI);
18057     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18058   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18059     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18060                                       TII->get(X86::MOV32rm), X86::EAX)
18061     .addReg(0)
18062     .addImm(0).addReg(0)
18063     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18064                       MI->getOperand(3).getTargetFlags())
18065     .addReg(0);
18066     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18067     addDirectMem(MIB, X86::EAX);
18068     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18069   } else {
18070     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18071                                       TII->get(X86::MOV32rm), X86::EAX)
18072     .addReg(TII->getGlobalBaseReg(F))
18073     .addImm(0).addReg(0)
18074     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18075                       MI->getOperand(3).getTargetFlags())
18076     .addReg(0);
18077     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18078     addDirectMem(MIB, X86::EAX);
18079     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18080   }
18081
18082   MI->eraseFromParent(); // The pseudo instruction is gone now.
18083   return BB;
18084 }
18085
18086 MachineBasicBlock *
18087 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18088                                     MachineBasicBlock *MBB) const {
18089   DebugLoc DL = MI->getDebugLoc();
18090   MachineFunction *MF = MBB->getParent();
18091   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18092   MachineRegisterInfo &MRI = MF->getRegInfo();
18093
18094   const BasicBlock *BB = MBB->getBasicBlock();
18095   MachineFunction::iterator I = MBB;
18096   ++I;
18097
18098   // Memory Reference
18099   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18100   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18101
18102   unsigned DstReg;
18103   unsigned MemOpndSlot = 0;
18104
18105   unsigned CurOp = 0;
18106
18107   DstReg = MI->getOperand(CurOp++).getReg();
18108   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18109   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18110   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18111   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18112
18113   MemOpndSlot = CurOp;
18114
18115   MVT PVT = getPointerTy();
18116   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18117          "Invalid Pointer Size!");
18118
18119   // For v = setjmp(buf), we generate
18120   //
18121   // thisMBB:
18122   //  buf[LabelOffset] = restoreMBB
18123   //  SjLjSetup restoreMBB
18124   //
18125   // mainMBB:
18126   //  v_main = 0
18127   //
18128   // sinkMBB:
18129   //  v = phi(main, restore)
18130   //
18131   // restoreMBB:
18132   //  v_restore = 1
18133
18134   MachineBasicBlock *thisMBB = MBB;
18135   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18136   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18137   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18138   MF->insert(I, mainMBB);
18139   MF->insert(I, sinkMBB);
18140   MF->push_back(restoreMBB);
18141
18142   MachineInstrBuilder MIB;
18143
18144   // Transfer the remainder of BB and its successor edges to sinkMBB.
18145   sinkMBB->splice(sinkMBB->begin(), MBB,
18146                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18147   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18148
18149   // thisMBB:
18150   unsigned PtrStoreOpc = 0;
18151   unsigned LabelReg = 0;
18152   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18153   Reloc::Model RM = MF->getTarget().getRelocationModel();
18154   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18155                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18156
18157   // Prepare IP either in reg or imm.
18158   if (!UseImmLabel) {
18159     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18160     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18161     LabelReg = MRI.createVirtualRegister(PtrRC);
18162     if (Subtarget->is64Bit()) {
18163       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18164               .addReg(X86::RIP)
18165               .addImm(0)
18166               .addReg(0)
18167               .addMBB(restoreMBB)
18168               .addReg(0);
18169     } else {
18170       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18171       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18172               .addReg(XII->getGlobalBaseReg(MF))
18173               .addImm(0)
18174               .addReg(0)
18175               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18176               .addReg(0);
18177     }
18178   } else
18179     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18180   // Store IP
18181   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18182   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18183     if (i == X86::AddrDisp)
18184       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18185     else
18186       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18187   }
18188   if (!UseImmLabel)
18189     MIB.addReg(LabelReg);
18190   else
18191     MIB.addMBB(restoreMBB);
18192   MIB.setMemRefs(MMOBegin, MMOEnd);
18193   // Setup
18194   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18195           .addMBB(restoreMBB);
18196
18197   const X86RegisterInfo *RegInfo =
18198     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18199   MIB.addRegMask(RegInfo->getNoPreservedMask());
18200   thisMBB->addSuccessor(mainMBB);
18201   thisMBB->addSuccessor(restoreMBB);
18202
18203   // mainMBB:
18204   //  EAX = 0
18205   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18206   mainMBB->addSuccessor(sinkMBB);
18207
18208   // sinkMBB:
18209   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18210           TII->get(X86::PHI), DstReg)
18211     .addReg(mainDstReg).addMBB(mainMBB)
18212     .addReg(restoreDstReg).addMBB(restoreMBB);
18213
18214   // restoreMBB:
18215   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18216   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18217   restoreMBB->addSuccessor(sinkMBB);
18218
18219   MI->eraseFromParent();
18220   return sinkMBB;
18221 }
18222
18223 MachineBasicBlock *
18224 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18225                                      MachineBasicBlock *MBB) const {
18226   DebugLoc DL = MI->getDebugLoc();
18227   MachineFunction *MF = MBB->getParent();
18228   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18229   MachineRegisterInfo &MRI = MF->getRegInfo();
18230
18231   // Memory Reference
18232   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18233   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18234
18235   MVT PVT = getPointerTy();
18236   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18237          "Invalid Pointer Size!");
18238
18239   const TargetRegisterClass *RC =
18240     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18241   unsigned Tmp = MRI.createVirtualRegister(RC);
18242   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18243   const X86RegisterInfo *RegInfo =
18244     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18245   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18246   unsigned SP = RegInfo->getStackRegister();
18247
18248   MachineInstrBuilder MIB;
18249
18250   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18251   const int64_t SPOffset = 2 * PVT.getStoreSize();
18252
18253   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18254   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18255
18256   // Reload FP
18257   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18258   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18259     MIB.addOperand(MI->getOperand(i));
18260   MIB.setMemRefs(MMOBegin, MMOEnd);
18261   // Reload IP
18262   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18263   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18264     if (i == X86::AddrDisp)
18265       MIB.addDisp(MI->getOperand(i), LabelOffset);
18266     else
18267       MIB.addOperand(MI->getOperand(i));
18268   }
18269   MIB.setMemRefs(MMOBegin, MMOEnd);
18270   // Reload SP
18271   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18272   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18273     if (i == X86::AddrDisp)
18274       MIB.addDisp(MI->getOperand(i), SPOffset);
18275     else
18276       MIB.addOperand(MI->getOperand(i));
18277   }
18278   MIB.setMemRefs(MMOBegin, MMOEnd);
18279   // Jump
18280   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18281
18282   MI->eraseFromParent();
18283   return MBB;
18284 }
18285
18286 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18287 // accumulator loops. Writing back to the accumulator allows the coalescer
18288 // to remove extra copies in the loop.   
18289 MachineBasicBlock *
18290 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18291                                  MachineBasicBlock *MBB) const {
18292   MachineOperand &AddendOp = MI->getOperand(3);
18293
18294   // Bail out early if the addend isn't a register - we can't switch these.
18295   if (!AddendOp.isReg())
18296     return MBB;
18297
18298   MachineFunction &MF = *MBB->getParent();
18299   MachineRegisterInfo &MRI = MF.getRegInfo();
18300
18301   // Check whether the addend is defined by a PHI:
18302   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18303   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18304   if (!AddendDef.isPHI())
18305     return MBB;
18306
18307   // Look for the following pattern:
18308   // loop:
18309   //   %addend = phi [%entry, 0], [%loop, %result]
18310   //   ...
18311   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18312
18313   // Replace with:
18314   //   loop:
18315   //   %addend = phi [%entry, 0], [%loop, %result]
18316   //   ...
18317   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18318
18319   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18320     assert(AddendDef.getOperand(i).isReg());
18321     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18322     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18323     if (&PHISrcInst == MI) {
18324       // Found a matching instruction.
18325       unsigned NewFMAOpc = 0;
18326       switch (MI->getOpcode()) {
18327         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18328         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18329         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18330         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18331         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18332         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18333         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18334         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18335         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18336         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18337         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18338         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18339         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18340         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18341         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18342         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18343         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18344         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18345         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18346         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18347         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18348         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18349         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18350         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18351         default: llvm_unreachable("Unrecognized FMA variant.");
18352       }
18353
18354       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18355       MachineInstrBuilder MIB =
18356         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18357         .addOperand(MI->getOperand(0))
18358         .addOperand(MI->getOperand(3))
18359         .addOperand(MI->getOperand(2))
18360         .addOperand(MI->getOperand(1));
18361       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18362       MI->eraseFromParent();
18363     }
18364   }
18365
18366   return MBB;
18367 }
18368
18369 MachineBasicBlock *
18370 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18371                                                MachineBasicBlock *BB) const {
18372   switch (MI->getOpcode()) {
18373   default: llvm_unreachable("Unexpected instr type to insert");
18374   case X86::TAILJMPd64:
18375   case X86::TAILJMPr64:
18376   case X86::TAILJMPm64:
18377     llvm_unreachable("TAILJMP64 would not be touched here.");
18378   case X86::TCRETURNdi64:
18379   case X86::TCRETURNri64:
18380   case X86::TCRETURNmi64:
18381     return BB;
18382   case X86::WIN_ALLOCA:
18383     return EmitLoweredWinAlloca(MI, BB);
18384   case X86::SEG_ALLOCA_32:
18385     return EmitLoweredSegAlloca(MI, BB, false);
18386   case X86::SEG_ALLOCA_64:
18387     return EmitLoweredSegAlloca(MI, BB, true);
18388   case X86::TLSCall_32:
18389   case X86::TLSCall_64:
18390     return EmitLoweredTLSCall(MI, BB);
18391   case X86::CMOV_GR8:
18392   case X86::CMOV_FR32:
18393   case X86::CMOV_FR64:
18394   case X86::CMOV_V4F32:
18395   case X86::CMOV_V2F64:
18396   case X86::CMOV_V2I64:
18397   case X86::CMOV_V8F32:
18398   case X86::CMOV_V4F64:
18399   case X86::CMOV_V4I64:
18400   case X86::CMOV_V16F32:
18401   case X86::CMOV_V8F64:
18402   case X86::CMOV_V8I64:
18403   case X86::CMOV_GR16:
18404   case X86::CMOV_GR32:
18405   case X86::CMOV_RFP32:
18406   case X86::CMOV_RFP64:
18407   case X86::CMOV_RFP80:
18408     return EmitLoweredSelect(MI, BB);
18409
18410   case X86::FP32_TO_INT16_IN_MEM:
18411   case X86::FP32_TO_INT32_IN_MEM:
18412   case X86::FP32_TO_INT64_IN_MEM:
18413   case X86::FP64_TO_INT16_IN_MEM:
18414   case X86::FP64_TO_INT32_IN_MEM:
18415   case X86::FP64_TO_INT64_IN_MEM:
18416   case X86::FP80_TO_INT16_IN_MEM:
18417   case X86::FP80_TO_INT32_IN_MEM:
18418   case X86::FP80_TO_INT64_IN_MEM: {
18419     MachineFunction *F = BB->getParent();
18420     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18421     DebugLoc DL = MI->getDebugLoc();
18422
18423     // Change the floating point control register to use "round towards zero"
18424     // mode when truncating to an integer value.
18425     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18426     addFrameReference(BuildMI(*BB, MI, DL,
18427                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18428
18429     // Load the old value of the high byte of the control word...
18430     unsigned OldCW =
18431       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18432     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18433                       CWFrameIdx);
18434
18435     // Set the high part to be round to zero...
18436     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18437       .addImm(0xC7F);
18438
18439     // Reload the modified control word now...
18440     addFrameReference(BuildMI(*BB, MI, DL,
18441                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18442
18443     // Restore the memory image of control word to original value
18444     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18445       .addReg(OldCW);
18446
18447     // Get the X86 opcode to use.
18448     unsigned Opc;
18449     switch (MI->getOpcode()) {
18450     default: llvm_unreachable("illegal opcode!");
18451     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18452     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18453     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18454     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18455     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18456     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18457     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18458     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18459     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18460     }
18461
18462     X86AddressMode AM;
18463     MachineOperand &Op = MI->getOperand(0);
18464     if (Op.isReg()) {
18465       AM.BaseType = X86AddressMode::RegBase;
18466       AM.Base.Reg = Op.getReg();
18467     } else {
18468       AM.BaseType = X86AddressMode::FrameIndexBase;
18469       AM.Base.FrameIndex = Op.getIndex();
18470     }
18471     Op = MI->getOperand(1);
18472     if (Op.isImm())
18473       AM.Scale = Op.getImm();
18474     Op = MI->getOperand(2);
18475     if (Op.isImm())
18476       AM.IndexReg = Op.getImm();
18477     Op = MI->getOperand(3);
18478     if (Op.isGlobal()) {
18479       AM.GV = Op.getGlobal();
18480     } else {
18481       AM.Disp = Op.getImm();
18482     }
18483     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18484                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18485
18486     // Reload the original control word now.
18487     addFrameReference(BuildMI(*BB, MI, DL,
18488                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18489
18490     MI->eraseFromParent();   // The pseudo instruction is gone now.
18491     return BB;
18492   }
18493     // String/text processing lowering.
18494   case X86::PCMPISTRM128REG:
18495   case X86::VPCMPISTRM128REG:
18496   case X86::PCMPISTRM128MEM:
18497   case X86::VPCMPISTRM128MEM:
18498   case X86::PCMPESTRM128REG:
18499   case X86::VPCMPESTRM128REG:
18500   case X86::PCMPESTRM128MEM:
18501   case X86::VPCMPESTRM128MEM:
18502     assert(Subtarget->hasSSE42() &&
18503            "Target must have SSE4.2 or AVX features enabled");
18504     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18505
18506   // String/text processing lowering.
18507   case X86::PCMPISTRIREG:
18508   case X86::VPCMPISTRIREG:
18509   case X86::PCMPISTRIMEM:
18510   case X86::VPCMPISTRIMEM:
18511   case X86::PCMPESTRIREG:
18512   case X86::VPCMPESTRIREG:
18513   case X86::PCMPESTRIMEM:
18514   case X86::VPCMPESTRIMEM:
18515     assert(Subtarget->hasSSE42() &&
18516            "Target must have SSE4.2 or AVX features enabled");
18517     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18518
18519   // Thread synchronization.
18520   case X86::MONITOR:
18521     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18522
18523   // xbegin
18524   case X86::XBEGIN:
18525     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18526
18527   case X86::VASTART_SAVE_XMM_REGS:
18528     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18529
18530   case X86::VAARG_64:
18531     return EmitVAARG64WithCustomInserter(MI, BB);
18532
18533   case X86::EH_SjLj_SetJmp32:
18534   case X86::EH_SjLj_SetJmp64:
18535     return emitEHSjLjSetJmp(MI, BB);
18536
18537   case X86::EH_SjLj_LongJmp32:
18538   case X86::EH_SjLj_LongJmp64:
18539     return emitEHSjLjLongJmp(MI, BB);
18540
18541   case TargetOpcode::STACKMAP:
18542   case TargetOpcode::PATCHPOINT:
18543     return emitPatchPoint(MI, BB);
18544
18545   case X86::VFMADDPDr213r:
18546   case X86::VFMADDPSr213r:
18547   case X86::VFMADDSDr213r:
18548   case X86::VFMADDSSr213r:
18549   case X86::VFMSUBPDr213r:
18550   case X86::VFMSUBPSr213r:
18551   case X86::VFMSUBSDr213r:
18552   case X86::VFMSUBSSr213r:
18553   case X86::VFNMADDPDr213r:
18554   case X86::VFNMADDPSr213r:
18555   case X86::VFNMADDSDr213r:
18556   case X86::VFNMADDSSr213r:
18557   case X86::VFNMSUBPDr213r:
18558   case X86::VFNMSUBPSr213r:
18559   case X86::VFNMSUBSDr213r:
18560   case X86::VFNMSUBSSr213r:
18561   case X86::VFMADDPDr213rY:
18562   case X86::VFMADDPSr213rY:
18563   case X86::VFMSUBPDr213rY:
18564   case X86::VFMSUBPSr213rY:
18565   case X86::VFNMADDPDr213rY:
18566   case X86::VFNMADDPSr213rY:
18567   case X86::VFNMSUBPDr213rY:
18568   case X86::VFNMSUBPSr213rY:
18569     return emitFMA3Instr(MI, BB);
18570   }
18571 }
18572
18573 //===----------------------------------------------------------------------===//
18574 //                           X86 Optimization Hooks
18575 //===----------------------------------------------------------------------===//
18576
18577 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18578                                                       APInt &KnownZero,
18579                                                       APInt &KnownOne,
18580                                                       const SelectionDAG &DAG,
18581                                                       unsigned Depth) const {
18582   unsigned BitWidth = KnownZero.getBitWidth();
18583   unsigned Opc = Op.getOpcode();
18584   assert((Opc >= ISD::BUILTIN_OP_END ||
18585           Opc == ISD::INTRINSIC_WO_CHAIN ||
18586           Opc == ISD::INTRINSIC_W_CHAIN ||
18587           Opc == ISD::INTRINSIC_VOID) &&
18588          "Should use MaskedValueIsZero if you don't know whether Op"
18589          " is a target node!");
18590
18591   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18592   switch (Opc) {
18593   default: break;
18594   case X86ISD::ADD:
18595   case X86ISD::SUB:
18596   case X86ISD::ADC:
18597   case X86ISD::SBB:
18598   case X86ISD::SMUL:
18599   case X86ISD::UMUL:
18600   case X86ISD::INC:
18601   case X86ISD::DEC:
18602   case X86ISD::OR:
18603   case X86ISD::XOR:
18604   case X86ISD::AND:
18605     // These nodes' second result is a boolean.
18606     if (Op.getResNo() == 0)
18607       break;
18608     // Fallthrough
18609   case X86ISD::SETCC:
18610     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18611     break;
18612   case ISD::INTRINSIC_WO_CHAIN: {
18613     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18614     unsigned NumLoBits = 0;
18615     switch (IntId) {
18616     default: break;
18617     case Intrinsic::x86_sse_movmsk_ps:
18618     case Intrinsic::x86_avx_movmsk_ps_256:
18619     case Intrinsic::x86_sse2_movmsk_pd:
18620     case Intrinsic::x86_avx_movmsk_pd_256:
18621     case Intrinsic::x86_mmx_pmovmskb:
18622     case Intrinsic::x86_sse2_pmovmskb_128:
18623     case Intrinsic::x86_avx2_pmovmskb: {
18624       // High bits of movmskp{s|d}, pmovmskb are known zero.
18625       switch (IntId) {
18626         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18627         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18628         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18629         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18630         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18631         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18632         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18633         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18634       }
18635       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18636       break;
18637     }
18638     }
18639     break;
18640   }
18641   }
18642 }
18643
18644 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18645   SDValue Op,
18646   const SelectionDAG &,
18647   unsigned Depth) const {
18648   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18649   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18650     return Op.getValueType().getScalarType().getSizeInBits();
18651
18652   // Fallback case.
18653   return 1;
18654 }
18655
18656 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18657 /// node is a GlobalAddress + offset.
18658 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18659                                        const GlobalValue* &GA,
18660                                        int64_t &Offset) const {
18661   if (N->getOpcode() == X86ISD::Wrapper) {
18662     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18663       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18664       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18665       return true;
18666     }
18667   }
18668   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18669 }
18670
18671 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18672 /// same as extracting the high 128-bit part of 256-bit vector and then
18673 /// inserting the result into the low part of a new 256-bit vector
18674 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18675   EVT VT = SVOp->getValueType(0);
18676   unsigned NumElems = VT.getVectorNumElements();
18677
18678   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18679   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18680     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18681         SVOp->getMaskElt(j) >= 0)
18682       return false;
18683
18684   return true;
18685 }
18686
18687 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18688 /// same as extracting the low 128-bit part of 256-bit vector and then
18689 /// inserting the result into the high part of a new 256-bit vector
18690 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18691   EVT VT = SVOp->getValueType(0);
18692   unsigned NumElems = VT.getVectorNumElements();
18693
18694   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18695   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18696     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18697         SVOp->getMaskElt(j) >= 0)
18698       return false;
18699
18700   return true;
18701 }
18702
18703 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18704 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18705                                         TargetLowering::DAGCombinerInfo &DCI,
18706                                         const X86Subtarget* Subtarget) {
18707   SDLoc dl(N);
18708   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18709   SDValue V1 = SVOp->getOperand(0);
18710   SDValue V2 = SVOp->getOperand(1);
18711   EVT VT = SVOp->getValueType(0);
18712   unsigned NumElems = VT.getVectorNumElements();
18713
18714   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18715       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18716     //
18717     //                   0,0,0,...
18718     //                      |
18719     //    V      UNDEF    BUILD_VECTOR    UNDEF
18720     //     \      /           \           /
18721     //  CONCAT_VECTOR         CONCAT_VECTOR
18722     //         \                  /
18723     //          \                /
18724     //          RESULT: V + zero extended
18725     //
18726     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18727         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18728         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18729       return SDValue();
18730
18731     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18732       return SDValue();
18733
18734     // To match the shuffle mask, the first half of the mask should
18735     // be exactly the first vector, and all the rest a splat with the
18736     // first element of the second one.
18737     for (unsigned i = 0; i != NumElems/2; ++i)
18738       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18739           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18740         return SDValue();
18741
18742     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18743     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18744       if (Ld->hasNUsesOfValue(1, 0)) {
18745         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18746         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18747         SDValue ResNode =
18748           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18749                                   Ld->getMemoryVT(),
18750                                   Ld->getPointerInfo(),
18751                                   Ld->getAlignment(),
18752                                   false/*isVolatile*/, true/*ReadMem*/,
18753                                   false/*WriteMem*/);
18754
18755         // Make sure the newly-created LOAD is in the same position as Ld in
18756         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18757         // and update uses of Ld's output chain to use the TokenFactor.
18758         if (Ld->hasAnyUseOfValue(1)) {
18759           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18760                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18761           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18762           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18763                                  SDValue(ResNode.getNode(), 1));
18764         }
18765
18766         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18767       }
18768     }
18769
18770     // Emit a zeroed vector and insert the desired subvector on its
18771     // first half.
18772     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18773     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18774     return DCI.CombineTo(N, InsV);
18775   }
18776
18777   //===--------------------------------------------------------------------===//
18778   // Combine some shuffles into subvector extracts and inserts:
18779   //
18780
18781   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18782   if (isShuffleHigh128VectorInsertLow(SVOp)) {
18783     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18784     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18785     return DCI.CombineTo(N, InsV);
18786   }
18787
18788   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18789   if (isShuffleLow128VectorInsertHigh(SVOp)) {
18790     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18791     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18792     return DCI.CombineTo(N, InsV);
18793   }
18794
18795   return SDValue();
18796 }
18797
18798 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
18799 /// possible.
18800 ///
18801 /// This is the leaf of the recursive combinine below. When we have found some
18802 /// chain of single-use x86 shuffle instructions and accumulated the combined
18803 /// shuffle mask represented by them, this will try to pattern match that mask
18804 /// into either a single instruction if there is a special purpose instruction
18805 /// for this operation, or into a PSHUFB instruction which is a fully general
18806 /// instruction but should only be used to replace chains over a certain depth.
18807 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
18808                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
18809                                    TargetLowering::DAGCombinerInfo &DCI,
18810                                    const X86Subtarget *Subtarget) {
18811   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
18812
18813   // Find the operand that enters the chain. Note that multiple uses are OK
18814   // here, we're not going to remove the operand we find.
18815   SDValue Input = Op.getOperand(0);
18816   while (Input.getOpcode() == ISD::BITCAST)
18817     Input = Input.getOperand(0);
18818
18819   MVT VT = Input.getSimpleValueType();
18820   MVT RootVT = Root.getSimpleValueType();
18821   SDLoc DL(Root);
18822
18823   // Just remove no-op shuffle masks.
18824   if (Mask.size() == 1) {
18825     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
18826                   /*AddTo*/ true);
18827     return true;
18828   }
18829
18830   // Use the float domain if the operand type is a floating point type.
18831   bool FloatDomain = VT.isFloatingPoint();
18832
18833   // If we don't have access to VEX encodings, the generic PSHUF instructions
18834   // are preferable to some of the specialized forms despite requiring one more
18835   // byte to encode because they can implicitly copy.
18836   //
18837   // IF we *do* have VEX encodings, than we can use shorter, more specific
18838   // shuffle instructions freely as they can copy due to the extra register
18839   // operand.
18840   if (Subtarget->hasAVX()) {
18841     // We have both floating point and integer variants of shuffles that dup
18842     // either the low or high half of the vector.
18843     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
18844       bool Lo = Mask.equals(0, 0);
18845       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
18846                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
18847       if (Depth == 1 && Root->getOpcode() == Shuffle)
18848         return false; // Nothing to do!
18849       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
18850       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
18851       DCI.AddToWorklist(Op.getNode());
18852       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
18853       DCI.AddToWorklist(Op.getNode());
18854       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
18855                     /*AddTo*/ true);
18856       return true;
18857     }
18858
18859     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
18860
18861     // For the integer domain we have specialized instructions for duplicating
18862     // any element size from the low or high half.
18863     if (!FloatDomain &&
18864         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
18865          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
18866          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
18867          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
18868          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
18869                      15))) {
18870       bool Lo = Mask[0] == 0;
18871       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
18872       if (Depth == 1 && Root->getOpcode() == Shuffle)
18873         return false; // Nothing to do!
18874       MVT ShuffleVT;
18875       switch (Mask.size()) {
18876       case 4: ShuffleVT = MVT::v4i32; break;
18877       case 8: ShuffleVT = MVT::v8i16; break;
18878       case 16: ShuffleVT = MVT::v16i8; break;
18879       };
18880       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
18881       DCI.AddToWorklist(Op.getNode());
18882       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
18883       DCI.AddToWorklist(Op.getNode());
18884       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
18885                     /*AddTo*/ true);
18886       return true;
18887     }
18888   }
18889
18890   // Don't try to re-form single instruction chains under any circumstances now
18891   // that we've done encoding canonicalization for them.
18892   if (Depth < 2)
18893     return false;
18894
18895   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
18896   // can replace them with a single PSHUFB instruction profitably. Intel's
18897   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
18898   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
18899   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
18900     SmallVector<SDValue, 16> PSHUFBMask;
18901     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
18902     int Ratio = 16 / Mask.size();
18903     for (unsigned i = 0; i < 16; ++i) {
18904       int M = Ratio * Mask[i / Ratio] + i % Ratio;
18905       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
18906     }
18907     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
18908     DCI.AddToWorklist(Op.getNode());
18909     SDValue PSHUFBMaskOp =
18910         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
18911     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
18912     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
18913     DCI.AddToWorklist(Op.getNode());
18914     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
18915                   /*AddTo*/ true);
18916     return true;
18917   }
18918
18919   // Failed to find any combines.
18920   return false;
18921 }
18922
18923 /// \brief Fully generic combining of x86 shuffle instructions.
18924 ///
18925 /// This should be the last combine run over the x86 shuffle instructions. Once
18926 /// they have been fully optimized, this will recursively consdier all chains
18927 /// of single-use shuffle instructions, build a generic model of the cumulative
18928 /// shuffle operation, and check for simpler instructions which implement this
18929 /// operation. We use this primarily for two purposes:
18930 ///
18931 /// 1) Collapse generic shuffles to specialized single instructions when
18932 ///    equivalent. In most cases, this is just an encoding size win, but
18933 ///    sometimes we will collapse multiple generic shuffles into a single
18934 ///    special-purpose shuffle.
18935 /// 2) Look for sequences of shuffle instructions with 3 or more total
18936 ///    instructions, and replace them with the slightly more expensive SSSE3
18937 ///    PSHUFB instruction if available. We do this as the last combining step
18938 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
18939 ///    a suitable short sequence of other instructions. The PHUFB will either
18940 ///    use a register or have to read from memory and so is slightly (but only
18941 ///    slightly) more expensive than the other shuffle instructions.
18942 ///
18943 /// Because this is inherently a quadratic operation (for each shuffle in
18944 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
18945 /// This should never be an issue in practice as the shuffle lowering doesn't
18946 /// produce sequences of more than 8 instructions.
18947 ///
18948 /// FIXME: We will currently miss some cases where the redundant shuffling
18949 /// would simplify under the threshold for PSHUFB formation because of
18950 /// combine-ordering. To fix this, we should do the redundant instruction
18951 /// combining in this recursive walk.
18952 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
18953                                           ArrayRef<int> IncomingMask, int Depth,
18954                                           bool HasPSHUFB, SelectionDAG &DAG,
18955                                           TargetLowering::DAGCombinerInfo &DCI,
18956                                           const X86Subtarget *Subtarget) {
18957   // Bound the depth of our recursive combine because this is ultimately
18958   // quadratic in nature.
18959   if (Depth > 8)
18960     return false;
18961
18962   // Directly rip through bitcasts to find the underlying operand.
18963   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
18964     Op = Op.getOperand(0);
18965
18966   MVT VT = Op.getSimpleValueType();
18967   if (!VT.isVector())
18968     return false; // Bail if we hit a non-vector.
18969   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
18970   // version should be added.
18971   if (VT.getSizeInBits() != 128)
18972     return false;
18973
18974   assert(Root.getSimpleValueType().isVector() &&
18975          "Shuffles operate on vector types!");
18976   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
18977          "Can only combine shuffles of the same vector register size.");
18978
18979   if (!isTargetShuffle(Op.getOpcode()))
18980     return false;
18981   SmallVector<int, 16> OpMask;
18982   bool IsUnary;
18983   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
18984   // We only can combine unary shuffles which we can decode the mask for.
18985   if (!HaveMask || !IsUnary)
18986     return false;
18987
18988   assert(VT.getVectorNumElements() == OpMask.size() &&
18989          "Different mask size from vector size!");
18990
18991   SmallVector<int, 16> Mask;
18992   Mask.reserve(std::max(OpMask.size(), IncomingMask.size()));
18993
18994   // Merge this shuffle operation's mask into our accumulated mask. This is
18995   // a bit tricky as the shuffle may have a different size from the root.
18996   if (OpMask.size() == IncomingMask.size()) {
18997     for (int M : IncomingMask)
18998       Mask.push_back(OpMask[M]);
18999   } else if (OpMask.size() < IncomingMask.size()) {
19000     assert(IncomingMask.size() % OpMask.size() == 0 &&
19001            "The smaller number of elements must divide the larger.");
19002     int Ratio = IncomingMask.size() / OpMask.size();
19003     for (int M : IncomingMask)
19004       Mask.push_back(Ratio * OpMask[M / Ratio] + M % Ratio);
19005   } else {
19006     assert(OpMask.size() > IncomingMask.size() && "All other cases handled!");
19007     assert(OpMask.size() % IncomingMask.size() == 0 &&
19008            "The smaller number of elements must divide the larger.");
19009     int Ratio = OpMask.size() / IncomingMask.size();
19010     for (int i = 0, e = OpMask.size(); i < e; ++i)
19011       Mask.push_back(OpMask[Ratio * IncomingMask[i / Ratio] + i % Ratio]);
19012   }
19013
19014   // See if we can recurse into the operand to combine more things.
19015   switch (Op.getOpcode()) {
19016     case X86ISD::PSHUFB:
19017       HasPSHUFB = true;
19018     case X86ISD::PSHUFD:
19019     case X86ISD::PSHUFHW:
19020     case X86ISD::PSHUFLW:
19021       if (Op.getOperand(0).hasOneUse() &&
19022           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19023                                         HasPSHUFB, DAG, DCI, Subtarget))
19024         return true;
19025       break;
19026
19027     case X86ISD::UNPCKL:
19028     case X86ISD::UNPCKH:
19029       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19030       // We can't check for single use, we have to check that this shuffle is the only user.
19031       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19032           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19033                                         HasPSHUFB, DAG, DCI, Subtarget))
19034           return true;
19035       break;
19036   }
19037
19038   // Minor canonicalization of the accumulated shuffle mask to make it easier
19039   // to match below. All this does is detect masks with squential pairs of
19040   // elements, and shrink them to the half-width mask. It does this in a loop
19041   // so it will reduce the size of the mask to the minimal width mask which
19042   // performs an equivalent shuffle.
19043   while (Mask.size() > 1) {
19044     SmallVector<int, 16> NewMask;
19045     for (int i = 0, e = Mask.size()/2; i < e; ++i) {
19046       if (Mask[2*i] % 2 != 0 || Mask[2*i] != Mask[2*i + 1] + 1) {
19047         NewMask.clear();
19048         break;
19049       }
19050       NewMask.push_back(Mask[2*i] / 2);
19051     }
19052     if (NewMask.empty())
19053       break;
19054     Mask.swap(NewMask);
19055   }
19056
19057   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19058                                 Subtarget);
19059 }
19060
19061 /// \brief Get the PSHUF-style mask from PSHUF node.
19062 ///
19063 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19064 /// PSHUF-style masks that can be reused with such instructions.
19065 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19066   SmallVector<int, 4> Mask;
19067   bool IsUnary;
19068   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19069   (void)HaveMask;
19070   assert(HaveMask);
19071
19072   switch (N.getOpcode()) {
19073   case X86ISD::PSHUFD:
19074     return Mask;
19075   case X86ISD::PSHUFLW:
19076     Mask.resize(4);
19077     return Mask;
19078   case X86ISD::PSHUFHW:
19079     Mask.erase(Mask.begin(), Mask.begin() + 4);
19080     for (int &M : Mask)
19081       M -= 4;
19082     return Mask;
19083   default:
19084     llvm_unreachable("No valid shuffle instruction found!");
19085   }
19086 }
19087
19088 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19089 ///
19090 /// We walk up the chain and look for a combinable shuffle, skipping over
19091 /// shuffles that we could hoist this shuffle's transformation past without
19092 /// altering anything.
19093 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19094                                          SelectionDAG &DAG,
19095                                          TargetLowering::DAGCombinerInfo &DCI) {
19096   assert(N.getOpcode() == X86ISD::PSHUFD &&
19097          "Called with something other than an x86 128-bit half shuffle!");
19098   SDLoc DL(N);
19099
19100   // Walk up a single-use chain looking for a combinable shuffle.
19101   SDValue V = N.getOperand(0);
19102   for (; V.hasOneUse(); V = V.getOperand(0)) {
19103     switch (V.getOpcode()) {
19104     default:
19105       return false; // Nothing combined!
19106
19107     case ISD::BITCAST:
19108       // Skip bitcasts as we always know the type for the target specific
19109       // instructions.
19110       continue;
19111
19112     case X86ISD::PSHUFD:
19113       // Found another dword shuffle.
19114       break;
19115
19116     case X86ISD::PSHUFLW:
19117       // Check that the low words (being shuffled) are the identity in the
19118       // dword shuffle, and the high words are self-contained.
19119       if (Mask[0] != 0 || Mask[1] != 1 ||
19120           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19121         return false;
19122
19123       continue;
19124
19125     case X86ISD::PSHUFHW:
19126       // Check that the high words (being shuffled) are the identity in the
19127       // dword shuffle, and the low words are self-contained.
19128       if (Mask[2] != 2 || Mask[3] != 3 ||
19129           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19130         return false;
19131
19132       continue;
19133
19134     case X86ISD::UNPCKL:
19135     case X86ISD::UNPCKH:
19136       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19137       // shuffle into a preceding word shuffle.
19138       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19139         return false;
19140
19141       // Search for a half-shuffle which we can combine with.
19142       unsigned CombineOp =
19143           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19144       if (V.getOperand(0) != V.getOperand(1) ||
19145           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19146         return false;
19147       V = V.getOperand(0);
19148       do {
19149         switch (V.getOpcode()) {
19150         default:
19151           return false; // Nothing to combine.
19152
19153         case X86ISD::PSHUFLW:
19154         case X86ISD::PSHUFHW:
19155           if (V.getOpcode() == CombineOp)
19156             break;
19157
19158           // Fallthrough!
19159         case ISD::BITCAST:
19160           V = V.getOperand(0);
19161           continue;
19162         }
19163         break;
19164       } while (V.hasOneUse());
19165       break;
19166     }
19167     // Break out of the loop if we break out of the switch.
19168     break;
19169   }
19170
19171   if (!V.hasOneUse())
19172     // We fell out of the loop without finding a viable combining instruction.
19173     return false;
19174
19175   // Record the old value to use in RAUW-ing.
19176   SDValue Old = V;
19177
19178   // Merge this node's mask and our incoming mask.
19179   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19180   for (int &M : Mask)
19181     M = VMask[M];
19182   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19183                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19184
19185   // It is possible that one of the combinable shuffles was completely absorbed
19186   // by the other, just replace it and revisit all users in that case.
19187   if (Old.getNode() == V.getNode()) {
19188     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19189     return true;
19190   }
19191
19192   // Replace N with its operand as we're going to combine that shuffle away.
19193   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19194
19195   // Replace the combinable shuffle with the combined one, updating all users
19196   // so that we re-evaluate the chain here.
19197   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19198   return true;
19199 }
19200
19201 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19202 ///
19203 /// We walk up the chain, skipping shuffles of the other half and looking
19204 /// through shuffles which switch halves trying to find a shuffle of the same
19205 /// pair of dwords.
19206 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19207                                         SelectionDAG &DAG,
19208                                         TargetLowering::DAGCombinerInfo &DCI) {
19209   assert(
19210       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19211       "Called with something other than an x86 128-bit half shuffle!");
19212   SDLoc DL(N);
19213   unsigned CombineOpcode = N.getOpcode();
19214
19215   // Walk up a single-use chain looking for a combinable shuffle.
19216   SDValue V = N.getOperand(0);
19217   for (; V.hasOneUse(); V = V.getOperand(0)) {
19218     switch (V.getOpcode()) {
19219     default:
19220       return false; // Nothing combined!
19221
19222     case ISD::BITCAST:
19223       // Skip bitcasts as we always know the type for the target specific
19224       // instructions.
19225       continue;
19226
19227     case X86ISD::PSHUFLW:
19228     case X86ISD::PSHUFHW:
19229       if (V.getOpcode() == CombineOpcode)
19230         break;
19231
19232       // Other-half shuffles are no-ops.
19233       continue;
19234
19235     case X86ISD::PSHUFD: {
19236       // We can only handle pshufd if the half we are combining either stays in
19237       // its half, or switches to the other half. Bail if one of these isn't
19238       // true.
19239       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19240       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
19241       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
19242             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
19243         return false;
19244
19245       // Map the mask through the pshufd and keep walking up the chain.
19246       for (int i = 0; i < 4; ++i)
19247         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
19248
19249       // Switch halves if the pshufd does.
19250       CombineOpcode =
19251           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19252       continue;
19253     }
19254     }
19255     // Break out of the loop if we break out of the switch.
19256     break;
19257   }
19258
19259   if (!V.hasOneUse())
19260     // We fell out of the loop without finding a viable combining instruction.
19261     return false;
19262
19263   // Record the old value to use in RAUW-ing.
19264   SDValue Old = V;
19265
19266   // Merge this node's mask and our incoming mask (adjusted to account for all
19267   // the pshufd instructions encountered).
19268   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19269   for (int &M : Mask)
19270     M = VMask[M];
19271   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19272                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19273
19274   // Replace N with its operand as we're going to combine that shuffle away.
19275   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19276
19277   // Replace the combinable shuffle with the combined one, updating all users
19278   // so that we re-evaluate the chain here.
19279   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19280   return true;
19281 }
19282
19283 /// \brief Try to combine x86 target specific shuffles.
19284 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19285                                            TargetLowering::DAGCombinerInfo &DCI,
19286                                            const X86Subtarget *Subtarget) {
19287   SDLoc DL(N);
19288   MVT VT = N.getSimpleValueType();
19289   SmallVector<int, 4> Mask;
19290
19291   switch (N.getOpcode()) {
19292   case X86ISD::PSHUFD:
19293   case X86ISD::PSHUFLW:
19294   case X86ISD::PSHUFHW:
19295     Mask = getPSHUFShuffleMask(N);
19296     assert(Mask.size() == 4);
19297     break;
19298   default:
19299     return SDValue();
19300   }
19301
19302   // Nuke no-op shuffles that show up after combining.
19303   if (isNoopShuffleMask(Mask))
19304     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19305
19306   // Look for simplifications involving one or two shuffle instructions.
19307   SDValue V = N.getOperand(0);
19308   switch (N.getOpcode()) {
19309   default:
19310     break;
19311   case X86ISD::PSHUFLW:
19312   case X86ISD::PSHUFHW:
19313     assert(VT == MVT::v8i16);
19314     (void)VT;
19315
19316     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19317       return SDValue(); // We combined away this shuffle, so we're done.
19318
19319     // See if this reduces to a PSHUFD which is no more expensive and can
19320     // combine with more operations.
19321     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
19322         areAdjacentMasksSequential(Mask)) {
19323       int DMask[] = {-1, -1, -1, -1};
19324       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19325       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19326       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19327       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19328       DCI.AddToWorklist(V.getNode());
19329       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19330                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19331       DCI.AddToWorklist(V.getNode());
19332       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19333     }
19334
19335     // Look for shuffle patterns which can be implemented as a single unpack.
19336     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19337     // only works when we have a PSHUFD followed by two half-shuffles.
19338     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19339         (V.getOpcode() == X86ISD::PSHUFLW ||
19340          V.getOpcode() == X86ISD::PSHUFHW) &&
19341         V.getOpcode() != N.getOpcode() &&
19342         V.hasOneUse()) {
19343       SDValue D = V.getOperand(0);
19344       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19345         D = D.getOperand(0);
19346       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19347         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19348         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19349         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19350         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19351         int WordMask[8];
19352         for (int i = 0; i < 4; ++i) {
19353           WordMask[i + NOffset] = Mask[i] + NOffset;
19354           WordMask[i + VOffset] = VMask[i] + VOffset;
19355         }
19356         // Map the word mask through the DWord mask.
19357         int MappedMask[8];
19358         for (int i = 0; i < 8; ++i)
19359           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19360         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19361         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19362         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19363                        std::begin(UnpackLoMask)) ||
19364             std::equal(std::begin(MappedMask), std::end(MappedMask),
19365                        std::begin(UnpackHiMask))) {
19366           // We can replace all three shuffles with an unpack.
19367           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19368           DCI.AddToWorklist(V.getNode());
19369           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19370                                                 : X86ISD::UNPCKH,
19371                              DL, MVT::v8i16, V, V);
19372         }
19373       }
19374     }
19375
19376     break;
19377
19378   case X86ISD::PSHUFD:
19379     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19380       return SDValue(); // We combined away this shuffle.
19381
19382     break;
19383   }
19384
19385   return SDValue();
19386 }
19387
19388 /// PerformShuffleCombine - Performs several different shuffle combines.
19389 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19390                                      TargetLowering::DAGCombinerInfo &DCI,
19391                                      const X86Subtarget *Subtarget) {
19392   SDLoc dl(N);
19393   SDValue N0 = N->getOperand(0);
19394   SDValue N1 = N->getOperand(1);
19395   EVT VT = N->getValueType(0);
19396
19397   // Don't create instructions with illegal types after legalize types has run.
19398   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19399   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19400     return SDValue();
19401
19402   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19403   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19404       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19405     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19406
19407   // During Type Legalization, when promoting illegal vector types,
19408   // the backend might introduce new shuffle dag nodes and bitcasts.
19409   //
19410   // This code performs the following transformation:
19411   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19412   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19413   //
19414   // We do this only if both the bitcast and the BINOP dag nodes have
19415   // one use. Also, perform this transformation only if the new binary
19416   // operation is legal. This is to avoid introducing dag nodes that
19417   // potentially need to be further expanded (or custom lowered) into a
19418   // less optimal sequence of dag nodes.
19419   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19420       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19421       N0.getOpcode() == ISD::BITCAST) {
19422     SDValue BC0 = N0.getOperand(0);
19423     EVT SVT = BC0.getValueType();
19424     unsigned Opcode = BC0.getOpcode();
19425     unsigned NumElts = VT.getVectorNumElements();
19426     
19427     if (BC0.hasOneUse() && SVT.isVector() &&
19428         SVT.getVectorNumElements() * 2 == NumElts &&
19429         TLI.isOperationLegal(Opcode, VT)) {
19430       bool CanFold = false;
19431       switch (Opcode) {
19432       default : break;
19433       case ISD::ADD :
19434       case ISD::FADD :
19435       case ISD::SUB :
19436       case ISD::FSUB :
19437       case ISD::MUL :
19438       case ISD::FMUL :
19439         CanFold = true;
19440       }
19441
19442       unsigned SVTNumElts = SVT.getVectorNumElements();
19443       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19444       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19445         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19446       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19447         CanFold = SVOp->getMaskElt(i) < 0;
19448
19449       if (CanFold) {
19450         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19451         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19452         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19453         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19454       }
19455     }
19456   }
19457
19458   // Only handle 128 wide vector from here on.
19459   if (!VT.is128BitVector())
19460     return SDValue();
19461
19462   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19463   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19464   // consecutive, non-overlapping, and in the right order.
19465   SmallVector<SDValue, 16> Elts;
19466   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19467     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19468
19469   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19470   if (LD.getNode())
19471     return LD;
19472
19473   if (isTargetShuffle(N->getOpcode())) {
19474     SDValue Shuffle =
19475         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19476     if (Shuffle.getNode())
19477       return Shuffle;
19478
19479     // Try recursively combining arbitrary sequences of x86 shuffle
19480     // instructions into higher-order shuffles. We do this after combining
19481     // specific PSHUF instruction sequences into their minimal form so that we
19482     // can evaluate how many specialized shuffle instructions are involved in
19483     // a particular chain.
19484     SmallVector<int, 1> NonceMask; // Just a placeholder.
19485     NonceMask.push_back(0);
19486     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19487                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19488                                       DCI, Subtarget))
19489       return SDValue(); // This routine will use CombineTo to replace N.
19490   }
19491
19492   return SDValue();
19493 }
19494
19495 /// PerformTruncateCombine - Converts truncate operation to
19496 /// a sequence of vector shuffle operations.
19497 /// It is possible when we truncate 256-bit vector to 128-bit vector
19498 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19499                                       TargetLowering::DAGCombinerInfo &DCI,
19500                                       const X86Subtarget *Subtarget)  {
19501   return SDValue();
19502 }
19503
19504 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19505 /// specific shuffle of a load can be folded into a single element load.
19506 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19507 /// shuffles have been customed lowered so we need to handle those here.
19508 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19509                                          TargetLowering::DAGCombinerInfo &DCI) {
19510   if (DCI.isBeforeLegalizeOps())
19511     return SDValue();
19512
19513   SDValue InVec = N->getOperand(0);
19514   SDValue EltNo = N->getOperand(1);
19515
19516   if (!isa<ConstantSDNode>(EltNo))
19517     return SDValue();
19518
19519   EVT VT = InVec.getValueType();
19520
19521   bool HasShuffleIntoBitcast = false;
19522   if (InVec.getOpcode() == ISD::BITCAST) {
19523     // Don't duplicate a load with other uses.
19524     if (!InVec.hasOneUse())
19525       return SDValue();
19526     EVT BCVT = InVec.getOperand(0).getValueType();
19527     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19528       return SDValue();
19529     InVec = InVec.getOperand(0);
19530     HasShuffleIntoBitcast = true;
19531   }
19532
19533   if (!isTargetShuffle(InVec.getOpcode()))
19534     return SDValue();
19535
19536   // Don't duplicate a load with other uses.
19537   if (!InVec.hasOneUse())
19538     return SDValue();
19539
19540   SmallVector<int, 16> ShuffleMask;
19541   bool UnaryShuffle;
19542   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19543                             UnaryShuffle))
19544     return SDValue();
19545
19546   // Select the input vector, guarding against out of range extract vector.
19547   unsigned NumElems = VT.getVectorNumElements();
19548   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19549   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19550   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19551                                          : InVec.getOperand(1);
19552
19553   // If inputs to shuffle are the same for both ops, then allow 2 uses
19554   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19555
19556   if (LdNode.getOpcode() == ISD::BITCAST) {
19557     // Don't duplicate a load with other uses.
19558     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19559       return SDValue();
19560
19561     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19562     LdNode = LdNode.getOperand(0);
19563   }
19564
19565   if (!ISD::isNormalLoad(LdNode.getNode()))
19566     return SDValue();
19567
19568   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19569
19570   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19571     return SDValue();
19572
19573   if (HasShuffleIntoBitcast) {
19574     // If there's a bitcast before the shuffle, check if the load type and
19575     // alignment is valid.
19576     unsigned Align = LN0->getAlignment();
19577     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19578     unsigned NewAlign = TLI.getDataLayout()->
19579       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19580
19581     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19582       return SDValue();
19583   }
19584
19585   // All checks match so transform back to vector_shuffle so that DAG combiner
19586   // can finish the job
19587   SDLoc dl(N);
19588
19589   // Create shuffle node taking into account the case that its a unary shuffle
19590   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19591   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19592                                  InVec.getOperand(0), Shuffle,
19593                                  &ShuffleMask[0]);
19594   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19595   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19596                      EltNo);
19597 }
19598
19599 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19600 /// generation and convert it from being a bunch of shuffles and extracts
19601 /// to a simple store and scalar loads to extract the elements.
19602 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19603                                          TargetLowering::DAGCombinerInfo &DCI) {
19604   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19605   if (NewOp.getNode())
19606     return NewOp;
19607
19608   SDValue InputVector = N->getOperand(0);
19609
19610   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19611   // from mmx to v2i32 has a single usage.
19612   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19613       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19614       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19615     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19616                        N->getValueType(0),
19617                        InputVector.getNode()->getOperand(0));
19618
19619   // Only operate on vectors of 4 elements, where the alternative shuffling
19620   // gets to be more expensive.
19621   if (InputVector.getValueType() != MVT::v4i32)
19622     return SDValue();
19623
19624   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19625   // single use which is a sign-extend or zero-extend, and all elements are
19626   // used.
19627   SmallVector<SDNode *, 4> Uses;
19628   unsigned ExtractedElements = 0;
19629   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19630        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19631     if (UI.getUse().getResNo() != InputVector.getResNo())
19632       return SDValue();
19633
19634     SDNode *Extract = *UI;
19635     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19636       return SDValue();
19637
19638     if (Extract->getValueType(0) != MVT::i32)
19639       return SDValue();
19640     if (!Extract->hasOneUse())
19641       return SDValue();
19642     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19643         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19644       return SDValue();
19645     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19646       return SDValue();
19647
19648     // Record which element was extracted.
19649     ExtractedElements |=
19650       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19651
19652     Uses.push_back(Extract);
19653   }
19654
19655   // If not all the elements were used, this may not be worthwhile.
19656   if (ExtractedElements != 15)
19657     return SDValue();
19658
19659   // Ok, we've now decided to do the transformation.
19660   SDLoc dl(InputVector);
19661
19662   // Store the value to a temporary stack slot.
19663   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19664   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19665                             MachinePointerInfo(), false, false, 0);
19666
19667   // Replace each use (extract) with a load of the appropriate element.
19668   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19669        UE = Uses.end(); UI != UE; ++UI) {
19670     SDNode *Extract = *UI;
19671
19672     // cOMpute the element's address.
19673     SDValue Idx = Extract->getOperand(1);
19674     unsigned EltSize =
19675         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19676     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19677     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19678     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19679
19680     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19681                                      StackPtr, OffsetVal);
19682
19683     // Load the scalar.
19684     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19685                                      ScalarAddr, MachinePointerInfo(),
19686                                      false, false, false, 0);
19687
19688     // Replace the exact with the load.
19689     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19690   }
19691
19692   // The replacement was made in place; don't return anything.
19693   return SDValue();
19694 }
19695
19696 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19697 static std::pair<unsigned, bool>
19698 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19699                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19700   if (!VT.isVector())
19701     return std::make_pair(0, false);
19702
19703   bool NeedSplit = false;
19704   switch (VT.getSimpleVT().SimpleTy) {
19705   default: return std::make_pair(0, false);
19706   case MVT::v32i8:
19707   case MVT::v16i16:
19708   case MVT::v8i32:
19709     if (!Subtarget->hasAVX2())
19710       NeedSplit = true;
19711     if (!Subtarget->hasAVX())
19712       return std::make_pair(0, false);
19713     break;
19714   case MVT::v16i8:
19715   case MVT::v8i16:
19716   case MVT::v4i32:
19717     if (!Subtarget->hasSSE2())
19718       return std::make_pair(0, false);
19719   }
19720
19721   // SSE2 has only a small subset of the operations.
19722   bool hasUnsigned = Subtarget->hasSSE41() ||
19723                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19724   bool hasSigned = Subtarget->hasSSE41() ||
19725                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19726
19727   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19728
19729   unsigned Opc = 0;
19730   // Check for x CC y ? x : y.
19731   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19732       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19733     switch (CC) {
19734     default: break;
19735     case ISD::SETULT:
19736     case ISD::SETULE:
19737       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19738     case ISD::SETUGT:
19739     case ISD::SETUGE:
19740       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19741     case ISD::SETLT:
19742     case ISD::SETLE:
19743       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19744     case ISD::SETGT:
19745     case ISD::SETGE:
19746       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19747     }
19748   // Check for x CC y ? y : x -- a min/max with reversed arms.
19749   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19750              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19751     switch (CC) {
19752     default: break;
19753     case ISD::SETULT:
19754     case ISD::SETULE:
19755       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19756     case ISD::SETUGT:
19757     case ISD::SETUGE:
19758       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19759     case ISD::SETLT:
19760     case ISD::SETLE:
19761       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19762     case ISD::SETGT:
19763     case ISD::SETGE:
19764       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19765     }
19766   }
19767
19768   return std::make_pair(Opc, NeedSplit);
19769 }
19770
19771 static SDValue
19772 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19773                                       const X86Subtarget *Subtarget) {
19774   SDLoc dl(N);
19775   SDValue Cond = N->getOperand(0);
19776   SDValue LHS = N->getOperand(1);
19777   SDValue RHS = N->getOperand(2);
19778
19779   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19780     SDValue CondSrc = Cond->getOperand(0);
19781     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19782       Cond = CondSrc->getOperand(0);
19783   }
19784
19785   MVT VT = N->getSimpleValueType(0);
19786   MVT EltVT = VT.getVectorElementType();
19787   unsigned NumElems = VT.getVectorNumElements();
19788   // There is no blend with immediate in AVX-512.
19789   if (VT.is512BitVector())
19790     return SDValue();
19791
19792   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19793     return SDValue();
19794   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19795     return SDValue();
19796
19797   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19798     return SDValue();
19799
19800   unsigned MaskValue = 0;
19801   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19802     return SDValue();
19803
19804   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19805   for (unsigned i = 0; i < NumElems; ++i) {
19806     // Be sure we emit undef where we can.
19807     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19808       ShuffleMask[i] = -1;
19809     else
19810       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19811   }
19812
19813   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19814 }
19815
19816 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19817 /// nodes.
19818 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19819                                     TargetLowering::DAGCombinerInfo &DCI,
19820                                     const X86Subtarget *Subtarget) {
19821   SDLoc DL(N);
19822   SDValue Cond = N->getOperand(0);
19823   // Get the LHS/RHS of the select.
19824   SDValue LHS = N->getOperand(1);
19825   SDValue RHS = N->getOperand(2);
19826   EVT VT = LHS.getValueType();
19827   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19828
19829   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19830   // instructions match the semantics of the common C idiom x<y?x:y but not
19831   // x<=y?x:y, because of how they handle negative zero (which can be
19832   // ignored in unsafe-math mode).
19833   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19834       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19835       (Subtarget->hasSSE2() ||
19836        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19837     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19838
19839     unsigned Opcode = 0;
19840     // Check for x CC y ? x : y.
19841     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19842         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19843       switch (CC) {
19844       default: break;
19845       case ISD::SETULT:
19846         // Converting this to a min would handle NaNs incorrectly, and swapping
19847         // the operands would cause it to handle comparisons between positive
19848         // and negative zero incorrectly.
19849         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19850           if (!DAG.getTarget().Options.UnsafeFPMath &&
19851               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19852             break;
19853           std::swap(LHS, RHS);
19854         }
19855         Opcode = X86ISD::FMIN;
19856         break;
19857       case ISD::SETOLE:
19858         // Converting this to a min would handle comparisons between positive
19859         // and negative zero incorrectly.
19860         if (!DAG.getTarget().Options.UnsafeFPMath &&
19861             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19862           break;
19863         Opcode = X86ISD::FMIN;
19864         break;
19865       case ISD::SETULE:
19866         // Converting this to a min would handle both negative zeros and NaNs
19867         // incorrectly, but we can swap the operands to fix both.
19868         std::swap(LHS, RHS);
19869       case ISD::SETOLT:
19870       case ISD::SETLT:
19871       case ISD::SETLE:
19872         Opcode = X86ISD::FMIN;
19873         break;
19874
19875       case ISD::SETOGE:
19876         // Converting this to a max would handle comparisons between positive
19877         // and negative zero incorrectly.
19878         if (!DAG.getTarget().Options.UnsafeFPMath &&
19879             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19880           break;
19881         Opcode = X86ISD::FMAX;
19882         break;
19883       case ISD::SETUGT:
19884         // Converting this to a max would handle NaNs incorrectly, and swapping
19885         // the operands would cause it to handle comparisons between positive
19886         // and negative zero incorrectly.
19887         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19888           if (!DAG.getTarget().Options.UnsafeFPMath &&
19889               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19890             break;
19891           std::swap(LHS, RHS);
19892         }
19893         Opcode = X86ISD::FMAX;
19894         break;
19895       case ISD::SETUGE:
19896         // Converting this to a max would handle both negative zeros and NaNs
19897         // incorrectly, but we can swap the operands to fix both.
19898         std::swap(LHS, RHS);
19899       case ISD::SETOGT:
19900       case ISD::SETGT:
19901       case ISD::SETGE:
19902         Opcode = X86ISD::FMAX;
19903         break;
19904       }
19905     // Check for x CC y ? y : x -- a min/max with reversed arms.
19906     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19907                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19908       switch (CC) {
19909       default: break;
19910       case ISD::SETOGE:
19911         // Converting this to a min would handle comparisons between positive
19912         // and negative zero incorrectly, and swapping the operands would
19913         // cause it to handle NaNs incorrectly.
19914         if (!DAG.getTarget().Options.UnsafeFPMath &&
19915             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19916           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19917             break;
19918           std::swap(LHS, RHS);
19919         }
19920         Opcode = X86ISD::FMIN;
19921         break;
19922       case ISD::SETUGT:
19923         // Converting this to a min would handle NaNs incorrectly.
19924         if (!DAG.getTarget().Options.UnsafeFPMath &&
19925             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19926           break;
19927         Opcode = X86ISD::FMIN;
19928         break;
19929       case ISD::SETUGE:
19930         // Converting this to a min would handle both negative zeros and NaNs
19931         // incorrectly, but we can swap the operands to fix both.
19932         std::swap(LHS, RHS);
19933       case ISD::SETOGT:
19934       case ISD::SETGT:
19935       case ISD::SETGE:
19936         Opcode = X86ISD::FMIN;
19937         break;
19938
19939       case ISD::SETULT:
19940         // Converting this to a max would handle NaNs incorrectly.
19941         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19942           break;
19943         Opcode = X86ISD::FMAX;
19944         break;
19945       case ISD::SETOLE:
19946         // Converting this to a max would handle comparisons between positive
19947         // and negative zero incorrectly, and swapping the operands would
19948         // cause it to handle NaNs incorrectly.
19949         if (!DAG.getTarget().Options.UnsafeFPMath &&
19950             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19951           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19952             break;
19953           std::swap(LHS, RHS);
19954         }
19955         Opcode = X86ISD::FMAX;
19956         break;
19957       case ISD::SETULE:
19958         // Converting this to a max would handle both negative zeros and NaNs
19959         // incorrectly, but we can swap the operands to fix both.
19960         std::swap(LHS, RHS);
19961       case ISD::SETOLT:
19962       case ISD::SETLT:
19963       case ISD::SETLE:
19964         Opcode = X86ISD::FMAX;
19965         break;
19966       }
19967     }
19968
19969     if (Opcode)
19970       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19971   }
19972
19973   EVT CondVT = Cond.getValueType();
19974   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19975       CondVT.getVectorElementType() == MVT::i1) {
19976     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19977     // lowering on AVX-512. In this case we convert it to
19978     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19979     // The same situation for all 128 and 256-bit vectors of i8 and i16
19980     EVT OpVT = LHS.getValueType();
19981     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19982         (OpVT.getVectorElementType() == MVT::i8 ||
19983          OpVT.getVectorElementType() == MVT::i16)) {
19984       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19985       DCI.AddToWorklist(Cond.getNode());
19986       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19987     }
19988   }
19989   // If this is a select between two integer constants, try to do some
19990   // optimizations.
19991   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19992     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19993       // Don't do this for crazy integer types.
19994       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19995         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19996         // so that TrueC (the true value) is larger than FalseC.
19997         bool NeedsCondInvert = false;
19998
19999         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20000             // Efficiently invertible.
20001             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20002              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20003               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20004           NeedsCondInvert = true;
20005           std::swap(TrueC, FalseC);
20006         }
20007
20008         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20009         if (FalseC->getAPIntValue() == 0 &&
20010             TrueC->getAPIntValue().isPowerOf2()) {
20011           if (NeedsCondInvert) // Invert the condition if needed.
20012             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20013                                DAG.getConstant(1, Cond.getValueType()));
20014
20015           // Zero extend the condition if needed.
20016           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20017
20018           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20019           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20020                              DAG.getConstant(ShAmt, MVT::i8));
20021         }
20022
20023         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20024         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20025           if (NeedsCondInvert) // Invert the condition if needed.
20026             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20027                                DAG.getConstant(1, Cond.getValueType()));
20028
20029           // Zero extend the condition if needed.
20030           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20031                              FalseC->getValueType(0), Cond);
20032           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20033                              SDValue(FalseC, 0));
20034         }
20035
20036         // Optimize cases that will turn into an LEA instruction.  This requires
20037         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20038         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20039           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20040           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20041
20042           bool isFastMultiplier = false;
20043           if (Diff < 10) {
20044             switch ((unsigned char)Diff) {
20045               default: break;
20046               case 1:  // result = add base, cond
20047               case 2:  // result = lea base(    , cond*2)
20048               case 3:  // result = lea base(cond, cond*2)
20049               case 4:  // result = lea base(    , cond*4)
20050               case 5:  // result = lea base(cond, cond*4)
20051               case 8:  // result = lea base(    , cond*8)
20052               case 9:  // result = lea base(cond, cond*8)
20053                 isFastMultiplier = true;
20054                 break;
20055             }
20056           }
20057
20058           if (isFastMultiplier) {
20059             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20060             if (NeedsCondInvert) // Invert the condition if needed.
20061               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20062                                  DAG.getConstant(1, Cond.getValueType()));
20063
20064             // Zero extend the condition if needed.
20065             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20066                                Cond);
20067             // Scale the condition by the difference.
20068             if (Diff != 1)
20069               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20070                                  DAG.getConstant(Diff, Cond.getValueType()));
20071
20072             // Add the base if non-zero.
20073             if (FalseC->getAPIntValue() != 0)
20074               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20075                                  SDValue(FalseC, 0));
20076             return Cond;
20077           }
20078         }
20079       }
20080   }
20081
20082   // Canonicalize max and min:
20083   // (x > y) ? x : y -> (x >= y) ? x : y
20084   // (x < y) ? x : y -> (x <= y) ? x : y
20085   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20086   // the need for an extra compare
20087   // against zero. e.g.
20088   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20089   // subl   %esi, %edi
20090   // testl  %edi, %edi
20091   // movl   $0, %eax
20092   // cmovgl %edi, %eax
20093   // =>
20094   // xorl   %eax, %eax
20095   // subl   %esi, $edi
20096   // cmovsl %eax, %edi
20097   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20098       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20099       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20100     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20101     switch (CC) {
20102     default: break;
20103     case ISD::SETLT:
20104     case ISD::SETGT: {
20105       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20106       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20107                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20108       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20109     }
20110     }
20111   }
20112
20113   // Early exit check
20114   if (!TLI.isTypeLegal(VT))
20115     return SDValue();
20116
20117   // Match VSELECTs into subs with unsigned saturation.
20118   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20119       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20120       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20121        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20122     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20123
20124     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20125     // left side invert the predicate to simplify logic below.
20126     SDValue Other;
20127     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20128       Other = RHS;
20129       CC = ISD::getSetCCInverse(CC, true);
20130     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20131       Other = LHS;
20132     }
20133
20134     if (Other.getNode() && Other->getNumOperands() == 2 &&
20135         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20136       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20137       SDValue CondRHS = Cond->getOperand(1);
20138
20139       // Look for a general sub with unsigned saturation first.
20140       // x >= y ? x-y : 0 --> subus x, y
20141       // x >  y ? x-y : 0 --> subus x, y
20142       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20143           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20144         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20145
20146       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20147         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20148           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20149             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20150               // If the RHS is a constant we have to reverse the const
20151               // canonicalization.
20152               // x > C-1 ? x+-C : 0 --> subus x, C
20153               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20154                   CondRHSConst->getAPIntValue() ==
20155                       (-OpRHSConst->getAPIntValue() - 1))
20156                 return DAG.getNode(
20157                     X86ISD::SUBUS, DL, VT, OpLHS,
20158                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20159
20160           // Another special case: If C was a sign bit, the sub has been
20161           // canonicalized into a xor.
20162           // FIXME: Would it be better to use computeKnownBits to determine
20163           //        whether it's safe to decanonicalize the xor?
20164           // x s< 0 ? x^C : 0 --> subus x, C
20165           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20166               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20167               OpRHSConst->getAPIntValue().isSignBit())
20168             // Note that we have to rebuild the RHS constant here to ensure we
20169             // don't rely on particular values of undef lanes.
20170             return DAG.getNode(
20171                 X86ISD::SUBUS, DL, VT, OpLHS,
20172                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20173         }
20174     }
20175   }
20176
20177   // Try to match a min/max vector operation.
20178   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20179     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20180     unsigned Opc = ret.first;
20181     bool NeedSplit = ret.second;
20182
20183     if (Opc && NeedSplit) {
20184       unsigned NumElems = VT.getVectorNumElements();
20185       // Extract the LHS vectors
20186       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20187       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20188
20189       // Extract the RHS vectors
20190       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20191       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20192
20193       // Create min/max for each subvector
20194       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20195       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20196
20197       // Merge the result
20198       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20199     } else if (Opc)
20200       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20201   }
20202
20203   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20204   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20205       // Check if SETCC has already been promoted
20206       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20207       // Check that condition value type matches vselect operand type
20208       CondVT == VT) { 
20209
20210     assert(Cond.getValueType().isVector() &&
20211            "vector select expects a vector selector!");
20212
20213     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20214     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20215
20216     if (!TValIsAllOnes && !FValIsAllZeros) {
20217       // Try invert the condition if true value is not all 1s and false value
20218       // is not all 0s.
20219       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20220       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20221
20222       if (TValIsAllZeros || FValIsAllOnes) {
20223         SDValue CC = Cond.getOperand(2);
20224         ISD::CondCode NewCC =
20225           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20226                                Cond.getOperand(0).getValueType().isInteger());
20227         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20228         std::swap(LHS, RHS);
20229         TValIsAllOnes = FValIsAllOnes;
20230         FValIsAllZeros = TValIsAllZeros;
20231       }
20232     }
20233
20234     if (TValIsAllOnes || FValIsAllZeros) {
20235       SDValue Ret;
20236
20237       if (TValIsAllOnes && FValIsAllZeros)
20238         Ret = Cond;
20239       else if (TValIsAllOnes)
20240         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20241                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20242       else if (FValIsAllZeros)
20243         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20244                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20245
20246       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20247     }
20248   }
20249
20250   // Try to fold this VSELECT into a MOVSS/MOVSD
20251   if (N->getOpcode() == ISD::VSELECT &&
20252       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20253     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20254         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20255       bool CanFold = false;
20256       unsigned NumElems = Cond.getNumOperands();
20257       SDValue A = LHS;
20258       SDValue B = RHS;
20259       
20260       if (isZero(Cond.getOperand(0))) {
20261         CanFold = true;
20262
20263         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20264         // fold (vselect <0,-1> -> (movsd A, B)
20265         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20266           CanFold = isAllOnes(Cond.getOperand(i));
20267       } else if (isAllOnes(Cond.getOperand(0))) {
20268         CanFold = true;
20269         std::swap(A, B);
20270
20271         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20272         // fold (vselect <-1,0> -> (movsd B, A)
20273         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20274           CanFold = isZero(Cond.getOperand(i));
20275       }
20276
20277       if (CanFold) {
20278         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20279           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20280         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20281       }
20282
20283       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20284         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20285         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20286         //                             (v2i64 (bitcast B)))))
20287         //
20288         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20289         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20290         //                             (v2f64 (bitcast B)))))
20291         //
20292         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20293         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20294         //                             (v2i64 (bitcast A)))))
20295         //
20296         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20297         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20298         //                             (v2f64 (bitcast A)))))
20299
20300         CanFold = (isZero(Cond.getOperand(0)) &&
20301                    isZero(Cond.getOperand(1)) &&
20302                    isAllOnes(Cond.getOperand(2)) &&
20303                    isAllOnes(Cond.getOperand(3)));
20304
20305         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20306             isAllOnes(Cond.getOperand(1)) &&
20307             isZero(Cond.getOperand(2)) &&
20308             isZero(Cond.getOperand(3))) {
20309           CanFold = true;
20310           std::swap(LHS, RHS);
20311         }
20312
20313         if (CanFold) {
20314           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20315           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20316           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20317           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20318                                                 NewB, DAG);
20319           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20320         }
20321       }
20322     }
20323   }
20324
20325   // If we know that this node is legal then we know that it is going to be
20326   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20327   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20328   // to simplify previous instructions.
20329   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20330       !DCI.isBeforeLegalize() &&
20331       // We explicitly check against v8i16 and v16i16 because, although
20332       // they're marked as Custom, they might only be legal when Cond is a
20333       // build_vector of constants. This will be taken care in a later
20334       // condition.
20335       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20336        VT != MVT::v8i16)) {
20337     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20338
20339     // Don't optimize vector selects that map to mask-registers.
20340     if (BitWidth == 1)
20341       return SDValue();
20342
20343     // Check all uses of that condition operand to check whether it will be
20344     // consumed by non-BLEND instructions, which may depend on all bits are set
20345     // properly.
20346     for (SDNode::use_iterator I = Cond->use_begin(),
20347                               E = Cond->use_end(); I != E; ++I)
20348       if (I->getOpcode() != ISD::VSELECT)
20349         // TODO: Add other opcodes eventually lowered into BLEND.
20350         return SDValue();
20351
20352     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20353     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20354
20355     APInt KnownZero, KnownOne;
20356     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20357                                           DCI.isBeforeLegalizeOps());
20358     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20359         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20360       DCI.CommitTargetLoweringOpt(TLO);
20361   }
20362
20363   // We should generate an X86ISD::BLENDI from a vselect if its argument
20364   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20365   // constants. This specific pattern gets generated when we split a
20366   // selector for a 512 bit vector in a machine without AVX512 (but with
20367   // 256-bit vectors), during legalization:
20368   //
20369   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20370   //
20371   // Iff we find this pattern and the build_vectors are built from
20372   // constants, we translate the vselect into a shuffle_vector that we
20373   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20374   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20375     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20376     if (Shuffle.getNode())
20377       return Shuffle;
20378   }
20379
20380   return SDValue();
20381 }
20382
20383 // Check whether a boolean test is testing a boolean value generated by
20384 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20385 // code.
20386 //
20387 // Simplify the following patterns:
20388 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20389 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20390 // to (Op EFLAGS Cond)
20391 //
20392 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20393 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20394 // to (Op EFLAGS !Cond)
20395 //
20396 // where Op could be BRCOND or CMOV.
20397 //
20398 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20399   // Quit if not CMP and SUB with its value result used.
20400   if (Cmp.getOpcode() != X86ISD::CMP &&
20401       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20402       return SDValue();
20403
20404   // Quit if not used as a boolean value.
20405   if (CC != X86::COND_E && CC != X86::COND_NE)
20406     return SDValue();
20407
20408   // Check CMP operands. One of them should be 0 or 1 and the other should be
20409   // an SetCC or extended from it.
20410   SDValue Op1 = Cmp.getOperand(0);
20411   SDValue Op2 = Cmp.getOperand(1);
20412
20413   SDValue SetCC;
20414   const ConstantSDNode* C = nullptr;
20415   bool needOppositeCond = (CC == X86::COND_E);
20416   bool checkAgainstTrue = false; // Is it a comparison against 1?
20417
20418   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20419     SetCC = Op2;
20420   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20421     SetCC = Op1;
20422   else // Quit if all operands are not constants.
20423     return SDValue();
20424
20425   if (C->getZExtValue() == 1) {
20426     needOppositeCond = !needOppositeCond;
20427     checkAgainstTrue = true;
20428   } else if (C->getZExtValue() != 0)
20429     // Quit if the constant is neither 0 or 1.
20430     return SDValue();
20431
20432   bool truncatedToBoolWithAnd = false;
20433   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20434   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20435          SetCC.getOpcode() == ISD::TRUNCATE ||
20436          SetCC.getOpcode() == ISD::AND) {
20437     if (SetCC.getOpcode() == ISD::AND) {
20438       int OpIdx = -1;
20439       ConstantSDNode *CS;
20440       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20441           CS->getZExtValue() == 1)
20442         OpIdx = 1;
20443       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20444           CS->getZExtValue() == 1)
20445         OpIdx = 0;
20446       if (OpIdx == -1)
20447         break;
20448       SetCC = SetCC.getOperand(OpIdx);
20449       truncatedToBoolWithAnd = true;
20450     } else
20451       SetCC = SetCC.getOperand(0);
20452   }
20453
20454   switch (SetCC.getOpcode()) {
20455   case X86ISD::SETCC_CARRY:
20456     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20457     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20458     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20459     // truncated to i1 using 'and'.
20460     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20461       break;
20462     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20463            "Invalid use of SETCC_CARRY!");
20464     // FALL THROUGH
20465   case X86ISD::SETCC:
20466     // Set the condition code or opposite one if necessary.
20467     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20468     if (needOppositeCond)
20469       CC = X86::GetOppositeBranchCondition(CC);
20470     return SetCC.getOperand(1);
20471   case X86ISD::CMOV: {
20472     // Check whether false/true value has canonical one, i.e. 0 or 1.
20473     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20474     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20475     // Quit if true value is not a constant.
20476     if (!TVal)
20477       return SDValue();
20478     // Quit if false value is not a constant.
20479     if (!FVal) {
20480       SDValue Op = SetCC.getOperand(0);
20481       // Skip 'zext' or 'trunc' node.
20482       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20483           Op.getOpcode() == ISD::TRUNCATE)
20484         Op = Op.getOperand(0);
20485       // A special case for rdrand/rdseed, where 0 is set if false cond is
20486       // found.
20487       if ((Op.getOpcode() != X86ISD::RDRAND &&
20488            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20489         return SDValue();
20490     }
20491     // Quit if false value is not the constant 0 or 1.
20492     bool FValIsFalse = true;
20493     if (FVal && FVal->getZExtValue() != 0) {
20494       if (FVal->getZExtValue() != 1)
20495         return SDValue();
20496       // If FVal is 1, opposite cond is needed.
20497       needOppositeCond = !needOppositeCond;
20498       FValIsFalse = false;
20499     }
20500     // Quit if TVal is not the constant opposite of FVal.
20501     if (FValIsFalse && TVal->getZExtValue() != 1)
20502       return SDValue();
20503     if (!FValIsFalse && TVal->getZExtValue() != 0)
20504       return SDValue();
20505     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20506     if (needOppositeCond)
20507       CC = X86::GetOppositeBranchCondition(CC);
20508     return SetCC.getOperand(3);
20509   }
20510   }
20511
20512   return SDValue();
20513 }
20514
20515 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20516 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20517                                   TargetLowering::DAGCombinerInfo &DCI,
20518                                   const X86Subtarget *Subtarget) {
20519   SDLoc DL(N);
20520
20521   // If the flag operand isn't dead, don't touch this CMOV.
20522   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20523     return SDValue();
20524
20525   SDValue FalseOp = N->getOperand(0);
20526   SDValue TrueOp = N->getOperand(1);
20527   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20528   SDValue Cond = N->getOperand(3);
20529
20530   if (CC == X86::COND_E || CC == X86::COND_NE) {
20531     switch (Cond.getOpcode()) {
20532     default: break;
20533     case X86ISD::BSR:
20534     case X86ISD::BSF:
20535       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20536       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20537         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20538     }
20539   }
20540
20541   SDValue Flags;
20542
20543   Flags = checkBoolTestSetCCCombine(Cond, CC);
20544   if (Flags.getNode() &&
20545       // Extra check as FCMOV only supports a subset of X86 cond.
20546       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20547     SDValue Ops[] = { FalseOp, TrueOp,
20548                       DAG.getConstant(CC, MVT::i8), Flags };
20549     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20550   }
20551
20552   // If this is a select between two integer constants, try to do some
20553   // optimizations.  Note that the operands are ordered the opposite of SELECT
20554   // operands.
20555   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20556     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20557       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20558       // larger than FalseC (the false value).
20559       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20560         CC = X86::GetOppositeBranchCondition(CC);
20561         std::swap(TrueC, FalseC);
20562         std::swap(TrueOp, FalseOp);
20563       }
20564
20565       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20566       // This is efficient for any integer data type (including i8/i16) and
20567       // shift amount.
20568       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20569         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20570                            DAG.getConstant(CC, MVT::i8), Cond);
20571
20572         // Zero extend the condition if needed.
20573         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20574
20575         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20576         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20577                            DAG.getConstant(ShAmt, MVT::i8));
20578         if (N->getNumValues() == 2)  // Dead flag value?
20579           return DCI.CombineTo(N, Cond, SDValue());
20580         return Cond;
20581       }
20582
20583       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20584       // for any integer data type, including i8/i16.
20585       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20586         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20587                            DAG.getConstant(CC, MVT::i8), Cond);
20588
20589         // Zero extend the condition if needed.
20590         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20591                            FalseC->getValueType(0), Cond);
20592         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20593                            SDValue(FalseC, 0));
20594
20595         if (N->getNumValues() == 2)  // Dead flag value?
20596           return DCI.CombineTo(N, Cond, SDValue());
20597         return Cond;
20598       }
20599
20600       // Optimize cases that will turn into an LEA instruction.  This requires
20601       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20602       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20603         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20604         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20605
20606         bool isFastMultiplier = false;
20607         if (Diff < 10) {
20608           switch ((unsigned char)Diff) {
20609           default: break;
20610           case 1:  // result = add base, cond
20611           case 2:  // result = lea base(    , cond*2)
20612           case 3:  // result = lea base(cond, cond*2)
20613           case 4:  // result = lea base(    , cond*4)
20614           case 5:  // result = lea base(cond, cond*4)
20615           case 8:  // result = lea base(    , cond*8)
20616           case 9:  // result = lea base(cond, cond*8)
20617             isFastMultiplier = true;
20618             break;
20619           }
20620         }
20621
20622         if (isFastMultiplier) {
20623           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20624           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20625                              DAG.getConstant(CC, MVT::i8), Cond);
20626           // Zero extend the condition if needed.
20627           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20628                              Cond);
20629           // Scale the condition by the difference.
20630           if (Diff != 1)
20631             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20632                                DAG.getConstant(Diff, Cond.getValueType()));
20633
20634           // Add the base if non-zero.
20635           if (FalseC->getAPIntValue() != 0)
20636             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20637                                SDValue(FalseC, 0));
20638           if (N->getNumValues() == 2)  // Dead flag value?
20639             return DCI.CombineTo(N, Cond, SDValue());
20640           return Cond;
20641         }
20642       }
20643     }
20644   }
20645
20646   // Handle these cases:
20647   //   (select (x != c), e, c) -> select (x != c), e, x),
20648   //   (select (x == c), c, e) -> select (x == c), x, e)
20649   // where the c is an integer constant, and the "select" is the combination
20650   // of CMOV and CMP.
20651   //
20652   // The rationale for this change is that the conditional-move from a constant
20653   // needs two instructions, however, conditional-move from a register needs
20654   // only one instruction.
20655   //
20656   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20657   //  some instruction-combining opportunities. This opt needs to be
20658   //  postponed as late as possible.
20659   //
20660   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20661     // the DCI.xxxx conditions are provided to postpone the optimization as
20662     // late as possible.
20663
20664     ConstantSDNode *CmpAgainst = nullptr;
20665     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20666         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20667         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20668
20669       if (CC == X86::COND_NE &&
20670           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20671         CC = X86::GetOppositeBranchCondition(CC);
20672         std::swap(TrueOp, FalseOp);
20673       }
20674
20675       if (CC == X86::COND_E &&
20676           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20677         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20678                           DAG.getConstant(CC, MVT::i8), Cond };
20679         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20680       }
20681     }
20682   }
20683
20684   return SDValue();
20685 }
20686
20687 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20688                                                 const X86Subtarget *Subtarget) {
20689   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20690   switch (IntNo) {
20691   default: return SDValue();
20692   // SSE/AVX/AVX2 blend intrinsics.
20693   case Intrinsic::x86_avx2_pblendvb:
20694   case Intrinsic::x86_avx2_pblendw:
20695   case Intrinsic::x86_avx2_pblendd_128:
20696   case Intrinsic::x86_avx2_pblendd_256:
20697     // Don't try to simplify this intrinsic if we don't have AVX2.
20698     if (!Subtarget->hasAVX2())
20699       return SDValue();
20700     // FALL-THROUGH
20701   case Intrinsic::x86_avx_blend_pd_256:
20702   case Intrinsic::x86_avx_blend_ps_256:
20703   case Intrinsic::x86_avx_blendv_pd_256:
20704   case Intrinsic::x86_avx_blendv_ps_256:
20705     // Don't try to simplify this intrinsic if we don't have AVX.
20706     if (!Subtarget->hasAVX())
20707       return SDValue();
20708     // FALL-THROUGH
20709   case Intrinsic::x86_sse41_pblendw:
20710   case Intrinsic::x86_sse41_blendpd:
20711   case Intrinsic::x86_sse41_blendps:
20712   case Intrinsic::x86_sse41_blendvps:
20713   case Intrinsic::x86_sse41_blendvpd:
20714   case Intrinsic::x86_sse41_pblendvb: {
20715     SDValue Op0 = N->getOperand(1);
20716     SDValue Op1 = N->getOperand(2);
20717     SDValue Mask = N->getOperand(3);
20718
20719     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20720     if (!Subtarget->hasSSE41())
20721       return SDValue();
20722
20723     // fold (blend A, A, Mask) -> A
20724     if (Op0 == Op1)
20725       return Op0;
20726     // fold (blend A, B, allZeros) -> A
20727     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20728       return Op0;
20729     // fold (blend A, B, allOnes) -> B
20730     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20731       return Op1;
20732     
20733     // Simplify the case where the mask is a constant i32 value.
20734     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20735       if (C->isNullValue())
20736         return Op0;
20737       if (C->isAllOnesValue())
20738         return Op1;
20739     }
20740
20741     return SDValue();
20742   }
20743
20744   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20745   case Intrinsic::x86_sse2_psrai_w:
20746   case Intrinsic::x86_sse2_psrai_d:
20747   case Intrinsic::x86_avx2_psrai_w:
20748   case Intrinsic::x86_avx2_psrai_d:
20749   case Intrinsic::x86_sse2_psra_w:
20750   case Intrinsic::x86_sse2_psra_d:
20751   case Intrinsic::x86_avx2_psra_w:
20752   case Intrinsic::x86_avx2_psra_d: {
20753     SDValue Op0 = N->getOperand(1);
20754     SDValue Op1 = N->getOperand(2);
20755     EVT VT = Op0.getValueType();
20756     assert(VT.isVector() && "Expected a vector type!");
20757
20758     if (isa<BuildVectorSDNode>(Op1))
20759       Op1 = Op1.getOperand(0);
20760
20761     if (!isa<ConstantSDNode>(Op1))
20762       return SDValue();
20763
20764     EVT SVT = VT.getVectorElementType();
20765     unsigned SVTBits = SVT.getSizeInBits();
20766
20767     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20768     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20769     uint64_t ShAmt = C.getZExtValue();
20770
20771     // Don't try to convert this shift into a ISD::SRA if the shift
20772     // count is bigger than or equal to the element size.
20773     if (ShAmt >= SVTBits)
20774       return SDValue();
20775
20776     // Trivial case: if the shift count is zero, then fold this
20777     // into the first operand.
20778     if (ShAmt == 0)
20779       return Op0;
20780
20781     // Replace this packed shift intrinsic with a target independent
20782     // shift dag node.
20783     SDValue Splat = DAG.getConstant(C, VT);
20784     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20785   }
20786   }
20787 }
20788
20789 /// PerformMulCombine - Optimize a single multiply with constant into two
20790 /// in order to implement it with two cheaper instructions, e.g.
20791 /// LEA + SHL, LEA + LEA.
20792 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20793                                  TargetLowering::DAGCombinerInfo &DCI) {
20794   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20795     return SDValue();
20796
20797   EVT VT = N->getValueType(0);
20798   if (VT != MVT::i64)
20799     return SDValue();
20800
20801   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20802   if (!C)
20803     return SDValue();
20804   uint64_t MulAmt = C->getZExtValue();
20805   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20806     return SDValue();
20807
20808   uint64_t MulAmt1 = 0;
20809   uint64_t MulAmt2 = 0;
20810   if ((MulAmt % 9) == 0) {
20811     MulAmt1 = 9;
20812     MulAmt2 = MulAmt / 9;
20813   } else if ((MulAmt % 5) == 0) {
20814     MulAmt1 = 5;
20815     MulAmt2 = MulAmt / 5;
20816   } else if ((MulAmt % 3) == 0) {
20817     MulAmt1 = 3;
20818     MulAmt2 = MulAmt / 3;
20819   }
20820   if (MulAmt2 &&
20821       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20822     SDLoc DL(N);
20823
20824     if (isPowerOf2_64(MulAmt2) &&
20825         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20826       // If second multiplifer is pow2, issue it first. We want the multiply by
20827       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20828       // is an add.
20829       std::swap(MulAmt1, MulAmt2);
20830
20831     SDValue NewMul;
20832     if (isPowerOf2_64(MulAmt1))
20833       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20834                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20835     else
20836       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20837                            DAG.getConstant(MulAmt1, VT));
20838
20839     if (isPowerOf2_64(MulAmt2))
20840       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20841                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20842     else
20843       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20844                            DAG.getConstant(MulAmt2, VT));
20845
20846     // Do not add new nodes to DAG combiner worklist.
20847     DCI.CombineTo(N, NewMul, false);
20848   }
20849   return SDValue();
20850 }
20851
20852 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20853   SDValue N0 = N->getOperand(0);
20854   SDValue N1 = N->getOperand(1);
20855   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20856   EVT VT = N0.getValueType();
20857
20858   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20859   // since the result of setcc_c is all zero's or all ones.
20860   if (VT.isInteger() && !VT.isVector() &&
20861       N1C && N0.getOpcode() == ISD::AND &&
20862       N0.getOperand(1).getOpcode() == ISD::Constant) {
20863     SDValue N00 = N0.getOperand(0);
20864     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20865         ((N00.getOpcode() == ISD::ANY_EXTEND ||
20866           N00.getOpcode() == ISD::ZERO_EXTEND) &&
20867          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20868       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20869       APInt ShAmt = N1C->getAPIntValue();
20870       Mask = Mask.shl(ShAmt);
20871       if (Mask != 0)
20872         return DAG.getNode(ISD::AND, SDLoc(N), VT,
20873                            N00, DAG.getConstant(Mask, VT));
20874     }
20875   }
20876
20877   // Hardware support for vector shifts is sparse which makes us scalarize the
20878   // vector operations in many cases. Also, on sandybridge ADD is faster than
20879   // shl.
20880   // (shl V, 1) -> add V,V
20881   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20882     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
20883       assert(N0.getValueType().isVector() && "Invalid vector shift type");
20884       // We shift all of the values by one. In many cases we do not have
20885       // hardware support for this operation. This is better expressed as an ADD
20886       // of two values.
20887       if (N1SplatC->getZExtValue() == 1)
20888         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20889     }
20890
20891   return SDValue();
20892 }
20893
20894 /// \brief Returns a vector of 0s if the node in input is a vector logical
20895 /// shift by a constant amount which is known to be bigger than or equal
20896 /// to the vector element size in bits.
20897 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20898                                       const X86Subtarget *Subtarget) {
20899   EVT VT = N->getValueType(0);
20900
20901   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20902       (!Subtarget->hasInt256() ||
20903        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20904     return SDValue();
20905
20906   SDValue Amt = N->getOperand(1);
20907   SDLoc DL(N);
20908   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20909     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
20910       APInt ShiftAmt = AmtSplat->getAPIntValue();
20911       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20912
20913       // SSE2/AVX2 logical shifts always return a vector of 0s
20914       // if the shift amount is bigger than or equal to
20915       // the element size. The constant shift amount will be
20916       // encoded as a 8-bit immediate.
20917       if (ShiftAmt.trunc(8).uge(MaxAmount))
20918         return getZeroVector(VT, Subtarget, DAG, DL);
20919     }
20920
20921   return SDValue();
20922 }
20923
20924 /// PerformShiftCombine - Combine shifts.
20925 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20926                                    TargetLowering::DAGCombinerInfo &DCI,
20927                                    const X86Subtarget *Subtarget) {
20928   if (N->getOpcode() == ISD::SHL) {
20929     SDValue V = PerformSHLCombine(N, DAG);
20930     if (V.getNode()) return V;
20931   }
20932
20933   if (N->getOpcode() != ISD::SRA) {
20934     // Try to fold this logical shift into a zero vector.
20935     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20936     if (V.getNode()) return V;
20937   }
20938
20939   return SDValue();
20940 }
20941
20942 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
20943 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20944 // and friends.  Likewise for OR -> CMPNEQSS.
20945 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20946                             TargetLowering::DAGCombinerInfo &DCI,
20947                             const X86Subtarget *Subtarget) {
20948   unsigned opcode;
20949
20950   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20951   // we're requiring SSE2 for both.
20952   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20953     SDValue N0 = N->getOperand(0);
20954     SDValue N1 = N->getOperand(1);
20955     SDValue CMP0 = N0->getOperand(1);
20956     SDValue CMP1 = N1->getOperand(1);
20957     SDLoc DL(N);
20958
20959     // The SETCCs should both refer to the same CMP.
20960     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20961       return SDValue();
20962
20963     SDValue CMP00 = CMP0->getOperand(0);
20964     SDValue CMP01 = CMP0->getOperand(1);
20965     EVT     VT    = CMP00.getValueType();
20966
20967     if (VT == MVT::f32 || VT == MVT::f64) {
20968       bool ExpectingFlags = false;
20969       // Check for any users that want flags:
20970       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20971            !ExpectingFlags && UI != UE; ++UI)
20972         switch (UI->getOpcode()) {
20973         default:
20974         case ISD::BR_CC:
20975         case ISD::BRCOND:
20976         case ISD::SELECT:
20977           ExpectingFlags = true;
20978           break;
20979         case ISD::CopyToReg:
20980         case ISD::SIGN_EXTEND:
20981         case ISD::ZERO_EXTEND:
20982         case ISD::ANY_EXTEND:
20983           break;
20984         }
20985
20986       if (!ExpectingFlags) {
20987         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20988         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20989
20990         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20991           X86::CondCode tmp = cc0;
20992           cc0 = cc1;
20993           cc1 = tmp;
20994         }
20995
20996         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
20997             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20998           // FIXME: need symbolic constants for these magic numbers.
20999           // See X86ATTInstPrinter.cpp:printSSECC().
21000           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21001           if (Subtarget->hasAVX512()) {
21002             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21003                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21004             if (N->getValueType(0) != MVT::i1)
21005               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21006                                  FSetCC);
21007             return FSetCC;
21008           }
21009           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21010                                               CMP00.getValueType(), CMP00, CMP01,
21011                                               DAG.getConstant(x86cc, MVT::i8));
21012
21013           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21014           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21015
21016           if (is64BitFP && !Subtarget->is64Bit()) {
21017             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21018             // 64-bit integer, since that's not a legal type. Since
21019             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21020             // bits, but can do this little dance to extract the lowest 32 bits
21021             // and work with those going forward.
21022             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21023                                            OnesOrZeroesF);
21024             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21025                                            Vector64);
21026             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21027                                         Vector32, DAG.getIntPtrConstant(0));
21028             IntVT = MVT::i32;
21029           }
21030
21031           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21032           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21033                                       DAG.getConstant(1, IntVT));
21034           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21035           return OneBitOfTruth;
21036         }
21037       }
21038     }
21039   }
21040   return SDValue();
21041 }
21042
21043 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21044 /// so it can be folded inside ANDNP.
21045 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21046   EVT VT = N->getValueType(0);
21047
21048   // Match direct AllOnes for 128 and 256-bit vectors
21049   if (ISD::isBuildVectorAllOnes(N))
21050     return true;
21051
21052   // Look through a bit convert.
21053   if (N->getOpcode() == ISD::BITCAST)
21054     N = N->getOperand(0).getNode();
21055
21056   // Sometimes the operand may come from a insert_subvector building a 256-bit
21057   // allones vector
21058   if (VT.is256BitVector() &&
21059       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21060     SDValue V1 = N->getOperand(0);
21061     SDValue V2 = N->getOperand(1);
21062
21063     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21064         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21065         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21066         ISD::isBuildVectorAllOnes(V2.getNode()))
21067       return true;
21068   }
21069
21070   return false;
21071 }
21072
21073 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21074 // register. In most cases we actually compare or select YMM-sized registers
21075 // and mixing the two types creates horrible code. This method optimizes
21076 // some of the transition sequences.
21077 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21078                                  TargetLowering::DAGCombinerInfo &DCI,
21079                                  const X86Subtarget *Subtarget) {
21080   EVT VT = N->getValueType(0);
21081   if (!VT.is256BitVector())
21082     return SDValue();
21083
21084   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21085           N->getOpcode() == ISD::ZERO_EXTEND ||
21086           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21087
21088   SDValue Narrow = N->getOperand(0);
21089   EVT NarrowVT = Narrow->getValueType(0);
21090   if (!NarrowVT.is128BitVector())
21091     return SDValue();
21092
21093   if (Narrow->getOpcode() != ISD::XOR &&
21094       Narrow->getOpcode() != ISD::AND &&
21095       Narrow->getOpcode() != ISD::OR)
21096     return SDValue();
21097
21098   SDValue N0  = Narrow->getOperand(0);
21099   SDValue N1  = Narrow->getOperand(1);
21100   SDLoc DL(Narrow);
21101
21102   // The Left side has to be a trunc.
21103   if (N0.getOpcode() != ISD::TRUNCATE)
21104     return SDValue();
21105
21106   // The type of the truncated inputs.
21107   EVT WideVT = N0->getOperand(0)->getValueType(0);
21108   if (WideVT != VT)
21109     return SDValue();
21110
21111   // The right side has to be a 'trunc' or a constant vector.
21112   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21113   ConstantSDNode *RHSConstSplat = nullptr;
21114   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21115     RHSConstSplat = RHSBV->getConstantSplatNode();
21116   if (!RHSTrunc && !RHSConstSplat)
21117     return SDValue();
21118
21119   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21120
21121   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21122     return SDValue();
21123
21124   // Set N0 and N1 to hold the inputs to the new wide operation.
21125   N0 = N0->getOperand(0);
21126   if (RHSConstSplat) {
21127     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21128                      SDValue(RHSConstSplat, 0));
21129     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21130     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21131   } else if (RHSTrunc) {
21132     N1 = N1->getOperand(0);
21133   }
21134
21135   // Generate the wide operation.
21136   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21137   unsigned Opcode = N->getOpcode();
21138   switch (Opcode) {
21139   case ISD::ANY_EXTEND:
21140     return Op;
21141   case ISD::ZERO_EXTEND: {
21142     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21143     APInt Mask = APInt::getAllOnesValue(InBits);
21144     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21145     return DAG.getNode(ISD::AND, DL, VT,
21146                        Op, DAG.getConstant(Mask, VT));
21147   }
21148   case ISD::SIGN_EXTEND:
21149     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21150                        Op, DAG.getValueType(NarrowVT));
21151   default:
21152     llvm_unreachable("Unexpected opcode");
21153   }
21154 }
21155
21156 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21157                                  TargetLowering::DAGCombinerInfo &DCI,
21158                                  const X86Subtarget *Subtarget) {
21159   EVT VT = N->getValueType(0);
21160   if (DCI.isBeforeLegalizeOps())
21161     return SDValue();
21162
21163   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21164   if (R.getNode())
21165     return R;
21166
21167   // Create BEXTR instructions
21168   // BEXTR is ((X >> imm) & (2**size-1))
21169   if (VT == MVT::i32 || VT == MVT::i64) {
21170     SDValue N0 = N->getOperand(0);
21171     SDValue N1 = N->getOperand(1);
21172     SDLoc DL(N);
21173
21174     // Check for BEXTR.
21175     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21176         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21177       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21178       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21179       if (MaskNode && ShiftNode) {
21180         uint64_t Mask = MaskNode->getZExtValue();
21181         uint64_t Shift = ShiftNode->getZExtValue();
21182         if (isMask_64(Mask)) {
21183           uint64_t MaskSize = CountPopulation_64(Mask);
21184           if (Shift + MaskSize <= VT.getSizeInBits())
21185             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21186                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21187         }
21188       }
21189     } // BEXTR
21190
21191     return SDValue();
21192   }
21193
21194   // Want to form ANDNP nodes:
21195   // 1) In the hopes of then easily combining them with OR and AND nodes
21196   //    to form PBLEND/PSIGN.
21197   // 2) To match ANDN packed intrinsics
21198   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21199     return SDValue();
21200
21201   SDValue N0 = N->getOperand(0);
21202   SDValue N1 = N->getOperand(1);
21203   SDLoc DL(N);
21204
21205   // Check LHS for vnot
21206   if (N0.getOpcode() == ISD::XOR &&
21207       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21208       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21209     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21210
21211   // Check RHS for vnot
21212   if (N1.getOpcode() == ISD::XOR &&
21213       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21214       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21215     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21216
21217   return SDValue();
21218 }
21219
21220 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21221                                 TargetLowering::DAGCombinerInfo &DCI,
21222                                 const X86Subtarget *Subtarget) {
21223   if (DCI.isBeforeLegalizeOps())
21224     return SDValue();
21225
21226   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21227   if (R.getNode())
21228     return R;
21229
21230   SDValue N0 = N->getOperand(0);
21231   SDValue N1 = N->getOperand(1);
21232   EVT VT = N->getValueType(0);
21233
21234   // look for psign/blend
21235   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21236     if (!Subtarget->hasSSSE3() ||
21237         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21238       return SDValue();
21239
21240     // Canonicalize pandn to RHS
21241     if (N0.getOpcode() == X86ISD::ANDNP)
21242       std::swap(N0, N1);
21243     // or (and (m, y), (pandn m, x))
21244     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21245       SDValue Mask = N1.getOperand(0);
21246       SDValue X    = N1.getOperand(1);
21247       SDValue Y;
21248       if (N0.getOperand(0) == Mask)
21249         Y = N0.getOperand(1);
21250       if (N0.getOperand(1) == Mask)
21251         Y = N0.getOperand(0);
21252
21253       // Check to see if the mask appeared in both the AND and ANDNP and
21254       if (!Y.getNode())
21255         return SDValue();
21256
21257       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21258       // Look through mask bitcast.
21259       if (Mask.getOpcode() == ISD::BITCAST)
21260         Mask = Mask.getOperand(0);
21261       if (X.getOpcode() == ISD::BITCAST)
21262         X = X.getOperand(0);
21263       if (Y.getOpcode() == ISD::BITCAST)
21264         Y = Y.getOperand(0);
21265
21266       EVT MaskVT = Mask.getValueType();
21267
21268       // Validate that the Mask operand is a vector sra node.
21269       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21270       // there is no psrai.b
21271       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21272       unsigned SraAmt = ~0;
21273       if (Mask.getOpcode() == ISD::SRA) {
21274         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21275           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21276             SraAmt = AmtConst->getZExtValue();
21277       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21278         SDValue SraC = Mask.getOperand(1);
21279         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21280       }
21281       if ((SraAmt + 1) != EltBits)
21282         return SDValue();
21283
21284       SDLoc DL(N);
21285
21286       // Now we know we at least have a plendvb with the mask val.  See if
21287       // we can form a psignb/w/d.
21288       // psign = x.type == y.type == mask.type && y = sub(0, x);
21289       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21290           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21291           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21292         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21293                "Unsupported VT for PSIGN");
21294         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21295         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21296       }
21297       // PBLENDVB only available on SSE 4.1
21298       if (!Subtarget->hasSSE41())
21299         return SDValue();
21300
21301       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21302
21303       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21304       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21305       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21306       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21307       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21308     }
21309   }
21310
21311   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21312     return SDValue();
21313
21314   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21315   MachineFunction &MF = DAG.getMachineFunction();
21316   bool OptForSize = MF.getFunction()->getAttributes().
21317     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21318
21319   // SHLD/SHRD instructions have lower register pressure, but on some
21320   // platforms they have higher latency than the equivalent
21321   // series of shifts/or that would otherwise be generated.
21322   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21323   // have higher latencies and we are not optimizing for size.
21324   if (!OptForSize && Subtarget->isSHLDSlow())
21325     return SDValue();
21326
21327   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21328     std::swap(N0, N1);
21329   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21330     return SDValue();
21331   if (!N0.hasOneUse() || !N1.hasOneUse())
21332     return SDValue();
21333
21334   SDValue ShAmt0 = N0.getOperand(1);
21335   if (ShAmt0.getValueType() != MVT::i8)
21336     return SDValue();
21337   SDValue ShAmt1 = N1.getOperand(1);
21338   if (ShAmt1.getValueType() != MVT::i8)
21339     return SDValue();
21340   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21341     ShAmt0 = ShAmt0.getOperand(0);
21342   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21343     ShAmt1 = ShAmt1.getOperand(0);
21344
21345   SDLoc DL(N);
21346   unsigned Opc = X86ISD::SHLD;
21347   SDValue Op0 = N0.getOperand(0);
21348   SDValue Op1 = N1.getOperand(0);
21349   if (ShAmt0.getOpcode() == ISD::SUB) {
21350     Opc = X86ISD::SHRD;
21351     std::swap(Op0, Op1);
21352     std::swap(ShAmt0, ShAmt1);
21353   }
21354
21355   unsigned Bits = VT.getSizeInBits();
21356   if (ShAmt1.getOpcode() == ISD::SUB) {
21357     SDValue Sum = ShAmt1.getOperand(0);
21358     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21359       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21360       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21361         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21362       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21363         return DAG.getNode(Opc, DL, VT,
21364                            Op0, Op1,
21365                            DAG.getNode(ISD::TRUNCATE, DL,
21366                                        MVT::i8, ShAmt0));
21367     }
21368   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21369     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21370     if (ShAmt0C &&
21371         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21372       return DAG.getNode(Opc, DL, VT,
21373                          N0.getOperand(0), N1.getOperand(0),
21374                          DAG.getNode(ISD::TRUNCATE, DL,
21375                                        MVT::i8, ShAmt0));
21376   }
21377
21378   return SDValue();
21379 }
21380
21381 // Generate NEG and CMOV for integer abs.
21382 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21383   EVT VT = N->getValueType(0);
21384
21385   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21386   // 8-bit integer abs to NEG and CMOV.
21387   if (VT.isInteger() && VT.getSizeInBits() == 8)
21388     return SDValue();
21389
21390   SDValue N0 = N->getOperand(0);
21391   SDValue N1 = N->getOperand(1);
21392   SDLoc DL(N);
21393
21394   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21395   // and change it to SUB and CMOV.
21396   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21397       N0.getOpcode() == ISD::ADD &&
21398       N0.getOperand(1) == N1 &&
21399       N1.getOpcode() == ISD::SRA &&
21400       N1.getOperand(0) == N0.getOperand(0))
21401     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21402       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21403         // Generate SUB & CMOV.
21404         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21405                                   DAG.getConstant(0, VT), N0.getOperand(0));
21406
21407         SDValue Ops[] = { N0.getOperand(0), Neg,
21408                           DAG.getConstant(X86::COND_GE, MVT::i8),
21409                           SDValue(Neg.getNode(), 1) };
21410         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21411       }
21412   return SDValue();
21413 }
21414
21415 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21416 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21417                                  TargetLowering::DAGCombinerInfo &DCI,
21418                                  const X86Subtarget *Subtarget) {
21419   if (DCI.isBeforeLegalizeOps())
21420     return SDValue();
21421
21422   if (Subtarget->hasCMov()) {
21423     SDValue RV = performIntegerAbsCombine(N, DAG);
21424     if (RV.getNode())
21425       return RV;
21426   }
21427
21428   return SDValue();
21429 }
21430
21431 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21432 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21433                                   TargetLowering::DAGCombinerInfo &DCI,
21434                                   const X86Subtarget *Subtarget) {
21435   LoadSDNode *Ld = cast<LoadSDNode>(N);
21436   EVT RegVT = Ld->getValueType(0);
21437   EVT MemVT = Ld->getMemoryVT();
21438   SDLoc dl(Ld);
21439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21440
21441   // On Sandybridge unaligned 256bit loads are inefficient.
21442   ISD::LoadExtType Ext = Ld->getExtensionType();
21443   unsigned Alignment = Ld->getAlignment();
21444   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21445   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21446       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21447     unsigned NumElems = RegVT.getVectorNumElements();
21448     if (NumElems < 2)
21449       return SDValue();
21450
21451     SDValue Ptr = Ld->getBasePtr();
21452     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21453
21454     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21455                                   NumElems/2);
21456     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21457                                 Ld->getPointerInfo(), Ld->isVolatile(),
21458                                 Ld->isNonTemporal(), Ld->isInvariant(),
21459                                 Alignment);
21460     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21461     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21462                                 Ld->getPointerInfo(), Ld->isVolatile(),
21463                                 Ld->isNonTemporal(), Ld->isInvariant(),
21464                                 std::min(16U, Alignment));
21465     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21466                              Load1.getValue(1),
21467                              Load2.getValue(1));
21468
21469     SDValue NewVec = DAG.getUNDEF(RegVT);
21470     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21471     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21472     return DCI.CombineTo(N, NewVec, TF, true);
21473   }
21474
21475   return SDValue();
21476 }
21477
21478 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21479 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21480                                    const X86Subtarget *Subtarget) {
21481   StoreSDNode *St = cast<StoreSDNode>(N);
21482   EVT VT = St->getValue().getValueType();
21483   EVT StVT = St->getMemoryVT();
21484   SDLoc dl(St);
21485   SDValue StoredVal = St->getOperand(1);
21486   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21487
21488   // If we are saving a concatenation of two XMM registers, perform two stores.
21489   // On Sandy Bridge, 256-bit memory operations are executed by two
21490   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21491   // memory  operation.
21492   unsigned Alignment = St->getAlignment();
21493   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21494   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21495       StVT == VT && !IsAligned) {
21496     unsigned NumElems = VT.getVectorNumElements();
21497     if (NumElems < 2)
21498       return SDValue();
21499
21500     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21501     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21502
21503     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21504     SDValue Ptr0 = St->getBasePtr();
21505     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21506
21507     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21508                                 St->getPointerInfo(), St->isVolatile(),
21509                                 St->isNonTemporal(), Alignment);
21510     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21511                                 St->getPointerInfo(), St->isVolatile(),
21512                                 St->isNonTemporal(),
21513                                 std::min(16U, Alignment));
21514     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21515   }
21516
21517   // Optimize trunc store (of multiple scalars) to shuffle and store.
21518   // First, pack all of the elements in one place. Next, store to memory
21519   // in fewer chunks.
21520   if (St->isTruncatingStore() && VT.isVector()) {
21521     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21522     unsigned NumElems = VT.getVectorNumElements();
21523     assert(StVT != VT && "Cannot truncate to the same type");
21524     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21525     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21526
21527     // From, To sizes and ElemCount must be pow of two
21528     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21529     // We are going to use the original vector elt for storing.
21530     // Accumulated smaller vector elements must be a multiple of the store size.
21531     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21532
21533     unsigned SizeRatio  = FromSz / ToSz;
21534
21535     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21536
21537     // Create a type on which we perform the shuffle
21538     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21539             StVT.getScalarType(), NumElems*SizeRatio);
21540
21541     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21542
21543     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21544     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21545     for (unsigned i = 0; i != NumElems; ++i)
21546       ShuffleVec[i] = i * SizeRatio;
21547
21548     // Can't shuffle using an illegal type.
21549     if (!TLI.isTypeLegal(WideVecVT))
21550       return SDValue();
21551
21552     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21553                                          DAG.getUNDEF(WideVecVT),
21554                                          &ShuffleVec[0]);
21555     // At this point all of the data is stored at the bottom of the
21556     // register. We now need to save it to mem.
21557
21558     // Find the largest store unit
21559     MVT StoreType = MVT::i8;
21560     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21561          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21562       MVT Tp = (MVT::SimpleValueType)tp;
21563       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21564         StoreType = Tp;
21565     }
21566
21567     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21568     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21569         (64 <= NumElems * ToSz))
21570       StoreType = MVT::f64;
21571
21572     // Bitcast the original vector into a vector of store-size units
21573     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21574             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21575     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21576     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21577     SmallVector<SDValue, 8> Chains;
21578     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21579                                         TLI.getPointerTy());
21580     SDValue Ptr = St->getBasePtr();
21581
21582     // Perform one or more big stores into memory.
21583     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21584       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21585                                    StoreType, ShuffWide,
21586                                    DAG.getIntPtrConstant(i));
21587       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21588                                 St->getPointerInfo(), St->isVolatile(),
21589                                 St->isNonTemporal(), St->getAlignment());
21590       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21591       Chains.push_back(Ch);
21592     }
21593
21594     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21595   }
21596
21597   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21598   // the FP state in cases where an emms may be missing.
21599   // A preferable solution to the general problem is to figure out the right
21600   // places to insert EMMS.  This qualifies as a quick hack.
21601
21602   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21603   if (VT.getSizeInBits() != 64)
21604     return SDValue();
21605
21606   const Function *F = DAG.getMachineFunction().getFunction();
21607   bool NoImplicitFloatOps = F->getAttributes().
21608     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21609   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21610                      && Subtarget->hasSSE2();
21611   if ((VT.isVector() ||
21612        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21613       isa<LoadSDNode>(St->getValue()) &&
21614       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21615       St->getChain().hasOneUse() && !St->isVolatile()) {
21616     SDNode* LdVal = St->getValue().getNode();
21617     LoadSDNode *Ld = nullptr;
21618     int TokenFactorIndex = -1;
21619     SmallVector<SDValue, 8> Ops;
21620     SDNode* ChainVal = St->getChain().getNode();
21621     // Must be a store of a load.  We currently handle two cases:  the load
21622     // is a direct child, and it's under an intervening TokenFactor.  It is
21623     // possible to dig deeper under nested TokenFactors.
21624     if (ChainVal == LdVal)
21625       Ld = cast<LoadSDNode>(St->getChain());
21626     else if (St->getValue().hasOneUse() &&
21627              ChainVal->getOpcode() == ISD::TokenFactor) {
21628       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21629         if (ChainVal->getOperand(i).getNode() == LdVal) {
21630           TokenFactorIndex = i;
21631           Ld = cast<LoadSDNode>(St->getValue());
21632         } else
21633           Ops.push_back(ChainVal->getOperand(i));
21634       }
21635     }
21636
21637     if (!Ld || !ISD::isNormalLoad(Ld))
21638       return SDValue();
21639
21640     // If this is not the MMX case, i.e. we are just turning i64 load/store
21641     // into f64 load/store, avoid the transformation if there are multiple
21642     // uses of the loaded value.
21643     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21644       return SDValue();
21645
21646     SDLoc LdDL(Ld);
21647     SDLoc StDL(N);
21648     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21649     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21650     // pair instead.
21651     if (Subtarget->is64Bit() || F64IsLegal) {
21652       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21653       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21654                                   Ld->getPointerInfo(), Ld->isVolatile(),
21655                                   Ld->isNonTemporal(), Ld->isInvariant(),
21656                                   Ld->getAlignment());
21657       SDValue NewChain = NewLd.getValue(1);
21658       if (TokenFactorIndex != -1) {
21659         Ops.push_back(NewChain);
21660         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21661       }
21662       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21663                           St->getPointerInfo(),
21664                           St->isVolatile(), St->isNonTemporal(),
21665                           St->getAlignment());
21666     }
21667
21668     // Otherwise, lower to two pairs of 32-bit loads / stores.
21669     SDValue LoAddr = Ld->getBasePtr();
21670     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21671                                  DAG.getConstant(4, MVT::i32));
21672
21673     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21674                                Ld->getPointerInfo(),
21675                                Ld->isVolatile(), Ld->isNonTemporal(),
21676                                Ld->isInvariant(), Ld->getAlignment());
21677     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21678                                Ld->getPointerInfo().getWithOffset(4),
21679                                Ld->isVolatile(), Ld->isNonTemporal(),
21680                                Ld->isInvariant(),
21681                                MinAlign(Ld->getAlignment(), 4));
21682
21683     SDValue NewChain = LoLd.getValue(1);
21684     if (TokenFactorIndex != -1) {
21685       Ops.push_back(LoLd);
21686       Ops.push_back(HiLd);
21687       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21688     }
21689
21690     LoAddr = St->getBasePtr();
21691     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21692                          DAG.getConstant(4, MVT::i32));
21693
21694     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21695                                 St->getPointerInfo(),
21696                                 St->isVolatile(), St->isNonTemporal(),
21697                                 St->getAlignment());
21698     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21699                                 St->getPointerInfo().getWithOffset(4),
21700                                 St->isVolatile(),
21701                                 St->isNonTemporal(),
21702                                 MinAlign(St->getAlignment(), 4));
21703     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21704   }
21705   return SDValue();
21706 }
21707
21708 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21709 /// and return the operands for the horizontal operation in LHS and RHS.  A
21710 /// horizontal operation performs the binary operation on successive elements
21711 /// of its first operand, then on successive elements of its second operand,
21712 /// returning the resulting values in a vector.  For example, if
21713 ///   A = < float a0, float a1, float a2, float a3 >
21714 /// and
21715 ///   B = < float b0, float b1, float b2, float b3 >
21716 /// then the result of doing a horizontal operation on A and B is
21717 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21718 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21719 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21720 /// set to A, RHS to B, and the routine returns 'true'.
21721 /// Note that the binary operation should have the property that if one of the
21722 /// operands is UNDEF then the result is UNDEF.
21723 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21724   // Look for the following pattern: if
21725   //   A = < float a0, float a1, float a2, float a3 >
21726   //   B = < float b0, float b1, float b2, float b3 >
21727   // and
21728   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21729   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21730   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21731   // which is A horizontal-op B.
21732
21733   // At least one of the operands should be a vector shuffle.
21734   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21735       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21736     return false;
21737
21738   MVT VT = LHS.getSimpleValueType();
21739
21740   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21741          "Unsupported vector type for horizontal add/sub");
21742
21743   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21744   // operate independently on 128-bit lanes.
21745   unsigned NumElts = VT.getVectorNumElements();
21746   unsigned NumLanes = VT.getSizeInBits()/128;
21747   unsigned NumLaneElts = NumElts / NumLanes;
21748   assert((NumLaneElts % 2 == 0) &&
21749          "Vector type should have an even number of elements in each lane");
21750   unsigned HalfLaneElts = NumLaneElts/2;
21751
21752   // View LHS in the form
21753   //   LHS = VECTOR_SHUFFLE A, B, LMask
21754   // If LHS is not a shuffle then pretend it is the shuffle
21755   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21756   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21757   // type VT.
21758   SDValue A, B;
21759   SmallVector<int, 16> LMask(NumElts);
21760   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21761     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21762       A = LHS.getOperand(0);
21763     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21764       B = LHS.getOperand(1);
21765     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21766     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21767   } else {
21768     if (LHS.getOpcode() != ISD::UNDEF)
21769       A = LHS;
21770     for (unsigned i = 0; i != NumElts; ++i)
21771       LMask[i] = i;
21772   }
21773
21774   // Likewise, view RHS in the form
21775   //   RHS = VECTOR_SHUFFLE C, D, RMask
21776   SDValue C, D;
21777   SmallVector<int, 16> RMask(NumElts);
21778   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21779     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21780       C = RHS.getOperand(0);
21781     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21782       D = RHS.getOperand(1);
21783     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21784     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21785   } else {
21786     if (RHS.getOpcode() != ISD::UNDEF)
21787       C = RHS;
21788     for (unsigned i = 0; i != NumElts; ++i)
21789       RMask[i] = i;
21790   }
21791
21792   // Check that the shuffles are both shuffling the same vectors.
21793   if (!(A == C && B == D) && !(A == D && B == C))
21794     return false;
21795
21796   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21797   if (!A.getNode() && !B.getNode())
21798     return false;
21799
21800   // If A and B occur in reverse order in RHS, then "swap" them (which means
21801   // rewriting the mask).
21802   if (A != C)
21803     CommuteVectorShuffleMask(RMask, NumElts);
21804
21805   // At this point LHS and RHS are equivalent to
21806   //   LHS = VECTOR_SHUFFLE A, B, LMask
21807   //   RHS = VECTOR_SHUFFLE A, B, RMask
21808   // Check that the masks correspond to performing a horizontal operation.
21809   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21810     for (unsigned i = 0; i != NumLaneElts; ++i) {
21811       int LIdx = LMask[i+l], RIdx = RMask[i+l];
21812
21813       // Ignore any UNDEF components.
21814       if (LIdx < 0 || RIdx < 0 ||
21815           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21816           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21817         continue;
21818
21819       // Check that successive elements are being operated on.  If not, this is
21820       // not a horizontal operation.
21821       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21822       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21823       if (!(LIdx == Index && RIdx == Index + 1) &&
21824           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21825         return false;
21826     }
21827   }
21828
21829   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21830   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21831   return true;
21832 }
21833
21834 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21835 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21836                                   const X86Subtarget *Subtarget) {
21837   EVT VT = N->getValueType(0);
21838   SDValue LHS = N->getOperand(0);
21839   SDValue RHS = N->getOperand(1);
21840
21841   // Try to synthesize horizontal adds from adds of shuffles.
21842   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21843        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21844       isHorizontalBinOp(LHS, RHS, true))
21845     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21846   return SDValue();
21847 }
21848
21849 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21850 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21851                                   const X86Subtarget *Subtarget) {
21852   EVT VT = N->getValueType(0);
21853   SDValue LHS = N->getOperand(0);
21854   SDValue RHS = N->getOperand(1);
21855
21856   // Try to synthesize horizontal subs from subs of shuffles.
21857   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21858        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21859       isHorizontalBinOp(LHS, RHS, false))
21860     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21861   return SDValue();
21862 }
21863
21864 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21865 /// X86ISD::FXOR nodes.
21866 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21867   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21868   // F[X]OR(0.0, x) -> x
21869   // F[X]OR(x, 0.0) -> x
21870   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21871     if (C->getValueAPF().isPosZero())
21872       return N->getOperand(1);
21873   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21874     if (C->getValueAPF().isPosZero())
21875       return N->getOperand(0);
21876   return SDValue();
21877 }
21878
21879 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21880 /// X86ISD::FMAX nodes.
21881 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21882   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21883
21884   // Only perform optimizations if UnsafeMath is used.
21885   if (!DAG.getTarget().Options.UnsafeFPMath)
21886     return SDValue();
21887
21888   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21889   // into FMINC and FMAXC, which are Commutative operations.
21890   unsigned NewOp = 0;
21891   switch (N->getOpcode()) {
21892     default: llvm_unreachable("unknown opcode");
21893     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
21894     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
21895   }
21896
21897   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21898                      N->getOperand(0), N->getOperand(1));
21899 }
21900
21901 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21902 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21903   // FAND(0.0, x) -> 0.0
21904   // FAND(x, 0.0) -> 0.0
21905   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21906     if (C->getValueAPF().isPosZero())
21907       return N->getOperand(0);
21908   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21909     if (C->getValueAPF().isPosZero())
21910       return N->getOperand(1);
21911   return SDValue();
21912 }
21913
21914 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21915 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21916   // FANDN(x, 0.0) -> 0.0
21917   // FANDN(0.0, x) -> x
21918   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21919     if (C->getValueAPF().isPosZero())
21920       return N->getOperand(1);
21921   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21922     if (C->getValueAPF().isPosZero())
21923       return N->getOperand(1);
21924   return SDValue();
21925 }
21926
21927 static SDValue PerformBTCombine(SDNode *N,
21928                                 SelectionDAG &DAG,
21929                                 TargetLowering::DAGCombinerInfo &DCI) {
21930   // BT ignores high bits in the bit index operand.
21931   SDValue Op1 = N->getOperand(1);
21932   if (Op1.hasOneUse()) {
21933     unsigned BitWidth = Op1.getValueSizeInBits();
21934     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21935     APInt KnownZero, KnownOne;
21936     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21937                                           !DCI.isBeforeLegalizeOps());
21938     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21939     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21940         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21941       DCI.CommitTargetLoweringOpt(TLO);
21942   }
21943   return SDValue();
21944 }
21945
21946 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21947   SDValue Op = N->getOperand(0);
21948   if (Op.getOpcode() == ISD::BITCAST)
21949     Op = Op.getOperand(0);
21950   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21951   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21952       VT.getVectorElementType().getSizeInBits() ==
21953       OpVT.getVectorElementType().getSizeInBits()) {
21954     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21955   }
21956   return SDValue();
21957 }
21958
21959 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21960                                                const X86Subtarget *Subtarget) {
21961   EVT VT = N->getValueType(0);
21962   if (!VT.isVector())
21963     return SDValue();
21964
21965   SDValue N0 = N->getOperand(0);
21966   SDValue N1 = N->getOperand(1);
21967   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21968   SDLoc dl(N);
21969
21970   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21971   // both SSE and AVX2 since there is no sign-extended shift right
21972   // operation on a vector with 64-bit elements.
21973   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21974   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21975   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21976       N0.getOpcode() == ISD::SIGN_EXTEND)) {
21977     SDValue N00 = N0.getOperand(0);
21978
21979     // EXTLOAD has a better solution on AVX2,
21980     // it may be replaced with X86ISD::VSEXT node.
21981     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21982       if (!ISD::isNormalLoad(N00.getNode()))
21983         return SDValue();
21984
21985     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21986         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21987                                   N00, N1);
21988       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21989     }
21990   }
21991   return SDValue();
21992 }
21993
21994 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21995                                   TargetLowering::DAGCombinerInfo &DCI,
21996                                   const X86Subtarget *Subtarget) {
21997   if (!DCI.isBeforeLegalizeOps())
21998     return SDValue();
21999
22000   if (!Subtarget->hasFp256())
22001     return SDValue();
22002
22003   EVT VT = N->getValueType(0);
22004   if (VT.isVector() && VT.getSizeInBits() == 256) {
22005     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22006     if (R.getNode())
22007       return R;
22008   }
22009
22010   return SDValue();
22011 }
22012
22013 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22014                                  const X86Subtarget* Subtarget) {
22015   SDLoc dl(N);
22016   EVT VT = N->getValueType(0);
22017
22018   // Let legalize expand this if it isn't a legal type yet.
22019   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22020     return SDValue();
22021
22022   EVT ScalarVT = VT.getScalarType();
22023   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22024       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22025     return SDValue();
22026
22027   SDValue A = N->getOperand(0);
22028   SDValue B = N->getOperand(1);
22029   SDValue C = N->getOperand(2);
22030
22031   bool NegA = (A.getOpcode() == ISD::FNEG);
22032   bool NegB = (B.getOpcode() == ISD::FNEG);
22033   bool NegC = (C.getOpcode() == ISD::FNEG);
22034
22035   // Negative multiplication when NegA xor NegB
22036   bool NegMul = (NegA != NegB);
22037   if (NegA)
22038     A = A.getOperand(0);
22039   if (NegB)
22040     B = B.getOperand(0);
22041   if (NegC)
22042     C = C.getOperand(0);
22043
22044   unsigned Opcode;
22045   if (!NegMul)
22046     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22047   else
22048     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22049
22050   return DAG.getNode(Opcode, dl, VT, A, B, C);
22051 }
22052
22053 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22054                                   TargetLowering::DAGCombinerInfo &DCI,
22055                                   const X86Subtarget *Subtarget) {
22056   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22057   //           (and (i32 x86isd::setcc_carry), 1)
22058   // This eliminates the zext. This transformation is necessary because
22059   // ISD::SETCC is always legalized to i8.
22060   SDLoc dl(N);
22061   SDValue N0 = N->getOperand(0);
22062   EVT VT = N->getValueType(0);
22063
22064   if (N0.getOpcode() == ISD::AND &&
22065       N0.hasOneUse() &&
22066       N0.getOperand(0).hasOneUse()) {
22067     SDValue N00 = N0.getOperand(0);
22068     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22069       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22070       if (!C || C->getZExtValue() != 1)
22071         return SDValue();
22072       return DAG.getNode(ISD::AND, dl, VT,
22073                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22074                                      N00.getOperand(0), N00.getOperand(1)),
22075                          DAG.getConstant(1, VT));
22076     }
22077   }
22078
22079   if (N0.getOpcode() == ISD::TRUNCATE &&
22080       N0.hasOneUse() &&
22081       N0.getOperand(0).hasOneUse()) {
22082     SDValue N00 = N0.getOperand(0);
22083     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22084       return DAG.getNode(ISD::AND, dl, VT,
22085                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22086                                      N00.getOperand(0), N00.getOperand(1)),
22087                          DAG.getConstant(1, VT));
22088     }
22089   }
22090   if (VT.is256BitVector()) {
22091     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22092     if (R.getNode())
22093       return R;
22094   }
22095
22096   return SDValue();
22097 }
22098
22099 // Optimize x == -y --> x+y == 0
22100 //          x != -y --> x+y != 0
22101 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22102                                       const X86Subtarget* Subtarget) {
22103   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22104   SDValue LHS = N->getOperand(0);
22105   SDValue RHS = N->getOperand(1);
22106   EVT VT = N->getValueType(0);
22107   SDLoc DL(N);
22108
22109   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22110     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22111       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22112         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22113                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22114         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22115                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22116       }
22117   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22118     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22119       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22120         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22121                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22122         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22123                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22124       }
22125
22126   if (VT.getScalarType() == MVT::i1) {
22127     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22128       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22129     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22130     if (!IsSEXT0 && !IsVZero0)
22131       return SDValue();
22132     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22133       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22134     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22135
22136     if (!IsSEXT1 && !IsVZero1)
22137       return SDValue();
22138
22139     if (IsSEXT0 && IsVZero1) {
22140       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22141       if (CC == ISD::SETEQ)
22142         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22143       return LHS.getOperand(0);
22144     }
22145     if (IsSEXT1 && IsVZero0) {
22146       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22147       if (CC == ISD::SETEQ)
22148         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22149       return RHS.getOperand(0);
22150     }
22151   }
22152
22153   return SDValue();
22154 }
22155
22156 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22157                                       const X86Subtarget *Subtarget) {
22158   SDLoc dl(N);
22159   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22160   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22161          "X86insertps is only defined for v4x32");
22162
22163   SDValue Ld = N->getOperand(1);
22164   if (MayFoldLoad(Ld)) {
22165     // Extract the countS bits from the immediate so we can get the proper
22166     // address when narrowing the vector load to a specific element.
22167     // When the second source op is a memory address, interps doesn't use
22168     // countS and just gets an f32 from that address.
22169     unsigned DestIndex =
22170         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22171     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22172   } else
22173     return SDValue();
22174
22175   // Create this as a scalar to vector to match the instruction pattern.
22176   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22177   // countS bits are ignored when loading from memory on insertps, which
22178   // means we don't need to explicitly set them to 0.
22179   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22180                      LoadScalarToVector, N->getOperand(2));
22181 }
22182
22183 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22184 // as "sbb reg,reg", since it can be extended without zext and produces
22185 // an all-ones bit which is more useful than 0/1 in some cases.
22186 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22187                                MVT VT) {
22188   if (VT == MVT::i8)
22189     return DAG.getNode(ISD::AND, DL, VT,
22190                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22191                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22192                        DAG.getConstant(1, VT));
22193   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22194   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22195                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22196                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22197 }
22198
22199 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22200 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22201                                    TargetLowering::DAGCombinerInfo &DCI,
22202                                    const X86Subtarget *Subtarget) {
22203   SDLoc DL(N);
22204   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22205   SDValue EFLAGS = N->getOperand(1);
22206
22207   if (CC == X86::COND_A) {
22208     // Try to convert COND_A into COND_B in an attempt to facilitate
22209     // materializing "setb reg".
22210     //
22211     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22212     // cannot take an immediate as its first operand.
22213     //
22214     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22215         EFLAGS.getValueType().isInteger() &&
22216         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22217       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22218                                    EFLAGS.getNode()->getVTList(),
22219                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22220       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22221       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22222     }
22223   }
22224
22225   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22226   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22227   // cases.
22228   if (CC == X86::COND_B)
22229     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22230
22231   SDValue Flags;
22232
22233   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22234   if (Flags.getNode()) {
22235     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22236     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22237   }
22238
22239   return SDValue();
22240 }
22241
22242 // Optimize branch condition evaluation.
22243 //
22244 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22245                                     TargetLowering::DAGCombinerInfo &DCI,
22246                                     const X86Subtarget *Subtarget) {
22247   SDLoc DL(N);
22248   SDValue Chain = N->getOperand(0);
22249   SDValue Dest = N->getOperand(1);
22250   SDValue EFLAGS = N->getOperand(3);
22251   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22252
22253   SDValue Flags;
22254
22255   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22256   if (Flags.getNode()) {
22257     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22258     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22259                        Flags);
22260   }
22261
22262   return SDValue();
22263 }
22264
22265 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22266                                                          SelectionDAG &DAG) {
22267   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22268   // optimize away operation when it's from a constant.
22269   //
22270   // The general transformation is:
22271   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22272   //       AND(VECTOR_CMP(x,y), constant2)
22273   //    constant2 = UNARYOP(constant)
22274
22275   // Early exit if this isn't a vector operation, the operand of the
22276   // unary operation isn't a bitwise AND, or if the sizes of the operations
22277   // aren't the same.
22278   EVT VT = N->getValueType(0);
22279   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22280       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22281       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22282     return SDValue();
22283
22284   // Now check that the other operand of the AND is a constant. We could
22285   // make the transformation for non-constant splats as well, but it's unclear
22286   // that would be a benefit as it would not eliminate any operations, just
22287   // perform one more step in scalar code before moving to the vector unit.
22288   if (BuildVectorSDNode *BV =
22289           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22290     // Bail out if the vector isn't a constant.
22291     if (!BV->isConstant())
22292       return SDValue();
22293
22294     // Everything checks out. Build up the new and improved node.
22295     SDLoc DL(N);
22296     EVT IntVT = BV->getValueType(0);
22297     // Create a new constant of the appropriate type for the transformed
22298     // DAG.
22299     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22300     // The AND node needs bitcasts to/from an integer vector type around it.
22301     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22302     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22303                                  N->getOperand(0)->getOperand(0), MaskConst);
22304     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22305     return Res;
22306   }
22307
22308   return SDValue();
22309 }
22310
22311 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22312                                         const X86TargetLowering *XTLI) {
22313   // First try to optimize away the conversion entirely when it's
22314   // conditionally from a constant. Vectors only.
22315   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22316   if (Res != SDValue())
22317     return Res;
22318
22319   // Now move on to more general possibilities.
22320   SDValue Op0 = N->getOperand(0);
22321   EVT InVT = Op0->getValueType(0);
22322
22323   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22324   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22325     SDLoc dl(N);
22326     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22327     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22328     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22329   }
22330
22331   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22332   // a 32-bit target where SSE doesn't support i64->FP operations.
22333   if (Op0.getOpcode() == ISD::LOAD) {
22334     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22335     EVT VT = Ld->getValueType(0);
22336     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22337         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22338         !XTLI->getSubtarget()->is64Bit() &&
22339         VT == MVT::i64) {
22340       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22341                                           Ld->getChain(), Op0, DAG);
22342       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22343       return FILDChain;
22344     }
22345   }
22346   return SDValue();
22347 }
22348
22349 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22350 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22351                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22352   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22353   // the result is either zero or one (depending on the input carry bit).
22354   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22355   if (X86::isZeroNode(N->getOperand(0)) &&
22356       X86::isZeroNode(N->getOperand(1)) &&
22357       // We don't have a good way to replace an EFLAGS use, so only do this when
22358       // dead right now.
22359       SDValue(N, 1).use_empty()) {
22360     SDLoc DL(N);
22361     EVT VT = N->getValueType(0);
22362     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22363     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22364                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22365                                            DAG.getConstant(X86::COND_B,MVT::i8),
22366                                            N->getOperand(2)),
22367                                DAG.getConstant(1, VT));
22368     return DCI.CombineTo(N, Res1, CarryOut);
22369   }
22370
22371   return SDValue();
22372 }
22373
22374 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22375 //      (add Y, (setne X, 0)) -> sbb -1, Y
22376 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22377 //      (sub (setne X, 0), Y) -> adc -1, Y
22378 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22379   SDLoc DL(N);
22380
22381   // Look through ZExts.
22382   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22383   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22384     return SDValue();
22385
22386   SDValue SetCC = Ext.getOperand(0);
22387   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22388     return SDValue();
22389
22390   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22391   if (CC != X86::COND_E && CC != X86::COND_NE)
22392     return SDValue();
22393
22394   SDValue Cmp = SetCC.getOperand(1);
22395   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22396       !X86::isZeroNode(Cmp.getOperand(1)) ||
22397       !Cmp.getOperand(0).getValueType().isInteger())
22398     return SDValue();
22399
22400   SDValue CmpOp0 = Cmp.getOperand(0);
22401   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22402                                DAG.getConstant(1, CmpOp0.getValueType()));
22403
22404   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22405   if (CC == X86::COND_NE)
22406     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22407                        DL, OtherVal.getValueType(), OtherVal,
22408                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22409   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22410                      DL, OtherVal.getValueType(), OtherVal,
22411                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22412 }
22413
22414 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22415 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22416                                  const X86Subtarget *Subtarget) {
22417   EVT VT = N->getValueType(0);
22418   SDValue Op0 = N->getOperand(0);
22419   SDValue Op1 = N->getOperand(1);
22420
22421   // Try to synthesize horizontal adds from adds of shuffles.
22422   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22423        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22424       isHorizontalBinOp(Op0, Op1, true))
22425     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22426
22427   return OptimizeConditionalInDecrement(N, DAG);
22428 }
22429
22430 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22431                                  const X86Subtarget *Subtarget) {
22432   SDValue Op0 = N->getOperand(0);
22433   SDValue Op1 = N->getOperand(1);
22434
22435   // X86 can't encode an immediate LHS of a sub. See if we can push the
22436   // negation into a preceding instruction.
22437   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22438     // If the RHS of the sub is a XOR with one use and a constant, invert the
22439     // immediate. Then add one to the LHS of the sub so we can turn
22440     // X-Y -> X+~Y+1, saving one register.
22441     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22442         isa<ConstantSDNode>(Op1.getOperand(1))) {
22443       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22444       EVT VT = Op0.getValueType();
22445       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22446                                    Op1.getOperand(0),
22447                                    DAG.getConstant(~XorC, VT));
22448       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22449                          DAG.getConstant(C->getAPIntValue()+1, VT));
22450     }
22451   }
22452
22453   // Try to synthesize horizontal adds from adds of shuffles.
22454   EVT VT = N->getValueType(0);
22455   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22456        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22457       isHorizontalBinOp(Op0, Op1, true))
22458     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22459
22460   return OptimizeConditionalInDecrement(N, DAG);
22461 }
22462
22463 /// performVZEXTCombine - Performs build vector combines
22464 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22465                                         TargetLowering::DAGCombinerInfo &DCI,
22466                                         const X86Subtarget *Subtarget) {
22467   // (vzext (bitcast (vzext (x)) -> (vzext x)
22468   SDValue In = N->getOperand(0);
22469   while (In.getOpcode() == ISD::BITCAST)
22470     In = In.getOperand(0);
22471
22472   if (In.getOpcode() != X86ISD::VZEXT)
22473     return SDValue();
22474
22475   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22476                      In.getOperand(0));
22477 }
22478
22479 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22480                                              DAGCombinerInfo &DCI) const {
22481   SelectionDAG &DAG = DCI.DAG;
22482   switch (N->getOpcode()) {
22483   default: break;
22484   case ISD::EXTRACT_VECTOR_ELT:
22485     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22486   case ISD::VSELECT:
22487   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22488   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22489   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22490   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22491   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22492   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22493   case ISD::SHL:
22494   case ISD::SRA:
22495   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22496   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22497   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22498   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22499   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22500   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22501   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22502   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22503   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22504   case X86ISD::FXOR:
22505   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22506   case X86ISD::FMIN:
22507   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22508   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22509   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22510   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22511   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22512   case ISD::ANY_EXTEND:
22513   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22514   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22515   case ISD::SIGN_EXTEND_INREG:
22516     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22517   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22518   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22519   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22520   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22521   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22522   case X86ISD::SHUFP:       // Handle all target specific shuffles
22523   case X86ISD::PALIGNR:
22524   case X86ISD::UNPCKH:
22525   case X86ISD::UNPCKL:
22526   case X86ISD::MOVHLPS:
22527   case X86ISD::MOVLHPS:
22528   case X86ISD::PSHUFB:
22529   case X86ISD::PSHUFD:
22530   case X86ISD::PSHUFHW:
22531   case X86ISD::PSHUFLW:
22532   case X86ISD::MOVSS:
22533   case X86ISD::MOVSD:
22534   case X86ISD::VPERMILP:
22535   case X86ISD::VPERM2X128:
22536   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22537   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22538   case ISD::INTRINSIC_WO_CHAIN:
22539     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22540   case X86ISD::INSERTPS:
22541     return PerformINSERTPSCombine(N, DAG, Subtarget);
22542   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22543   }
22544
22545   return SDValue();
22546 }
22547
22548 /// isTypeDesirableForOp - Return true if the target has native support for
22549 /// the specified value type and it is 'desirable' to use the type for the
22550 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22551 /// instruction encodings are longer and some i16 instructions are slow.
22552 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22553   if (!isTypeLegal(VT))
22554     return false;
22555   if (VT != MVT::i16)
22556     return true;
22557
22558   switch (Opc) {
22559   default:
22560     return true;
22561   case ISD::LOAD:
22562   case ISD::SIGN_EXTEND:
22563   case ISD::ZERO_EXTEND:
22564   case ISD::ANY_EXTEND:
22565   case ISD::SHL:
22566   case ISD::SRL:
22567   case ISD::SUB:
22568   case ISD::ADD:
22569   case ISD::MUL:
22570   case ISD::AND:
22571   case ISD::OR:
22572   case ISD::XOR:
22573     return false;
22574   }
22575 }
22576
22577 /// IsDesirableToPromoteOp - This method query the target whether it is
22578 /// beneficial for dag combiner to promote the specified node. If true, it
22579 /// should return the desired promotion type by reference.
22580 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22581   EVT VT = Op.getValueType();
22582   if (VT != MVT::i16)
22583     return false;
22584
22585   bool Promote = false;
22586   bool Commute = false;
22587   switch (Op.getOpcode()) {
22588   default: break;
22589   case ISD::LOAD: {
22590     LoadSDNode *LD = cast<LoadSDNode>(Op);
22591     // If the non-extending load has a single use and it's not live out, then it
22592     // might be folded.
22593     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22594                                                      Op.hasOneUse()*/) {
22595       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22596              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22597         // The only case where we'd want to promote LOAD (rather then it being
22598         // promoted as an operand is when it's only use is liveout.
22599         if (UI->getOpcode() != ISD::CopyToReg)
22600           return false;
22601       }
22602     }
22603     Promote = true;
22604     break;
22605   }
22606   case ISD::SIGN_EXTEND:
22607   case ISD::ZERO_EXTEND:
22608   case ISD::ANY_EXTEND:
22609     Promote = true;
22610     break;
22611   case ISD::SHL:
22612   case ISD::SRL: {
22613     SDValue N0 = Op.getOperand(0);
22614     // Look out for (store (shl (load), x)).
22615     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22616       return false;
22617     Promote = true;
22618     break;
22619   }
22620   case ISD::ADD:
22621   case ISD::MUL:
22622   case ISD::AND:
22623   case ISD::OR:
22624   case ISD::XOR:
22625     Commute = true;
22626     // fallthrough
22627   case ISD::SUB: {
22628     SDValue N0 = Op.getOperand(0);
22629     SDValue N1 = Op.getOperand(1);
22630     if (!Commute && MayFoldLoad(N1))
22631       return false;
22632     // Avoid disabling potential load folding opportunities.
22633     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22634       return false;
22635     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22636       return false;
22637     Promote = true;
22638   }
22639   }
22640
22641   PVT = MVT::i32;
22642   return Promote;
22643 }
22644
22645 //===----------------------------------------------------------------------===//
22646 //                           X86 Inline Assembly Support
22647 //===----------------------------------------------------------------------===//
22648
22649 namespace {
22650   // Helper to match a string separated by whitespace.
22651   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22652     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22653
22654     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22655       StringRef piece(*args[i]);
22656       if (!s.startswith(piece)) // Check if the piece matches.
22657         return false;
22658
22659       s = s.substr(piece.size());
22660       StringRef::size_type pos = s.find_first_not_of(" \t");
22661       if (pos == 0) // We matched a prefix.
22662         return false;
22663
22664       s = s.substr(pos);
22665     }
22666
22667     return s.empty();
22668   }
22669   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22670 }
22671
22672 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22673
22674   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22675     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22676         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22677         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22678
22679       if (AsmPieces.size() == 3)
22680         return true;
22681       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22682         return true;
22683     }
22684   }
22685   return false;
22686 }
22687
22688 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22689   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22690
22691   std::string AsmStr = IA->getAsmString();
22692
22693   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22694   if (!Ty || Ty->getBitWidth() % 16 != 0)
22695     return false;
22696
22697   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22698   SmallVector<StringRef, 4> AsmPieces;
22699   SplitString(AsmStr, AsmPieces, ";\n");
22700
22701   switch (AsmPieces.size()) {
22702   default: return false;
22703   case 1:
22704     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22705     // we will turn this bswap into something that will be lowered to logical
22706     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22707     // lower so don't worry about this.
22708     // bswap $0
22709     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22710         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22711         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22712         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22713         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22714         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22715       // No need to check constraints, nothing other than the equivalent of
22716       // "=r,0" would be valid here.
22717       return IntrinsicLowering::LowerToByteSwap(CI);
22718     }
22719
22720     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22721     if (CI->getType()->isIntegerTy(16) &&
22722         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22723         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22724          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22725       AsmPieces.clear();
22726       const std::string &ConstraintsStr = IA->getConstraintString();
22727       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22728       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22729       if (clobbersFlagRegisters(AsmPieces))
22730         return IntrinsicLowering::LowerToByteSwap(CI);
22731     }
22732     break;
22733   case 3:
22734     if (CI->getType()->isIntegerTy(32) &&
22735         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22736         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22737         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22738         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22739       AsmPieces.clear();
22740       const std::string &ConstraintsStr = IA->getConstraintString();
22741       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22742       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22743       if (clobbersFlagRegisters(AsmPieces))
22744         return IntrinsicLowering::LowerToByteSwap(CI);
22745     }
22746
22747     if (CI->getType()->isIntegerTy(64)) {
22748       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22749       if (Constraints.size() >= 2 &&
22750           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22751           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22752         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22753         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22754             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22755             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22756           return IntrinsicLowering::LowerToByteSwap(CI);
22757       }
22758     }
22759     break;
22760   }
22761   return false;
22762 }
22763
22764 /// getConstraintType - Given a constraint letter, return the type of
22765 /// constraint it is for this target.
22766 X86TargetLowering::ConstraintType
22767 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22768   if (Constraint.size() == 1) {
22769     switch (Constraint[0]) {
22770     case 'R':
22771     case 'q':
22772     case 'Q':
22773     case 'f':
22774     case 't':
22775     case 'u':
22776     case 'y':
22777     case 'x':
22778     case 'Y':
22779     case 'l':
22780       return C_RegisterClass;
22781     case 'a':
22782     case 'b':
22783     case 'c':
22784     case 'd':
22785     case 'S':
22786     case 'D':
22787     case 'A':
22788       return C_Register;
22789     case 'I':
22790     case 'J':
22791     case 'K':
22792     case 'L':
22793     case 'M':
22794     case 'N':
22795     case 'G':
22796     case 'C':
22797     case 'e':
22798     case 'Z':
22799       return C_Other;
22800     default:
22801       break;
22802     }
22803   }
22804   return TargetLowering::getConstraintType(Constraint);
22805 }
22806
22807 /// Examine constraint type and operand type and determine a weight value.
22808 /// This object must already have been set up with the operand type
22809 /// and the current alternative constraint selected.
22810 TargetLowering::ConstraintWeight
22811   X86TargetLowering::getSingleConstraintMatchWeight(
22812     AsmOperandInfo &info, const char *constraint) const {
22813   ConstraintWeight weight = CW_Invalid;
22814   Value *CallOperandVal = info.CallOperandVal;
22815     // If we don't have a value, we can't do a match,
22816     // but allow it at the lowest weight.
22817   if (!CallOperandVal)
22818     return CW_Default;
22819   Type *type = CallOperandVal->getType();
22820   // Look at the constraint type.
22821   switch (*constraint) {
22822   default:
22823     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22824   case 'R':
22825   case 'q':
22826   case 'Q':
22827   case 'a':
22828   case 'b':
22829   case 'c':
22830   case 'd':
22831   case 'S':
22832   case 'D':
22833   case 'A':
22834     if (CallOperandVal->getType()->isIntegerTy())
22835       weight = CW_SpecificReg;
22836     break;
22837   case 'f':
22838   case 't':
22839   case 'u':
22840     if (type->isFloatingPointTy())
22841       weight = CW_SpecificReg;
22842     break;
22843   case 'y':
22844     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22845       weight = CW_SpecificReg;
22846     break;
22847   case 'x':
22848   case 'Y':
22849     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22850         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22851       weight = CW_Register;
22852     break;
22853   case 'I':
22854     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22855       if (C->getZExtValue() <= 31)
22856         weight = CW_Constant;
22857     }
22858     break;
22859   case 'J':
22860     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22861       if (C->getZExtValue() <= 63)
22862         weight = CW_Constant;
22863     }
22864     break;
22865   case 'K':
22866     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22867       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22868         weight = CW_Constant;
22869     }
22870     break;
22871   case 'L':
22872     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22873       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22874         weight = CW_Constant;
22875     }
22876     break;
22877   case 'M':
22878     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22879       if (C->getZExtValue() <= 3)
22880         weight = CW_Constant;
22881     }
22882     break;
22883   case 'N':
22884     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22885       if (C->getZExtValue() <= 0xff)
22886         weight = CW_Constant;
22887     }
22888     break;
22889   case 'G':
22890   case 'C':
22891     if (dyn_cast<ConstantFP>(CallOperandVal)) {
22892       weight = CW_Constant;
22893     }
22894     break;
22895   case 'e':
22896     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22897       if ((C->getSExtValue() >= -0x80000000LL) &&
22898           (C->getSExtValue() <= 0x7fffffffLL))
22899         weight = CW_Constant;
22900     }
22901     break;
22902   case 'Z':
22903     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22904       if (C->getZExtValue() <= 0xffffffff)
22905         weight = CW_Constant;
22906     }
22907     break;
22908   }
22909   return weight;
22910 }
22911
22912 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22913 /// with another that has more specific requirements based on the type of the
22914 /// corresponding operand.
22915 const char *X86TargetLowering::
22916 LowerXConstraint(EVT ConstraintVT) const {
22917   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22918   // 'f' like normal targets.
22919   if (ConstraintVT.isFloatingPoint()) {
22920     if (Subtarget->hasSSE2())
22921       return "Y";
22922     if (Subtarget->hasSSE1())
22923       return "x";
22924   }
22925
22926   return TargetLowering::LowerXConstraint(ConstraintVT);
22927 }
22928
22929 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22930 /// vector.  If it is invalid, don't add anything to Ops.
22931 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22932                                                      std::string &Constraint,
22933                                                      std::vector<SDValue>&Ops,
22934                                                      SelectionDAG &DAG) const {
22935   SDValue Result;
22936
22937   // Only support length 1 constraints for now.
22938   if (Constraint.length() > 1) return;
22939
22940   char ConstraintLetter = Constraint[0];
22941   switch (ConstraintLetter) {
22942   default: break;
22943   case 'I':
22944     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22945       if (C->getZExtValue() <= 31) {
22946         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22947         break;
22948       }
22949     }
22950     return;
22951   case 'J':
22952     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22953       if (C->getZExtValue() <= 63) {
22954         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22955         break;
22956       }
22957     }
22958     return;
22959   case 'K':
22960     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22961       if (isInt<8>(C->getSExtValue())) {
22962         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22963         break;
22964       }
22965     }
22966     return;
22967   case 'N':
22968     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22969       if (C->getZExtValue() <= 255) {
22970         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22971         break;
22972       }
22973     }
22974     return;
22975   case 'e': {
22976     // 32-bit signed value
22977     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22978       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22979                                            C->getSExtValue())) {
22980         // Widen to 64 bits here to get it sign extended.
22981         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22982         break;
22983       }
22984     // FIXME gcc accepts some relocatable values here too, but only in certain
22985     // memory models; it's complicated.
22986     }
22987     return;
22988   }
22989   case 'Z': {
22990     // 32-bit unsigned value
22991     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22992       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22993                                            C->getZExtValue())) {
22994         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22995         break;
22996       }
22997     }
22998     // FIXME gcc accepts some relocatable values here too, but only in certain
22999     // memory models; it's complicated.
23000     return;
23001   }
23002   case 'i': {
23003     // Literal immediates are always ok.
23004     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23005       // Widen to 64 bits here to get it sign extended.
23006       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23007       break;
23008     }
23009
23010     // In any sort of PIC mode addresses need to be computed at runtime by
23011     // adding in a register or some sort of table lookup.  These can't
23012     // be used as immediates.
23013     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23014       return;
23015
23016     // If we are in non-pic codegen mode, we allow the address of a global (with
23017     // an optional displacement) to be used with 'i'.
23018     GlobalAddressSDNode *GA = nullptr;
23019     int64_t Offset = 0;
23020
23021     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23022     while (1) {
23023       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23024         Offset += GA->getOffset();
23025         break;
23026       } else if (Op.getOpcode() == ISD::ADD) {
23027         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23028           Offset += C->getZExtValue();
23029           Op = Op.getOperand(0);
23030           continue;
23031         }
23032       } else if (Op.getOpcode() == ISD::SUB) {
23033         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23034           Offset += -C->getZExtValue();
23035           Op = Op.getOperand(0);
23036           continue;
23037         }
23038       }
23039
23040       // Otherwise, this isn't something we can handle, reject it.
23041       return;
23042     }
23043
23044     const GlobalValue *GV = GA->getGlobal();
23045     // If we require an extra load to get this address, as in PIC mode, we
23046     // can't accept it.
23047     if (isGlobalStubReference(
23048             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23049       return;
23050
23051     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23052                                         GA->getValueType(0), Offset);
23053     break;
23054   }
23055   }
23056
23057   if (Result.getNode()) {
23058     Ops.push_back(Result);
23059     return;
23060   }
23061   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23062 }
23063
23064 std::pair<unsigned, const TargetRegisterClass*>
23065 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23066                                                 MVT VT) const {
23067   // First, see if this is a constraint that directly corresponds to an LLVM
23068   // register class.
23069   if (Constraint.size() == 1) {
23070     // GCC Constraint Letters
23071     switch (Constraint[0]) {
23072     default: break;
23073       // TODO: Slight differences here in allocation order and leaving
23074       // RIP in the class. Do they matter any more here than they do
23075       // in the normal allocation?
23076     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23077       if (Subtarget->is64Bit()) {
23078         if (VT == MVT::i32 || VT == MVT::f32)
23079           return std::make_pair(0U, &X86::GR32RegClass);
23080         if (VT == MVT::i16)
23081           return std::make_pair(0U, &X86::GR16RegClass);
23082         if (VT == MVT::i8 || VT == MVT::i1)
23083           return std::make_pair(0U, &X86::GR8RegClass);
23084         if (VT == MVT::i64 || VT == MVT::f64)
23085           return std::make_pair(0U, &X86::GR64RegClass);
23086         break;
23087       }
23088       // 32-bit fallthrough
23089     case 'Q':   // Q_REGS
23090       if (VT == MVT::i32 || VT == MVT::f32)
23091         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23092       if (VT == MVT::i16)
23093         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23094       if (VT == MVT::i8 || VT == MVT::i1)
23095         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23096       if (VT == MVT::i64)
23097         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23098       break;
23099     case 'r':   // GENERAL_REGS
23100     case 'l':   // INDEX_REGS
23101       if (VT == MVT::i8 || VT == MVT::i1)
23102         return std::make_pair(0U, &X86::GR8RegClass);
23103       if (VT == MVT::i16)
23104         return std::make_pair(0U, &X86::GR16RegClass);
23105       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23106         return std::make_pair(0U, &X86::GR32RegClass);
23107       return std::make_pair(0U, &X86::GR64RegClass);
23108     case 'R':   // LEGACY_REGS
23109       if (VT == MVT::i8 || VT == MVT::i1)
23110         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23111       if (VT == MVT::i16)
23112         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23113       if (VT == MVT::i32 || !Subtarget->is64Bit())
23114         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23115       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23116     case 'f':  // FP Stack registers.
23117       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23118       // value to the correct fpstack register class.
23119       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23120         return std::make_pair(0U, &X86::RFP32RegClass);
23121       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23122         return std::make_pair(0U, &X86::RFP64RegClass);
23123       return std::make_pair(0U, &X86::RFP80RegClass);
23124     case 'y':   // MMX_REGS if MMX allowed.
23125       if (!Subtarget->hasMMX()) break;
23126       return std::make_pair(0U, &X86::VR64RegClass);
23127     case 'Y':   // SSE_REGS if SSE2 allowed
23128       if (!Subtarget->hasSSE2()) break;
23129       // FALL THROUGH.
23130     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23131       if (!Subtarget->hasSSE1()) break;
23132
23133       switch (VT.SimpleTy) {
23134       default: break;
23135       // Scalar SSE types.
23136       case MVT::f32:
23137       case MVT::i32:
23138         return std::make_pair(0U, &X86::FR32RegClass);
23139       case MVT::f64:
23140       case MVT::i64:
23141         return std::make_pair(0U, &X86::FR64RegClass);
23142       // Vector types.
23143       case MVT::v16i8:
23144       case MVT::v8i16:
23145       case MVT::v4i32:
23146       case MVT::v2i64:
23147       case MVT::v4f32:
23148       case MVT::v2f64:
23149         return std::make_pair(0U, &X86::VR128RegClass);
23150       // AVX types.
23151       case MVT::v32i8:
23152       case MVT::v16i16:
23153       case MVT::v8i32:
23154       case MVT::v4i64:
23155       case MVT::v8f32:
23156       case MVT::v4f64:
23157         return std::make_pair(0U, &X86::VR256RegClass);
23158       case MVT::v8f64:
23159       case MVT::v16f32:
23160       case MVT::v16i32:
23161       case MVT::v8i64:
23162         return std::make_pair(0U, &X86::VR512RegClass);
23163       }
23164       break;
23165     }
23166   }
23167
23168   // Use the default implementation in TargetLowering to convert the register
23169   // constraint into a member of a register class.
23170   std::pair<unsigned, const TargetRegisterClass*> Res;
23171   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23172
23173   // Not found as a standard register?
23174   if (!Res.second) {
23175     // Map st(0) -> st(7) -> ST0
23176     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23177         tolower(Constraint[1]) == 's' &&
23178         tolower(Constraint[2]) == 't' &&
23179         Constraint[3] == '(' &&
23180         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23181         Constraint[5] == ')' &&
23182         Constraint[6] == '}') {
23183
23184       Res.first = X86::FP0+Constraint[4]-'0';
23185       Res.second = &X86::RFP80RegClass;
23186       return Res;
23187     }
23188
23189     // GCC allows "st(0)" to be called just plain "st".
23190     if (StringRef("{st}").equals_lower(Constraint)) {
23191       Res.first = X86::FP0;
23192       Res.second = &X86::RFP80RegClass;
23193       return Res;
23194     }
23195
23196     // flags -> EFLAGS
23197     if (StringRef("{flags}").equals_lower(Constraint)) {
23198       Res.first = X86::EFLAGS;
23199       Res.second = &X86::CCRRegClass;
23200       return Res;
23201     }
23202
23203     // 'A' means EAX + EDX.
23204     if (Constraint == "A") {
23205       Res.first = X86::EAX;
23206       Res.second = &X86::GR32_ADRegClass;
23207       return Res;
23208     }
23209     return Res;
23210   }
23211
23212   // Otherwise, check to see if this is a register class of the wrong value
23213   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23214   // turn into {ax},{dx}.
23215   if (Res.second->hasType(VT))
23216     return Res;   // Correct type already, nothing to do.
23217
23218   // All of the single-register GCC register classes map their values onto
23219   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23220   // really want an 8-bit or 32-bit register, map to the appropriate register
23221   // class and return the appropriate register.
23222   if (Res.second == &X86::GR16RegClass) {
23223     if (VT == MVT::i8 || VT == MVT::i1) {
23224       unsigned DestReg = 0;
23225       switch (Res.first) {
23226       default: break;
23227       case X86::AX: DestReg = X86::AL; break;
23228       case X86::DX: DestReg = X86::DL; break;
23229       case X86::CX: DestReg = X86::CL; break;
23230       case X86::BX: DestReg = X86::BL; break;
23231       }
23232       if (DestReg) {
23233         Res.first = DestReg;
23234         Res.second = &X86::GR8RegClass;
23235       }
23236     } else if (VT == MVT::i32 || VT == MVT::f32) {
23237       unsigned DestReg = 0;
23238       switch (Res.first) {
23239       default: break;
23240       case X86::AX: DestReg = X86::EAX; break;
23241       case X86::DX: DestReg = X86::EDX; break;
23242       case X86::CX: DestReg = X86::ECX; break;
23243       case X86::BX: DestReg = X86::EBX; break;
23244       case X86::SI: DestReg = X86::ESI; break;
23245       case X86::DI: DestReg = X86::EDI; break;
23246       case X86::BP: DestReg = X86::EBP; break;
23247       case X86::SP: DestReg = X86::ESP; break;
23248       }
23249       if (DestReg) {
23250         Res.first = DestReg;
23251         Res.second = &X86::GR32RegClass;
23252       }
23253     } else if (VT == MVT::i64 || VT == MVT::f64) {
23254       unsigned DestReg = 0;
23255       switch (Res.first) {
23256       default: break;
23257       case X86::AX: DestReg = X86::RAX; break;
23258       case X86::DX: DestReg = X86::RDX; break;
23259       case X86::CX: DestReg = X86::RCX; break;
23260       case X86::BX: DestReg = X86::RBX; break;
23261       case X86::SI: DestReg = X86::RSI; break;
23262       case X86::DI: DestReg = X86::RDI; break;
23263       case X86::BP: DestReg = X86::RBP; break;
23264       case X86::SP: DestReg = X86::RSP; break;
23265       }
23266       if (DestReg) {
23267         Res.first = DestReg;
23268         Res.second = &X86::GR64RegClass;
23269       }
23270     }
23271   } else if (Res.second == &X86::FR32RegClass ||
23272              Res.second == &X86::FR64RegClass ||
23273              Res.second == &X86::VR128RegClass ||
23274              Res.second == &X86::VR256RegClass ||
23275              Res.second == &X86::FR32XRegClass ||
23276              Res.second == &X86::FR64XRegClass ||
23277              Res.second == &X86::VR128XRegClass ||
23278              Res.second == &X86::VR256XRegClass ||
23279              Res.second == &X86::VR512RegClass) {
23280     // Handle references to XMM physical registers that got mapped into the
23281     // wrong class.  This can happen with constraints like {xmm0} where the
23282     // target independent register mapper will just pick the first match it can
23283     // find, ignoring the required type.
23284
23285     if (VT == MVT::f32 || VT == MVT::i32)
23286       Res.second = &X86::FR32RegClass;
23287     else if (VT == MVT::f64 || VT == MVT::i64)
23288       Res.second = &X86::FR64RegClass;
23289     else if (X86::VR128RegClass.hasType(VT))
23290       Res.second = &X86::VR128RegClass;
23291     else if (X86::VR256RegClass.hasType(VT))
23292       Res.second = &X86::VR256RegClass;
23293     else if (X86::VR512RegClass.hasType(VT))
23294       Res.second = &X86::VR512RegClass;
23295   }
23296
23297   return Res;
23298 }
23299
23300 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23301                                             Type *Ty) const {
23302   // Scaling factors are not free at all.
23303   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23304   // will take 2 allocations in the out of order engine instead of 1
23305   // for plain addressing mode, i.e. inst (reg1).
23306   // E.g.,
23307   // vaddps (%rsi,%drx), %ymm0, %ymm1
23308   // Requires two allocations (one for the load, one for the computation)
23309   // whereas:
23310   // vaddps (%rsi), %ymm0, %ymm1
23311   // Requires just 1 allocation, i.e., freeing allocations for other operations
23312   // and having less micro operations to execute.
23313   //
23314   // For some X86 architectures, this is even worse because for instance for
23315   // stores, the complex addressing mode forces the instruction to use the
23316   // "load" ports instead of the dedicated "store" port.
23317   // E.g., on Haswell:
23318   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23319   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23320   if (isLegalAddressingMode(AM, Ty))
23321     // Scale represents reg2 * scale, thus account for 1
23322     // as soon as we use a second register.
23323     return AM.Scale != 0;
23324   return -1;
23325 }
23326
23327 bool X86TargetLowering::isTargetFTOL() const {
23328   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23329 }